content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System; using System.Text.Json; using System.Text.Json.Serialization; using Azure.Core; namespace Azure.Messaging.EventGrid.SystemEvents { [JsonConverter(typeof(AcsChatMessageEditedEventDataConverter))] public partial class AcsChatMessageEditedEventData { internal static AcsChatMessageEditedEventData DeserializeAcsChatMessageEditedEventData(JsonElement element) { Optional<string> messageBody = default; Optional<DateTimeOffset> editTime = default; Optional<string> messageId = default; Optional<CommunicationIdentifierModel> senderCommunicationIdentifier = default; Optional<string> senderDisplayName = default; Optional<DateTimeOffset> composeTime = default; Optional<string> type = default; Optional<long> version = default; Optional<CommunicationIdentifierModel> recipientCommunicationIdentifier = default; Optional<string> transactionId = default; Optional<string> threadId = default; foreach (var property in element.EnumerateObject()) { if (property.NameEquals("messageBody")) { messageBody = property.Value.GetString(); continue; } if (property.NameEquals("editTime")) { if (property.Value.ValueKind == JsonValueKind.Null) { property.ThrowNonNullablePropertyIsNull(); continue; } editTime = property.Value.GetDateTimeOffset("O"); continue; } if (property.NameEquals("messageId")) { messageId = property.Value.GetString(); continue; } if (property.NameEquals("senderCommunicationIdentifier")) { if (property.Value.ValueKind == JsonValueKind.Null) { property.ThrowNonNullablePropertyIsNull(); continue; } senderCommunicationIdentifier = CommunicationIdentifierModel.DeserializeCommunicationIdentifierModel(property.Value); continue; } if (property.NameEquals("senderDisplayName")) { senderDisplayName = property.Value.GetString(); continue; } if (property.NameEquals("composeTime")) { if (property.Value.ValueKind == JsonValueKind.Null) { property.ThrowNonNullablePropertyIsNull(); continue; } composeTime = property.Value.GetDateTimeOffset("O"); continue; } if (property.NameEquals("type")) { type = property.Value.GetString(); continue; } if (property.NameEquals("version")) { if (property.Value.ValueKind == JsonValueKind.Null) { property.ThrowNonNullablePropertyIsNull(); continue; } version = property.Value.GetInt64(); continue; } if (property.NameEquals("recipientCommunicationIdentifier")) { if (property.Value.ValueKind == JsonValueKind.Null) { property.ThrowNonNullablePropertyIsNull(); continue; } recipientCommunicationIdentifier = CommunicationIdentifierModel.DeserializeCommunicationIdentifierModel(property.Value); continue; } if (property.NameEquals("transactionId")) { transactionId = property.Value.GetString(); continue; } if (property.NameEquals("threadId")) { threadId = property.Value.GetString(); continue; } } return new AcsChatMessageEditedEventData(recipientCommunicationIdentifier.Value, transactionId.Value, threadId.Value, messageId.Value, senderCommunicationIdentifier.Value, senderDisplayName.Value, Optional.ToNullable(composeTime), type.Value, Optional.ToNullable(version), messageBody.Value, Optional.ToNullable(editTime)); } internal partial class AcsChatMessageEditedEventDataConverter : JsonConverter<AcsChatMessageEditedEventData> { public override void Write(Utf8JsonWriter writer, AcsChatMessageEditedEventData model, JsonSerializerOptions options) { writer.WriteObjectValue(model); } public override AcsChatMessageEditedEventData Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { using var document = JsonDocument.ParseValue(ref reader); return DeserializeAcsChatMessageEditedEventData(document.RootElement); } } } }
42.89313
335
0.544937
[ "MIT" ]
isra-fel/azure-sdk-for-net
sdk/eventgrid/Azure.Messaging.EventGrid/src/Generated/Models/AcsChatMessageEditedEventData.Serialization.cs
5,619
C#
// ███╗ ██╗ ██████╗ ████████╗██╗ ██████╗███████╗ // ████╗ ██║██╔═══██╗╚══██╔══╝██║██╔════╝██╔════╝ // ██╔██╗ ██║██║ ██║ ██║ ██║██║ █████╗ // ██║╚██╗██║██║ ██║ ██║ ██║██║ ██╔══╝ // ██║ ╚████║╚██████╔╝ ██║ ██║╚██████╗███████╗ // ╚═╝ ╚═══╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝╚══════╝ // ----------------------------------------------- // // This file is automatically generated // Please do not edit these files manually // Run the following in the root of the repos: // // *NIX : ./build.sh codegen // Windows : build.bat codegen // // ----------------------------------------------- // ReSharper disable RedundantUsingDirective using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Elasticsearch.Net; using static Elasticsearch.Net.HttpMethod; // ReSharper disable InterpolatedStringExpressionIsNotIFormattable // ReSharper disable once CheckNamespace // ReSharper disable InterpolatedStringExpressionIsNotIFormattable // ReSharper disable RedundantExtendsListEntry namespace Elasticsearch.Net.Specification.ClusterApi { ///<summary> /// Cluster APIs. /// <para>Not intended to be instantiated directly. Use the <see cref = "IElasticLowLevelClient.Cluster"/> property /// on <see cref = "IElasticLowLevelClient"/>. ///</para> ///</summary> public class LowLevelClusterNamespace : NamespacedClientProxy { internal LowLevelClusterNamespace(ElasticLowLevelClient client): base(client) { } ///<summary>POST on /_cluster/allocation/explain <para>https://www.elastic.co/guide/en/elasticsearch/reference/master/cluster-allocation-explain.html</para></summary> ///<param name = "body">The index, shard, and primary flag to explain. Empty means &#x27;explain the first unassigned shard&#x27;</param> ///<param name = "requestParameters">Request specific configuration such as querystring parameters &amp; request specific connection settings.</param> public TResponse AllocationExplain<TResponse>(PostData body, ClusterAllocationExplainRequestParameters requestParameters = null) where TResponse : class, IElasticsearchResponse, new() => DoRequest<TResponse>(POST, "_cluster/allocation/explain", body, RequestParams(requestParameters)); ///<summary>POST on /_cluster/allocation/explain <para>https://www.elastic.co/guide/en/elasticsearch/reference/master/cluster-allocation-explain.html</para></summary> ///<param name = "body">The index, shard, and primary flag to explain. Empty means &#x27;explain the first unassigned shard&#x27;</param> ///<param name = "requestParameters">Request specific configuration such as querystring parameters &amp; request specific connection settings.</param> [MapsApi("cluster.allocation_explain", "body")] public Task<TResponse> AllocationExplainAsync<TResponse>(PostData body, ClusterAllocationExplainRequestParameters requestParameters = null, CancellationToken ctx = default) where TResponse : class, IElasticsearchResponse, new() => DoRequestAsync<TResponse>(POST, "_cluster/allocation/explain", ctx, body, RequestParams(requestParameters)); ///<summary>DELETE on /_component_template/{name} <para>https://www.elastic.co/guide/en/elasticsearch/reference/master/indices-component-templates.html</para></summary> ///<param name = "name">The name of the template</param> ///<param name = "requestParameters">Request specific configuration such as querystring parameters &amp; request specific connection settings.</param> public TResponse DeleteComponentTemplate<TResponse>(string name, DeleteComponentTemplateRequestParameters requestParameters = null) where TResponse : class, IElasticsearchResponse, new() => DoRequest<TResponse>(DELETE, Url($"_component_template/{name:name}"), null, RequestParams(requestParameters)); ///<summary>DELETE on /_component_template/{name} <para>https://www.elastic.co/guide/en/elasticsearch/reference/master/indices-component-templates.html</para></summary> ///<param name = "name">The name of the template</param> ///<param name = "requestParameters">Request specific configuration such as querystring parameters &amp; request specific connection settings.</param> [MapsApi("cluster.delete_component_template", "name")] public Task<TResponse> DeleteComponentTemplateAsync<TResponse>(string name, DeleteComponentTemplateRequestParameters requestParameters = null, CancellationToken ctx = default) where TResponse : class, IElasticsearchResponse, new() => DoRequestAsync<TResponse>(DELETE, Url($"_component_template/{name:name}"), ctx, null, RequestParams(requestParameters)); ///<summary>GET on /_component_template <para>https://www.elastic.co/guide/en/elasticsearch/reference/master/indices-component-templates.html</para></summary> ///<param name = "requestParameters">Request specific configuration such as querystring parameters &amp; request specific connection settings.</param> public TResponse GetComponentTemplate<TResponse>(GetComponentTemplateRequestParameters requestParameters = null) where TResponse : class, IElasticsearchResponse, new() => DoRequest<TResponse>(GET, "_component_template", null, RequestParams(requestParameters)); ///<summary>GET on /_component_template <para>https://www.elastic.co/guide/en/elasticsearch/reference/master/indices-component-templates.html</para></summary> ///<param name = "requestParameters">Request specific configuration such as querystring parameters &amp; request specific connection settings.</param> [MapsApi("cluster.get_component_template", "")] public Task<TResponse> GetComponentTemplateAsync<TResponse>(GetComponentTemplateRequestParameters requestParameters = null, CancellationToken ctx = default) where TResponse : class, IElasticsearchResponse, new() => DoRequestAsync<TResponse>(GET, "_component_template", ctx, null, RequestParams(requestParameters)); ///<summary>GET on /_component_template/{name} <para>https://www.elastic.co/guide/en/elasticsearch/reference/master/indices-component-templates.html</para></summary> ///<param name = "name">The comma separated names of the component templates</param> ///<param name = "requestParameters">Request specific configuration such as querystring parameters &amp; request specific connection settings.</param> public TResponse GetComponentTemplate<TResponse>(string name, GetComponentTemplateRequestParameters requestParameters = null) where TResponse : class, IElasticsearchResponse, new() => DoRequest<TResponse>(GET, Url($"_component_template/{name:name}"), null, RequestParams(requestParameters)); ///<summary>GET on /_component_template/{name} <para>https://www.elastic.co/guide/en/elasticsearch/reference/master/indices-component-templates.html</para></summary> ///<param name = "name">The comma separated names of the component templates</param> ///<param name = "requestParameters">Request specific configuration such as querystring parameters &amp; request specific connection settings.</param> [MapsApi("cluster.get_component_template", "name")] public Task<TResponse> GetComponentTemplateAsync<TResponse>(string name, GetComponentTemplateRequestParameters requestParameters = null, CancellationToken ctx = default) where TResponse : class, IElasticsearchResponse, new() => DoRequestAsync<TResponse>(GET, Url($"_component_template/{name:name}"), ctx, null, RequestParams(requestParameters)); ///<summary>GET on /_cluster/settings <para>https://www.elastic.co/guide/en/elasticsearch/reference/master/cluster-update-settings.html</para></summary> ///<param name = "requestParameters">Request specific configuration such as querystring parameters &amp; request specific connection settings.</param> public TResponse GetSettings<TResponse>(ClusterGetSettingsRequestParameters requestParameters = null) where TResponse : class, IElasticsearchResponse, new() => DoRequest<TResponse>(GET, "_cluster/settings", null, RequestParams(requestParameters)); ///<summary>GET on /_cluster/settings <para>https://www.elastic.co/guide/en/elasticsearch/reference/master/cluster-update-settings.html</para></summary> ///<param name = "requestParameters">Request specific configuration such as querystring parameters &amp; request specific connection settings.</param> [MapsApi("cluster.get_settings", "")] public Task<TResponse> GetSettingsAsync<TResponse>(ClusterGetSettingsRequestParameters requestParameters = null, CancellationToken ctx = default) where TResponse : class, IElasticsearchResponse, new() => DoRequestAsync<TResponse>(GET, "_cluster/settings", ctx, null, RequestParams(requestParameters)); ///<summary>GET on /_cluster/health <para>https://www.elastic.co/guide/en/elasticsearch/reference/master/cluster-health.html</para></summary> ///<param name = "requestParameters">Request specific configuration such as querystring parameters &amp; request specific connection settings.</param> public TResponse Health<TResponse>(ClusterHealthRequestParameters requestParameters = null) where TResponse : class, IElasticsearchResponse, new() => DoRequest<TResponse>(GET, "_cluster/health", null, RequestParams(requestParameters)); ///<summary>GET on /_cluster/health <para>https://www.elastic.co/guide/en/elasticsearch/reference/master/cluster-health.html</para></summary> ///<param name = "requestParameters">Request specific configuration such as querystring parameters &amp; request specific connection settings.</param> [MapsApi("cluster.health", "")] public Task<TResponse> HealthAsync<TResponse>(ClusterHealthRequestParameters requestParameters = null, CancellationToken ctx = default) where TResponse : class, IElasticsearchResponse, new() => DoRequestAsync<TResponse>(GET, "_cluster/health", ctx, null, RequestParams(requestParameters)); ///<summary>GET on /_cluster/health/{index} <para>https://www.elastic.co/guide/en/elasticsearch/reference/master/cluster-health.html</para></summary> ///<param name = "index">Limit the information returned to a specific index</param> ///<param name = "requestParameters">Request specific configuration such as querystring parameters &amp; request specific connection settings.</param> public TResponse Health<TResponse>(string index, ClusterHealthRequestParameters requestParameters = null) where TResponse : class, IElasticsearchResponse, new() => DoRequest<TResponse>(GET, Url($"_cluster/health/{index:index}"), null, RequestParams(requestParameters)); ///<summary>GET on /_cluster/health/{index} <para>https://www.elastic.co/guide/en/elasticsearch/reference/master/cluster-health.html</para></summary> ///<param name = "index">Limit the information returned to a specific index</param> ///<param name = "requestParameters">Request specific configuration such as querystring parameters &amp; request specific connection settings.</param> [MapsApi("cluster.health", "index")] public Task<TResponse> HealthAsync<TResponse>(string index, ClusterHealthRequestParameters requestParameters = null, CancellationToken ctx = default) where TResponse : class, IElasticsearchResponse, new() => DoRequestAsync<TResponse>(GET, Url($"_cluster/health/{index:index}"), ctx, null, RequestParams(requestParameters)); ///<summary>GET on /_cluster/pending_tasks <para>https://www.elastic.co/guide/en/elasticsearch/reference/master/cluster-pending.html</para></summary> ///<param name = "requestParameters">Request specific configuration such as querystring parameters &amp; request specific connection settings.</param> public TResponse PendingTasks<TResponse>(ClusterPendingTasksRequestParameters requestParameters = null) where TResponse : class, IElasticsearchResponse, new() => DoRequest<TResponse>(GET, "_cluster/pending_tasks", null, RequestParams(requestParameters)); ///<summary>GET on /_cluster/pending_tasks <para>https://www.elastic.co/guide/en/elasticsearch/reference/master/cluster-pending.html</para></summary> ///<param name = "requestParameters">Request specific configuration such as querystring parameters &amp; request specific connection settings.</param> [MapsApi("cluster.pending_tasks", "")] public Task<TResponse> PendingTasksAsync<TResponse>(ClusterPendingTasksRequestParameters requestParameters = null, CancellationToken ctx = default) where TResponse : class, IElasticsearchResponse, new() => DoRequestAsync<TResponse>(GET, "_cluster/pending_tasks", ctx, null, RequestParams(requestParameters)); ///<summary>PUT on /_component_template/{name} <para>https://www.elastic.co/guide/en/elasticsearch/reference/master/indices-component-templates.html</para></summary> ///<param name = "name">The name of the template</param> ///<param name = "body">The template definition</param> ///<param name = "requestParameters">Request specific configuration such as querystring parameters &amp; request specific connection settings.</param> public TResponse PutComponentTemplate<TResponse>(string name, PostData body, PutComponentTemplateRequestParameters requestParameters = null) where TResponse : class, IElasticsearchResponse, new() => DoRequest<TResponse>(PUT, Url($"_component_template/{name:name}"), body, RequestParams(requestParameters)); ///<summary>PUT on /_component_template/{name} <para>https://www.elastic.co/guide/en/elasticsearch/reference/master/indices-component-templates.html</para></summary> ///<param name = "name">The name of the template</param> ///<param name = "body">The template definition</param> ///<param name = "requestParameters">Request specific configuration such as querystring parameters &amp; request specific connection settings.</param> [MapsApi("cluster.put_component_template", "name, body")] public Task<TResponse> PutComponentTemplateAsync<TResponse>(string name, PostData body, PutComponentTemplateRequestParameters requestParameters = null, CancellationToken ctx = default) where TResponse : class, IElasticsearchResponse, new() => DoRequestAsync<TResponse>(PUT, Url($"_component_template/{name:name}"), ctx, body, RequestParams(requestParameters)); ///<summary>PUT on /_cluster/settings <para>https://www.elastic.co/guide/en/elasticsearch/reference/master/cluster-update-settings.html</para></summary> ///<param name = "body">The settings to be updated. Can be either `transient` or `persistent` (survives cluster restart).</param> ///<param name = "requestParameters">Request specific configuration such as querystring parameters &amp; request specific connection settings.</param> public TResponse PutSettings<TResponse>(PostData body, ClusterPutSettingsRequestParameters requestParameters = null) where TResponse : class, IElasticsearchResponse, new() => DoRequest<TResponse>(PUT, "_cluster/settings", body, RequestParams(requestParameters)); ///<summary>PUT on /_cluster/settings <para>https://www.elastic.co/guide/en/elasticsearch/reference/master/cluster-update-settings.html</para></summary> ///<param name = "body">The settings to be updated. Can be either `transient` or `persistent` (survives cluster restart).</param> ///<param name = "requestParameters">Request specific configuration such as querystring parameters &amp; request specific connection settings.</param> [MapsApi("cluster.put_settings", "body")] public Task<TResponse> PutSettingsAsync<TResponse>(PostData body, ClusterPutSettingsRequestParameters requestParameters = null, CancellationToken ctx = default) where TResponse : class, IElasticsearchResponse, new() => DoRequestAsync<TResponse>(PUT, "_cluster/settings", ctx, body, RequestParams(requestParameters)); ///<summary>GET on /_remote/info <para>https://www.elastic.co/guide/en/elasticsearch/reference/master/cluster-remote-info.html</para></summary> ///<param name = "requestParameters">Request specific configuration such as querystring parameters &amp; request specific connection settings.</param> public TResponse RemoteInfo<TResponse>(RemoteInfoRequestParameters requestParameters = null) where TResponse : class, IElasticsearchResponse, new() => DoRequest<TResponse>(GET, "_remote/info", null, RequestParams(requestParameters)); ///<summary>GET on /_remote/info <para>https://www.elastic.co/guide/en/elasticsearch/reference/master/cluster-remote-info.html</para></summary> ///<param name = "requestParameters">Request specific configuration such as querystring parameters &amp; request specific connection settings.</param> [MapsApi("cluster.remote_info", "")] public Task<TResponse> RemoteInfoAsync<TResponse>(RemoteInfoRequestParameters requestParameters = null, CancellationToken ctx = default) where TResponse : class, IElasticsearchResponse, new() => DoRequestAsync<TResponse>(GET, "_remote/info", ctx, null, RequestParams(requestParameters)); ///<summary>POST on /_cluster/reroute <para>https://www.elastic.co/guide/en/elasticsearch/reference/master/cluster-reroute.html</para></summary> ///<param name = "body">The definition of `commands` to perform (`move`, `cancel`, `allocate`)</param> ///<param name = "requestParameters">Request specific configuration such as querystring parameters &amp; request specific connection settings.</param> public TResponse Reroute<TResponse>(PostData body, ClusterRerouteRequestParameters requestParameters = null) where TResponse : class, IElasticsearchResponse, new() => DoRequest<TResponse>(POST, "_cluster/reroute", body, RequestParams(requestParameters)); ///<summary>POST on /_cluster/reroute <para>https://www.elastic.co/guide/en/elasticsearch/reference/master/cluster-reroute.html</para></summary> ///<param name = "body">The definition of `commands` to perform (`move`, `cancel`, `allocate`)</param> ///<param name = "requestParameters">Request specific configuration such as querystring parameters &amp; request specific connection settings.</param> [MapsApi("cluster.reroute", "body")] public Task<TResponse> RerouteAsync<TResponse>(PostData body, ClusterRerouteRequestParameters requestParameters = null, CancellationToken ctx = default) where TResponse : class, IElasticsearchResponse, new() => DoRequestAsync<TResponse>(POST, "_cluster/reroute", ctx, body, RequestParams(requestParameters)); ///<summary>GET on /_cluster/state <para>https://www.elastic.co/guide/en/elasticsearch/reference/master/cluster-state.html</para></summary> ///<param name = "requestParameters">Request specific configuration such as querystring parameters &amp; request specific connection settings.</param> public TResponse State<TResponse>(ClusterStateRequestParameters requestParameters = null) where TResponse : class, IElasticsearchResponse, new() => DoRequest<TResponse>(GET, "_cluster/state", null, RequestParams(requestParameters)); ///<summary>GET on /_cluster/state <para>https://www.elastic.co/guide/en/elasticsearch/reference/master/cluster-state.html</para></summary> ///<param name = "requestParameters">Request specific configuration such as querystring parameters &amp; request specific connection settings.</param> [MapsApi("cluster.state", "")] public Task<TResponse> StateAsync<TResponse>(ClusterStateRequestParameters requestParameters = null, CancellationToken ctx = default) where TResponse : class, IElasticsearchResponse, new() => DoRequestAsync<TResponse>(GET, "_cluster/state", ctx, null, RequestParams(requestParameters)); ///<summary>GET on /_cluster/state/{metric} <para>https://www.elastic.co/guide/en/elasticsearch/reference/master/cluster-state.html</para></summary> ///<param name = "metric">Limit the information returned to the specified metrics</param> ///<param name = "requestParameters">Request specific configuration such as querystring parameters &amp; request specific connection settings.</param> public TResponse State<TResponse>(string metric, ClusterStateRequestParameters requestParameters = null) where TResponse : class, IElasticsearchResponse, new() => DoRequest<TResponse>(GET, Url($"_cluster/state/{metric:metric}"), null, RequestParams(requestParameters)); ///<summary>GET on /_cluster/state/{metric} <para>https://www.elastic.co/guide/en/elasticsearch/reference/master/cluster-state.html</para></summary> ///<param name = "metric">Limit the information returned to the specified metrics</param> ///<param name = "requestParameters">Request specific configuration such as querystring parameters &amp; request specific connection settings.</param> [MapsApi("cluster.state", "metric")] public Task<TResponse> StateAsync<TResponse>(string metric, ClusterStateRequestParameters requestParameters = null, CancellationToken ctx = default) where TResponse : class, IElasticsearchResponse, new() => DoRequestAsync<TResponse>(GET, Url($"_cluster/state/{metric:metric}"), ctx, null, RequestParams(requestParameters)); ///<summary>GET on /_cluster/state/{metric}/{index} <para>https://www.elastic.co/guide/en/elasticsearch/reference/master/cluster-state.html</para></summary> ///<param name = "metric">Limit the information returned to the specified metrics</param> ///<param name = "index">A comma-separated list of index names; use the special string `_all` or Indices.All to perform the operation on all indices</param> ///<param name = "requestParameters">Request specific configuration such as querystring parameters &amp; request specific connection settings.</param> public TResponse State<TResponse>(string metric, string index, ClusterStateRequestParameters requestParameters = null) where TResponse : class, IElasticsearchResponse, new() => DoRequest<TResponse>(GET, Url($"_cluster/state/{metric:metric}/{index:index}"), null, RequestParams(requestParameters)); ///<summary>GET on /_cluster/state/{metric}/{index} <para>https://www.elastic.co/guide/en/elasticsearch/reference/master/cluster-state.html</para></summary> ///<param name = "metric">Limit the information returned to the specified metrics</param> ///<param name = "index">A comma-separated list of index names; use the special string `_all` or Indices.All to perform the operation on all indices</param> ///<param name = "requestParameters">Request specific configuration such as querystring parameters &amp; request specific connection settings.</param> [MapsApi("cluster.state", "metric, index")] public Task<TResponse> StateAsync<TResponse>(string metric, string index, ClusterStateRequestParameters requestParameters = null, CancellationToken ctx = default) where TResponse : class, IElasticsearchResponse, new() => DoRequestAsync<TResponse>(GET, Url($"_cluster/state/{metric:metric}/{index:index}"), ctx, null, RequestParams(requestParameters)); ///<summary>GET on /_cluster/stats <para>https://www.elastic.co/guide/en/elasticsearch/reference/master/cluster-stats.html</para></summary> ///<param name = "requestParameters">Request specific configuration such as querystring parameters &amp; request specific connection settings.</param> public TResponse Stats<TResponse>(ClusterStatsRequestParameters requestParameters = null) where TResponse : class, IElasticsearchResponse, new() => DoRequest<TResponse>(GET, "_cluster/stats", null, RequestParams(requestParameters)); ///<summary>GET on /_cluster/stats <para>https://www.elastic.co/guide/en/elasticsearch/reference/master/cluster-stats.html</para></summary> ///<param name = "requestParameters">Request specific configuration such as querystring parameters &amp; request specific connection settings.</param> [MapsApi("cluster.stats", "")] public Task<TResponse> StatsAsync<TResponse>(ClusterStatsRequestParameters requestParameters = null, CancellationToken ctx = default) where TResponse : class, IElasticsearchResponse, new() => DoRequestAsync<TResponse>(GET, "_cluster/stats", ctx, null, RequestParams(requestParameters)); ///<summary>GET on /_cluster/stats/nodes/{node_id} <para>https://www.elastic.co/guide/en/elasticsearch/reference/master/cluster-stats.html</para></summary> ///<param name = "nodeId">A comma-separated list of node IDs or names to limit the returned information; use `_local` to return information from the node you&#x27;re connecting to, leave empty to get information from all nodes</param> ///<param name = "requestParameters">Request specific configuration such as querystring parameters &amp; request specific connection settings.</param> public TResponse Stats<TResponse>(string nodeId, ClusterStatsRequestParameters requestParameters = null) where TResponse : class, IElasticsearchResponse, new() => DoRequest<TResponse>(GET, Url($"_cluster/stats/nodes/{nodeId:nodeId}"), null, RequestParams(requestParameters)); ///<summary>GET on /_cluster/stats/nodes/{node_id} <para>https://www.elastic.co/guide/en/elasticsearch/reference/master/cluster-stats.html</para></summary> ///<param name = "nodeId">A comma-separated list of node IDs or names to limit the returned information; use `_local` to return information from the node you&#x27;re connecting to, leave empty to get information from all nodes</param> ///<param name = "requestParameters">Request specific configuration such as querystring parameters &amp; request specific connection settings.</param> [MapsApi("cluster.stats", "node_id")] public Task<TResponse> StatsAsync<TResponse>(string nodeId, ClusterStatsRequestParameters requestParameters = null, CancellationToken ctx = default) where TResponse : class, IElasticsearchResponse, new() => DoRequestAsync<TResponse>(GET, Url($"_cluster/stats/nodes/{nodeId:nodeId}"), ctx, null, RequestParams(requestParameters)); } }
113.955357
236
0.77043
[ "Apache-2.0" ]
adamralph/elasticsearch-net
src/Elasticsearch.Net/ElasticLowLevelClient.Cluster.cs
25,972
C#
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE namespace osu.Game.Rulesets.Taiko.Objects { public class SwellTick : TaikoHitObject { } }
26.2
93
0.694656
[ "MIT" ]
AtomCrafty/osu
osu.Game.Rulesets.Taiko/Objects/SwellTick.cs
253
C#
using System; using System.Collections.Generic; using System.IdentityModel.Tokens.Jwt; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading.Tasks; using AppLensV3.Authorization; using AppLensV3.Models; using Newtonsoft.Json; namespace AppLensV3.Helpers { /// <summary> /// Utilities Class. /// </summary> public static class Utilities { private static readonly Lazy<HttpClient> Client = new Lazy<HttpClient>(() => { var client = new HttpClient(); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); return client; }); private static HttpClient HttpClientObj { get { return Client.Value; } } /// <summary> /// Validates if a user belongs to a security or distribution group. /// </summary> /// <param name="userAlias">user Alias</param> /// <param name="groupObjectId">group object id.</param> /// <returns>True, if user is part of the group.</returns> public static async Task<bool> CheckUserGroupMembership(string userAlias, string groupObjectId) { string graphUrl = GraphConstants.GraphApiCheckMemberGroupsFormat; var requestUrl = string.Format(graphUrl, userAlias); HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, requestUrl); Dictionary<string, Array> requestParams = new Dictionary<string, Array>(); string[] groupIds = groupObjectId.Split(","); requestParams.Add("groupIds", groupIds); string authorizationToken = await AuthorizationTokenService.Instance.GetAuthorizationTokenAsync(); request.Headers.Add("Authorization", authorizationToken); request.Content = new StringContent(JsonConvert.SerializeObject(requestParams), Encoding.UTF8, "application/json"); HttpResponseMessage responseMsg = await HttpClientObj.SendAsync(request); var res = await responseMsg.Content.ReadAsStringAsync(); dynamic groupIdsResponse = JsonConvert.DeserializeObject(res); string[] groupIdsReturned = groupIdsResponse.value.ToObject<string[]>(); return groupIdsReturned.Length > 0; } /// <summary> /// Checks if detector is marked public. /// </summary> /// <param name="detectorCodeString">Detector code string.</param> /// <returns>True, if detector is marked public.</returns> public static bool IsDetectorMarkedPublic(string detectorCodeString) { if (string.IsNullOrWhiteSpace(detectorCodeString)) { throw new ArgumentNullException(nameof(detectorCodeString)); } // Loose logic to figure out whether the detector is public or not. // The challenge is we dont expose this data in detector definition. Need to figure out a better way to know if detector is public or not. string trimmedCode = detectorCodeString.Replace(" ", string.Empty).ToLower(); return trimmedCode.Contains("internalonly=false)") || trimmedCode.Contains("internalonly:false)"); } /// <summary> /// Checks if user is allowed to publish a detector. /// </summary> /// <param name="userAlias">user Alias.</param> /// <param name="resourceConfig">resource Config.</param> /// <param name="detectorCode">detector Code.</param> /// <param name="isOriginalCodeMarkedPublic">if original detector is marked public or not.</param> /// <returns>True, if user has access to publish the detector.</returns> public static async Task<bool> IsUserAllowedToPublishDetector(string userAlias, ResourceConfig resourceConfig, string detectorCode, bool isOriginalCodeMarkedPublic) { if (resourceConfig == null || !resourceConfig.PublishAccessControlEnabled || (!isOriginalCodeMarkedPublic && !IsDetectorMarkedPublic(detectorCode))) { return true; } string userAliasTrimmed = userAlias.Trim().Split(new char[] { '@' }).FirstOrDefault(); bool result = false; if (!resourceConfig.AllowedUsersToPublish.IsNullOrEmpty()) { result = resourceConfig.AllowedUsersToPublish.Exists(p => p.Equals(userAliasTrimmed, StringComparison.OrdinalIgnoreCase)); } if (!result && !resourceConfig.AllowedGroupsToPublish.IsNullOrEmpty()) { foreach (var group in resourceConfig.AllowedGroupsToPublish) { result = await CheckUserGroupMembership(userAlias, group.ObjectIds); if (result) { return result; } } } return result; } /// <summary> /// Gets User Id from Auth token. /// </summary> /// <param name="authorizationToken">Auth token.</param> /// <returns>User Id.</returns> public static string GetUserIdFromToken(string authorizationToken) { string userId = string.Empty; if (string.IsNullOrWhiteSpace(authorizationToken)) { throw new ArgumentNullException(nameof(authorizationToken)); } string accessToken = authorizationToken; if (authorizationToken.ToLower().Contains("bearer ")) { accessToken = authorizationToken.Split(" ")[1]; } var token = new JwtSecurityToken(accessToken); if (token.Payload.TryGetValue("upn", out object upn)) { userId = upn.ToString(); } return userId; } } }
41.176871
172
0.613745
[ "MIT" ]
Azure/Azure-AppServices-Diagnostics-Portal
ApplensBackend/Helpers/Utilities.cs
6,055
C#
using System; using NetRuntimeSystem = System; using System.ComponentModel; using NetOffice.Attributes; using NetOffice.PublisherApi; namespace NetOffice.PublisherApi.Behind { /// <summary> /// DispatchInterface Tag /// SupportByVersion Publisher, 14,15,16 /// </summary> [SupportByVersion("Publisher", 14,15,16)] [EntityType(EntityType.IsDispatchInterface)] public class Tag : COMObject, NetOffice.PublisherApi.Tag { #pragma warning disable #region Type Information /// <summary> /// Contract Type /// </summary> [EditorBrowsable(EditorBrowsableState.Advanced), Browsable(false), Category("NetOffice"), CoreOverridden] public override Type ContractType { get { if(null == _contractType) _contractType = typeof(NetOffice.PublisherApi.Tag); return _contractType; } } private static Type _contractType; /// <summary> /// Instance Type /// </summary> [EditorBrowsable(EditorBrowsableState.Advanced), Browsable(false), Category("NetOffice"), CoreOverridden] public override Type InstanceType { get { return LateBindingApiWrapperType; } } private static Type _type; [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public static Type LateBindingApiWrapperType { get { if (null == _type) _type = typeof(Tag); return _type; } } #endregion #region Ctor /// <summary> /// Stub Ctor, not indented to use /// </summary> public Tag() : base() { } #endregion #region Properties /// <summary> /// SupportByVersion Publisher 14, 15, 16 /// Get /// </summary> [SupportByVersion("Publisher", 14,15,16)] public virtual NetOffice.PublisherApi.Application Application { get { return InvokerService.InvokeInternal.ExecuteKnownReferencePropertyGet<NetOffice.PublisherApi.Application>(this, "Application", typeof(NetOffice.PublisherApi.Application)); } } /// <summary> /// SupportByVersion Publisher 14, 15, 16 /// Get /// Unknown COM Proxy /// </summary> [SupportByVersion("Publisher", 14,15,16), ProxyResult] public virtual object Parent { get { return InvokerService.InvokeInternal.ExecuteReferencePropertyGet(this, "Parent"); } } /// <summary> /// SupportByVersion Publisher 14, 15, 16 /// Get /// </summary> [SupportByVersion("Publisher", 14,15,16)] public virtual string Name { get { return InvokerService.InvokeInternal.ExecuteStringPropertyGet(this, "Name"); } } /// <summary> /// SupportByVersion Publisher 14, 15, 16 /// Get/Set /// </summary> [SupportByVersion("Publisher", 14,15,16)] public virtual object Value { get { return InvokerService.InvokeInternal.ExecuteVariantPropertyGet(this, "Value"); } set { InvokerService.InvokeInternal.ExecuteVariantPropertySet(this, "Value", value); } } #endregion #region Methods /// <summary> /// SupportByVersion Publisher 14, 15, 16 /// </summary> [SupportByVersion("Publisher", 14,15,16)] public virtual void Delete() { InvokerService.InvokeInternal.ExecuteMethod(this, "Delete"); } #endregion #pragma warning restore } }
22.12987
175
0.637031
[ "MIT" ]
igoreksiz/NetOffice
Source/Publisher/Behind/DispatchInterfaces/Tag.cs
3,410
C#
using Microsoft.EntityFrameworkCore.Migrations; using Pims.Dal.Helpers.Migrations; using System.Diagnostics.CodeAnalysis; namespace Pims.Dal.Migrations { public partial class v02091 : SeedMigration { protected override void Up(MigrationBuilder migrationBuilder) { PreUp(migrationBuilder); PostUp(migrationBuilder); } protected override void Down(MigrationBuilder migrationBuilder) { PreDown(migrationBuilder); PostDown(migrationBuilder); } } }
23.208333
71
0.666068
[ "Apache-2.0" ]
sookeke/PSP
backend/dal/Migrations/20210908232309_v0.2.0.9.1.cs
559
C#
using AcadTestRunner; using Autodesk.AutoCAD.DatabaseServices; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Linq2Acad.Tests { public abstract class ContainerAssertions { private Database db; private ObjectId containerId; private StringBuilder builder; protected ContainerAssertions(Database db, ObjectId containerId, string containerName, StringBuilder builder) { this.db = db; this.containerId = containerId; this.builder = builder; builder.Append(containerName + " "); } protected abstract bool ContainsInteral(Transaction tr, ObjectId containerId, string elementName); protected abstract bool ContainsInteral(Transaction tr, ObjectId containerId, ObjectId objectId); public void Contains(string blockName) { using (var tr = db.TransactionManager.StartTransaction()) { if (!ContainsInteral(tr, containerId, blockName)) { builder.Append(" does not contain an element with name '" + blockName + "'"); throw new AcadAssertFailedException(builder.ToString()); } } } public void Contains(ObjectId objectId) { using (var tr = db.TransactionManager.StartTransaction()) { if (!ContainsInteral(tr, containerId, objectId)) { builder.Append(" does not contain an element with ObjectId '" + objectId + "'"); throw new AcadAssertFailedException(builder.ToString()); } } } } public class TableAssertions<T> : ContainerAssertions where T : SymbolTable { public TableAssertions(Database db, ObjectId tableId, StringBuilder builder) : base(db, tableId, typeof(T).Name, builder) { } protected override bool ContainsInteral(Transaction tr, ObjectId containerId, string elementName) { var table = tr.GetObject(containerId, OpenMode.ForRead) as T; return table.Has(elementName); } protected override bool ContainsInteral(Transaction tr, ObjectId containerId, ObjectId objectId) { var table = tr.GetObject(containerId, OpenMode.ForRead) as T; return table.Has(objectId); } } public class DictionaryAssertions : ContainerAssertions { public DictionaryAssertions(Database db, ObjectId dictionaryId, string dictionaryName, StringBuilder builder) : base(db, dictionaryId, dictionaryName, builder) { } protected override bool ContainsInteral(Transaction tr, ObjectId containerId, string elementName) { var dict = tr.GetObject(containerId, OpenMode.ForRead) as DBDictionary; return dict.Contains(elementName); } protected override bool ContainsInteral(Transaction tr, ObjectId containerId, ObjectId objectId) { var dict = tr.GetObject(containerId, OpenMode.ForRead) as DBDictionary; return dict.Contains(objectId); } } }
31.351064
113
0.699695
[ "MIT" ]
BKSpurgeon/Linq2Acad
Linq2Acad.Tests/Assert/ContainerAssertions.cs
2,949
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FactorioModBuilder.Models.Base { public abstract class TreeItemBase { public string Name { get; set; } public TreeItemBase(string name) { this.Name = name; } } }
18.263158
40
0.648415
[ "MIT" ]
kmclarnon/FactorioModBuilder
FactorioModBuilder/Models/Base/TreeItemBase.cs
349
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:2.0.50727.5456 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Profiles.History { public partial class Default { } }
29.117647
82
0.412121
[ "BSD-3-Clause" ]
CTSIatUCSF/ProfilesRNS
Website/SourceCode/Profiles/Profiles/History/Default.aspx.designer.cs
497
C#
namespace Unifi.Models.Shared; /// <summary> /// The shared key info => slug mapping across the application /// </summary> public record SlugMapping { /// <summary> /// /// </summary> /// <value></value> public string MACAddress { get; init; } = string.Empty; /// <summary> /// /// </summary> /// <value></value> public string Slug { get; init; } = string.Empty; }
20.45
62
0.567237
[ "MIT" ]
mannkind/unifi2mq
Unifi/Models/Shared/SlugMapping.cs
409
C#
using System.Collections.Generic; using Todo.Web.Data; using Todo.Web.GraphQL.Common; namespace Todo.Web.GraphQL.Authors { public class AuthorPayloadBase : Payload { protected AuthorPayloadBase(Author author) { Author = author; } protected AuthorPayloadBase(IReadOnlyList<UserError> errors) : base(errors) { } public Author? Author { get; } } }
21.684211
87
0.65534
[ "MIT" ]
chneau/example-todo-aspnet-react
Todo.Web/GraphQL/Authors/AuthorPayloadBase.cs
412
C#
// Copyright (c) .NET Foundation and Contributors (https://dotnetfoundation.org/ & https://stride3d.net) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) // Distributed under the MIT license. See the LICENSE.md file in the project root for more information. using Stride.Core.Shaders.Utility; namespace Stride.Shaders.Parser.Utility { static public class StrideMessageCode { // analysis warning: W0### public static readonly MessageCode WarningDeclarationCall = new MessageCode("W0201", "The method invocation [{0}] calls the method [{1}] which is only declared, and not defined in class [{2}]"); public static readonly MessageCode WarningMissingStageKeyword = new MessageCode("W0202", "The stage keyword is missing in The method declaration [{0}] in class [{1}]"); public static readonly MessageCode WarningUseSemanticType = new MessageCode("W0203", "The generic [{0}] is not of Semantic type but was used as semantic. Change the type or change name of the generic if there is a conflict."); // analysis errors: E0### public static readonly MessageCode ErrorCyclicDependency = new MessageCode("E0201", "Cyclic mixin [{0}] dependency"); public static readonly MessageCode ErrorFunctionRedefined = new MessageCode("E0202", "There is already a function with the same signature as [{0}] in class [{1}]"); public static readonly MessageCode ErrorFunctionVariableNameConflict = new MessageCode("E0203", "The function [{0}] has the same name as a variable in class [{1}]"); public static readonly MessageCode ErrorVariableNameConflict = new MessageCode("E0204", "The variable [{0}] has the same name as another variable in class [{1}]"); public static readonly MessageCode ErrorVariableFunctionNameConflict = new MessageCode("E0205", "The variable [{0}] has the same name as a method in class [{1}]"); public static readonly MessageCode ErrorVreNoTypeInference = new MessageCode("E0206", "VariableReferenceExpression [{0}] has no type inference in class [{1}]"); public static readonly MessageCode ErrorStageVariableTypeConflict = new MessageCode("E0207", "Stage variable declaration [{0}] has not the same type as the actual definition [{1}] in class [{2}]"); public static readonly MessageCode ErrorImpossibleBaseCall = new MessageCode("E0208", "Unable to find the base call [{0}] of class [{1}]"); public static readonly MessageCode ErrorImpossibleVirtualCall = new MessageCode("E0209", "Unable to find the virtual call [{0}] of class [{1}] in context [{2}]"); public static readonly MessageCode ErrorExternStageVariableNotFound = new MessageCode("E0210", "There is no matching instance for variable [{0}] in class [{1}]"); public static readonly MessageCode ErrorExternStageFunctionNotFound = new MessageCode("E0211", "Unable to find the virtual call [{0}] of extern class [{1}] in context [{2}]"); public static readonly MessageCode ErrorMissingOverride = new MessageCode("E0212", "There is already a method with the same signature as [{0}] in class [{1}]. Missing override keyword?"); public static readonly MessageCode ErrorOverrideDeclaration = new MessageCode("E0213", "There is no need for the override keyword when overriding the method declaration [{0}] in class [{1}]"); public static readonly MessageCode ErrorNoMethodToOverride = new MessageCode("E0214", "There is no method [{0}] to override in class [{1}]"); public static readonly MessageCode ErrorShaderClassTypeParameter = new MessageCode("E0215", "The function [{0}] has a paramater [{1}] of shader class type which is not allowed in class [{2}]"); public static readonly MessageCode ErrorShaderClassReturnType = new MessageCode("E0216", "The function [{0}] is not allowed to return a class in class [{1}]"); public static readonly MessageCode ErrorMissingAbstract = new MessageCode("E0217", "The method [{0}] is only declared, so it should have the abstract keyword in class [{1}]"); public static readonly MessageCode ErrorUnnecessaryOverride = new MessageCode("E0218", "The method [{0}] is only declared, so it cannot have the override keyword in class [{1}]"); public static readonly MessageCode ErrorUnnecessaryAbstract = new MessageCode("E0219", "The method [{0}] is defined, so it cannot have the abstract keyword in clas [{1}]"); public static readonly MessageCode ErrorStageInitNotClassType = new MessageCode("E0220", "The variable [{0}] is initialized at stage and should be of class type in class [{1}]"); public static readonly MessageCode ErrorExternNotClassType = new MessageCode("E0221", "The extern variable [{0}] should be of class type in class [{1}]"); public static readonly MessageCode ErrorMissingExtern = new MessageCode("E0222", "The variable [{0}] is of class type and should have the extern keyword in class [{1}]"); public static readonly MessageCode ErrorVarNoInitialValue = new MessageCode("E0223", "The variable [{0}] should have an initial value to guess its type in class [{1}]"); public static readonly MessageCode ErrorVarNoTypeFound = new MessageCode("E0224", "Unable to guess the type of the variable [{0}] in class [{1}]"); public static readonly MessageCode ErrorTechniqueFound = new MessageCode("E0225", "Techniques like [{0}] are not allowed in the Stride shading language in class [{1}]"); public static readonly MessageCode ErrorExternMemberNotFound = new MessageCode("E0226", "There is no member [{0}] for the type [{1}] in class [{2}]"); public static readonly MessageCode ErrorStreamNotFound = new MessageCode("E0227", "Unable to find stream variable [{0}] in class [{1}]"); public static readonly MessageCode ErrorStreamUsage = new MessageCode("E0228", "the stream [{0}] was read first THEN written in class [{1}]"); public static readonly MessageCode ErrorVariableNameAmbiguity = new MessageCode("E0229", "The name [{0}] is ambiguous within variables in class [{1}]"); public static readonly MessageCode ErrorMethodNameAmbiguity = new MessageCode("E0230", "The name [{0}] is ambiguous within methods in class [{1}]"); public static readonly MessageCode ErrorMissingMethod = new MessageCode("E0231", "The method [{0}] in class [{1}] is not defined"); public static readonly MessageCode ErrorCyclicMethod = new MessageCode("E0232", "Method [{0}] performs a cyclic call, which is not allowed in class [{1}]"); public static readonly MessageCode ErrorDeclarationCall = new MessageCode("E0233", "The method invocation [{0}] calls the method [{1}] which is only declared, and not defined in class [{2}]"); public static readonly MessageCode ErrorNoBaseMixin = new MessageCode("E0234", "base call [{0}] without any base class in class [{1}]"); public static readonly MessageCode ErrorStageOutsideVariable = new MessageCode("E0235", "Use of the stage keyword in [{0}] which is outside a variable in class [{1}]"); public static readonly MessageCode ErrorMissingStreamsStruct = new MessageCode("E0236", "The variable [{0}] is a stream/patchstream and should be called this way [streams/constants.{0}] in class [{1}]"); public static readonly MessageCode ErrorMissingVariable = new MessageCode("E0237", "The variable [{0}] in class [{1}] is not defined"); public static readonly MessageCode ErrorNoTypeInference = new MessageCode("E0238", "Unable to infer type for [{0}] in class [{1}]"); public static readonly MessageCode ErrorShaderVariable = new MessageCode("E0239", "It is forbidden to create Shader variables like [{0}] in class [{1}]"); public static readonly MessageCode ErrorInterfaceFound = new MessageCode("E0240", "Hlsl interfaces like [{0}] are not allowed in Stride. Use classes instead. In class [{1}]"); public static readonly MessageCode ErrorMixinAsGeneric = new MessageCode("E0241", "A class like [{0}] cannot be used as a generic parameter for [{1}] in class [{2}]"); public static readonly MessageCode ErrorInOutStream = new MessageCode("E0242", "The stream [{0}] is used as an inout parameter in method [{1}] in class [{2}]"); public static readonly MessageCode ErrorIndexerNotLiteral = new MessageCode("E0243", "The IndexerExpression [{0}] of a composition have to be used with a literal index in class [{1}]"); public static readonly MessageCode ErrorMultiDimArray = new MessageCode("E0244", "Multi-dimentional arrays [{0}] are not supported in foreach statement [{1}] in class [{2}]"); public static readonly MessageCode ErrorExtraStageKeyword = new MessageCode("E0245", "The overriding method [{0}] have a stage keyword whereas its base doesn't [{1}], in class [{2}]"); public static readonly MessageCode ErrorTypedefInMethod = new MessageCode("E0246", "The typedef [{0}] is defined a method ([{1}]) which is not allowed, in class [{2}]"); public static readonly MessageCode ErrorNestedAssignment = new MessageCode("E0247", "Nested target assignment on the left like [{0}] are not supported, in shader [{1}]"); public static readonly MessageCode ErrorMultidimensionalCompositionArray = new MessageCode("E0248", "Multidimentional conposition arrays (type [{0}]) are not supported, in class [{1}]"); public static readonly MessageCode ErrorOverrindingDeclaration = new MessageCode("E0249", "Method [{0}] is an overriding declaration, this is not allowed"); public static readonly MessageCode ErrorNullKeyword = new MessageCode("E0250", "Keyword null is used outside of variable initialization in [{0}] in class [{1}]"); public static readonly MessageCode ErrorExtraStreamsPrefix = new MessageCode("E0251", "The variable [{0}] has the stream prefix but its declaration [{1}] is not a stream variable, in class [{2}]"); public static readonly MessageCode ErrorNonStaticCallInStaticMethod = new MessageCode("E0252", "The static method [{0}] performs a non-static call to [{1}], in class [{2}]"); public static readonly MessageCode ErrorNonStaticReferenceInStaticMethod = new MessageCode("E0253", "The static method [{0}] contains a reference to a non-static member [{1}], in class [{2}]"); // module errors: E1### public static readonly MessageCode UnknownModuleError = new MessageCode("E1200", "Unknown module error"); public static readonly MessageCode ErrorClassNotFound = new MessageCode("E1201", "The class [{0}] was not found from the include path"); public static readonly MessageCode ErrorDependencyNotInModule = new MessageCode("E1202", "The mixin [{0}] in [{1}] dependency is not in the module"); public static readonly MessageCode ErrorClassSourceNotInstantiated = new MessageCode("E1203", "The type [{0}] has generic parameters defined but only {1}/{2} arguments were passed when creating its instance"); public static readonly MessageCode ErrorAmbiguousComposition = new MessageCode("E1204", "The composition behind the variable [{0}] is ambiguous. Several matching variables were found."); // mix errors: E2### public static readonly MessageCode UnknownMixError = new MessageCode("E2200", "Unknown mix error"); public static readonly MessageCode ErrorVariableNotFound = new MessageCode("E2201", "Variable [{0}] not found in class [{1}]"); public static readonly MessageCode ErrorMissingStageVariable = new MessageCode("E2202", "Missing stage variable [{0}] from class [{1}]"); public static readonly MessageCode ErrorExternReferenceNotFound = new MessageCode("E2203", "Extern reference [{0}] not found from class [{1}]"); public static readonly MessageCode ErrorStageMixinNotFound = new MessageCode("E2204", "Stage mixin [{0}] not found from class [{1}] through stage initialized variable"); public static readonly MessageCode ErrorStageMixinVariableNotFound = new MessageCode("E2205", "Stage mixin [{0}] variable [{1}] not found from class [{1}]"); public static readonly MessageCode ErrorStageMixinMethodNotFound = new MessageCode("E2206", "Stage mixin [{0}] method [{1}] not found from class [{1}]"); public static readonly MessageCode ErrorIncompleteTesselationShader = new MessageCode("E2207", "Tessellation Shader is not compete, one stage is missing"); public static readonly MessageCode ErrorSemanticCbufferConflict = new MessageCode("E2208", "Variables [{0}] from [{1}] and [{2}] from [{3}] share the same semantic [{4}] but have distinct cbuffers ([{5}] and [{6}])"); public static readonly MessageCode ErrorRecursiveCall = new MessageCode("E2209", "Method [{0}] performs a recursive call which is not supported in shader language"); public static readonly MessageCode ErrorStreamUsageInitialization = new MessageCode("E2210", "A stream usage was added but not correctly initialized"); public static readonly MessageCode ErrorCrossStageMethodCall = new MessageCode("E2211", "Method [{0}] that uses streams is called in both [{1}] and [{2}] shader stages"); public static readonly MessageCode ErrorCallToAbstractMethod = new MessageCode("E2212", "The method invocation [{0}] calls the abstract method [{1}]"); public static readonly MessageCode ErrorCallNotFound = new MessageCode("E2213", "The method invocation [{0}] target could not be found"); public static readonly MessageCode ErrorTopMixinNotFound = new MessageCode("E2214", "The top mixin of [{0}] could not be found"); public static readonly MessageCode ErrorSemanticTypeConflict = new MessageCode("E2215", "Variables [{0}] from [{1}] and [{2}] from [{3}] share the same semantic [{4}] but have distinct types ([{5}] and [{6}])"); // linker errors: E3### public static readonly MessageCode SamplerFilterNotSupported = new MessageCode("E3000", "The sampler filter [{0}] is not supported"); public static readonly MessageCode SamplerAddressModeNotSupported = new MessageCode("E3001", "The sampler address mode [{0}] is not supported. Expecting AddressV, AddressU, AddressW"); public static readonly MessageCode SamplerBorderColorNotSupported = new MessageCode("E3002", "The sampler color component [{0}] is not supported. Expecting a float"); // loading errors public static readonly MessageCode ErrorUninstanciatedClass = new MessageCode("E3202", "The class [{0}] is not correctly instanciated with the current set of generics"); public static readonly MessageCode SamplerFieldNotSupported = new MessageCode("E3003", "The sampler field [{0}] is not supported"); public static readonly MessageCode LinkError = new MessageCode("E3004", "HLSL Link error: Could not find variable {0} in the shader"); public static readonly MessageCode LinkArgumentsError = new MessageCode("E3005", "HLSL Link error: Invalid number of arguments. Expecting only name of the linked variable"); public static readonly MessageCode VariableTypeNotSupported = new MessageCode("E3006", "The type of the variable [{0}] is not supported"); public static readonly MessageCode StreamVariableWithoutPrefix = new MessageCode("E3007", "Stream variable [{0}] is used without 'streams'. prefix"); public static readonly MessageCode WrongGenericNumber = new MessageCode("E3008", "The class [{0}] could not be instanciated because the number of required generics does not match the number of passed generics."); public static readonly MessageCode SameNameGenerics = new MessageCode("E3009", "The generic [{0}] has the same name as [{1}]. Class [{2}] couldn't be instanciated."); public static readonly MessageCode FileNameNotMatchingClassName = new MessageCode("E3010", "The shader file name [{0}] is not matching the shader class name [{1}]"); public static readonly MessageCode ShaderMustContainSingleClassDeclaration = new MessageCode("E3011", "The shader [{0}] must contain only a single shader class declaration"); // compiler errors: E4### public static readonly MessageCode EntryPointNotFound = new MessageCode("E4000", "Entrypoint [{0}] was not found for stage [{1}] in Shader [{2}]"); } }
155.704348
252
0.661119
[ "MIT" ]
AmbulantRex/stride
sources/engine/Stride.Shaders.Parser/Utility/StrideMessageCode.cs
17,906
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Runtime.ExceptionServices; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc.Abstractions; using Microsoft.AspNetCore.Mvc.Filters; using Microsoft.AspNetCore.Mvc.Internal; using Microsoft.AspNetCore.Mvc.ModelBinding; using Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.AspNetCore.Mvc.ViewFeatures; using Microsoft.AspNetCore.Mvc.ViewFeatures.Internal; using Microsoft.Extensions.Logging; namespace Microsoft.AspNetCore.Mvc.RazorPages.Internal { public class PageActionInvoker : ResourceInvoker, IActionInvoker { private readonly IPageHandlerMethodSelector _selector; private readonly PageContext _pageContext; private readonly ParameterBinder _parameterBinder; private readonly ITempDataDictionaryFactory _tempDataFactory; private readonly HtmlHelperOptions _htmlHelperOptions; private readonly CompiledPageActionDescriptor _actionDescriptor; private Dictionary<string, object> _arguments; private HandlerMethodDescriptor _handler; private PageBase _page; private object _pageModel; private ViewContext _viewContext; private PageHandlerSelectedContext _handlerSelectedContext; private PageHandlerExecutingContext _handlerExecutingContext; private PageHandlerExecutedContext _handlerExecutedContext; public PageActionInvoker( IPageHandlerMethodSelector handlerMethodSelector, DiagnosticSource diagnosticSource, ILogger logger, PageContext pageContext, IFilterMetadata[] filterMetadata, PageActionInvokerCacheEntry cacheEntry, ParameterBinder parameterBinder, ITempDataDictionaryFactory tempDataFactory, HtmlHelperOptions htmlHelperOptions) : base( diagnosticSource, logger, pageContext, filterMetadata, pageContext.ValueProviderFactories) { _selector = handlerMethodSelector; _pageContext = pageContext; CacheEntry = cacheEntry; _parameterBinder = parameterBinder; _tempDataFactory = tempDataFactory; _htmlHelperOptions = htmlHelperOptions; _actionDescriptor = pageContext.ActionDescriptor; } // Internal for testing internal PageActionInvokerCacheEntry CacheEntry { get; } private bool HasPageModel => _actionDescriptor.HandlerTypeInfo != _actionDescriptor.PageTypeInfo; // Internal for testing internal PageContext PageContext => _pageContext; /// <remarks> /// <see cref="ResourceInvoker"/> for details on what the variables in this method represent. /// </remarks> protected override async Task InvokeInnerFilterAsync() { var next = State.PageBegin; var scope = Scope.Invoker; var state = (object)null; var isCompleted = false; while (!isCompleted) { await Next(ref next, ref scope, ref state, ref isCompleted); } } protected override void ReleaseResources() { if (_pageModel != null && CacheEntry.ReleaseModel != null) { CacheEntry.ReleaseModel(_pageContext, _pageModel); } if (_page != null && CacheEntry.ReleasePage != null) { CacheEntry.ReleasePage(_pageContext, _viewContext, _page); } } private object CreateInstance() { if (HasPageModel) { // Since this is a PageModel, we need to activate it, and then run a handler method on the model. _pageModel = CacheEntry.ModelFactory(_pageContext); _pageContext.ViewData.Model = _pageModel; return _pageModel; } else { // Since this is a Page without a PageModel, we need to create the Page before running a handler method. _viewContext = new ViewContext( _pageContext, NullView.Instance, _pageContext.ViewData, _tempDataFactory.GetTempData(_pageContext.HttpContext), TextWriter.Null, _htmlHelperOptions); _viewContext.ExecutingFilePath = _pageContext.ActionDescriptor.RelativePath; _page = (PageBase)CacheEntry.PageFactory(_pageContext, _viewContext); if (_actionDescriptor.ModelTypeInfo == _actionDescriptor.PageTypeInfo) { _pageContext.ViewData.Model = _page; } return _page; } } private HandlerMethodDescriptor SelectHandler() { return _selector.Select(_pageContext); } private Task BindArgumentsAsync() { // Perf: Avoid allocating async state machines where possible. We only need the state // machine if you need to bind properties or arguments. if (_actionDescriptor.BoundProperties.Count == 0 && (_handler == null || _handler.Parameters.Count == 0)) { return Task.CompletedTask; } return BindArgumentsCoreAsync(); } private async Task BindArgumentsCoreAsync() { await CacheEntry.PropertyBinder(_pageContext, _instance); if (_handler == null) { return; } // We do two separate cache lookups, once for the binder and once for the executor. // Reduding it to a single lookup requires a lot of code change with little value. PageHandlerBinderDelegate handlerBinder = null; for (var i = 0; i < _actionDescriptor.HandlerMethods.Count; i++) { if (object.ReferenceEquals(_handler, _actionDescriptor.HandlerMethods[i])) { handlerBinder = CacheEntry.HandlerBinders[i]; break; } } await handlerBinder(_pageContext, _arguments); } private static object[] PrepareArguments( IDictionary<string, object> argumentsInDictionary, HandlerMethodDescriptor handler) { if (handler.Parameters.Count == 0) { return null; } var arguments = new object[handler.Parameters.Count]; for (var i = 0; i < arguments.Length; i++) { var parameter = handler.Parameters[i]; if (argumentsInDictionary.TryGetValue(parameter.ParameterInfo.Name, out var value)) { // Do nothing, already set the value. } else if (parameter.ParameterInfo.HasDefaultValue) { value = parameter.ParameterInfo.DefaultValue; } else if (parameter.ParameterInfo.ParameterType.IsValueType) { value = Activator.CreateInstance(parameter.ParameterInfo.ParameterType); } arguments[i] = value; } return arguments; } private async Task InvokeHandlerMethodAsync() { var handler = _handler; if (_handler != null) { var arguments = PrepareArguments(_arguments, handler); PageHandlerExecutorDelegate executor = null; for (var i = 0; i < _actionDescriptor.HandlerMethods.Count; i++) { if (object.ReferenceEquals(handler, _actionDescriptor.HandlerMethods[i])) { executor = CacheEntry.HandlerExecutors[i]; break; } } Debug.Assert(executor != null, "We should always find a executor for a handler"); _diagnosticSource.BeforeHandlerMethod(_pageContext, handler, _arguments, _instance); _logger.ExecutingHandlerMethod(_pageContext, handler, arguments); try { _result = await executor(_instance, arguments); _logger.ExecutedHandlerMethod(_pageContext, handler, _result); } finally { _diagnosticSource.AfterHandlerMethod(_pageContext, handler, _arguments, _instance, _result); } } // Pages have an implicit 'return Page()' even without a handler method. if (_result == null) { _result = new PageResult(); } // We also have some special initialization we need to do for PageResult. if (_result is PageResult pageResult) { // If we used a PageModel then the Page isn't initialized yet. if (_viewContext == null) { _viewContext = new ViewContext( _pageContext, NullView.Instance, _pageContext.ViewData, _tempDataFactory.GetTempData(_pageContext.HttpContext), TextWriter.Null, _htmlHelperOptions); _viewContext.ExecutingFilePath = _pageContext.ActionDescriptor.RelativePath; } if (_page == null) { _page = (PageBase)CacheEntry.PageFactory(_pageContext, _viewContext); } pageResult.Page = _page; pageResult.ViewData = pageResult.ViewData ?? _pageContext.ViewData; } } private Task Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted) { switch (next) { case State.PageBegin: { _instance = CreateInstance(); goto case State.PageSelectHandlerBegin; } case State.PageSelectHandlerBegin: { _cursor.Reset(); _handler = SelectHandler(); goto case State.PageSelectHandlerNext; } case State.PageSelectHandlerNext: var currentSelector = _cursor.GetNextFilter<IPageFilter, IAsyncPageFilter>(); if (currentSelector.FilterAsync != null) { if (_handlerSelectedContext == null) { _handlerSelectedContext = new PageHandlerSelectedContext(_pageContext, _filters, _instance) { HandlerMethod = _handler, }; } state = currentSelector.FilterAsync; goto case State.PageSelectHandlerAsyncBegin; } else if (currentSelector.Filter != null) { if (_handlerSelectedContext == null) { _handlerSelectedContext = new PageHandlerSelectedContext(_pageContext, _filters, _instance) { HandlerMethod = _handler, }; } state = currentSelector.Filter; goto case State.PageSelectHandlerSync; } else { goto case State.PageSelectHandlerEnd; } case State.PageSelectHandlerAsyncBegin: { Debug.Assert(state != null); Debug.Assert(_handlerSelectedContext != null); var filter = (IAsyncPageFilter)state; var handlerSelectedContext = _handlerSelectedContext; _diagnosticSource.BeforeOnPageHandlerSelection(handlerSelectedContext, filter); _logger.BeforeExecutingMethodOnFilter( PageLoggerExtensions.PageFilter, nameof(IAsyncPageFilter.OnPageHandlerSelectionAsync), filter); var task = filter.OnPageHandlerSelectionAsync(handlerSelectedContext); if (task.Status != TaskStatus.RanToCompletion) { next = State.PageSelectHandlerAsyncEnd; return task; } goto case State.PageSelectHandlerAsyncEnd; } case State.PageSelectHandlerAsyncEnd: { Debug.Assert(state != null); Debug.Assert(_handlerSelectedContext != null); var filter = (IAsyncPageFilter)state; _diagnosticSource.AfterOnPageHandlerSelection(_handlerSelectedContext, filter); _logger.AfterExecutingMethodOnFilter( PageLoggerExtensions.PageFilter, nameof(IAsyncPageFilter.OnPageHandlerSelectionAsync), filter); goto case State.PageSelectHandlerNext; } case State.PageSelectHandlerSync: { Debug.Assert(state != null); Debug.Assert(_handlerSelectedContext != null); var filter = (IPageFilter)state; var handlerSelectedContext = _handlerSelectedContext; _diagnosticSource.BeforeOnPageHandlerSelected(handlerSelectedContext, filter); _logger.BeforeExecutingMethodOnFilter( PageLoggerExtensions.PageFilter, nameof(IPageFilter.OnPageHandlerSelected), filter); filter.OnPageHandlerSelected(handlerSelectedContext); _diagnosticSource.AfterOnPageHandlerSelected(handlerSelectedContext, filter); goto case State.PageSelectHandlerNext; } case State.PageSelectHandlerEnd: { if (_handlerSelectedContext != null) { _handler = _handlerSelectedContext.HandlerMethod; } _arguments = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase); _cursor.Reset(); var task = BindArgumentsAsync(); if (task.Status != TaskStatus.RanToCompletion) { next = State.PageNext; return task; } goto case State.PageNext; } case State.PageNext: { var current = _cursor.GetNextFilter<IPageFilter, IAsyncPageFilter>(); if (current.FilterAsync != null) { if (_handlerExecutingContext == null) { _handlerExecutingContext = new PageHandlerExecutingContext(_pageContext, _filters, _handler, _arguments, _instance); } state = current.FilterAsync; goto case State.PageAsyncBegin; } else if (current.Filter != null) { if (_handlerExecutingContext == null) { _handlerExecutingContext = new PageHandlerExecutingContext(_pageContext, _filters, _handler, _arguments, _instance); } state = current.Filter; goto case State.PageSyncBegin; } else { goto case State.PageInside; } } case State.PageAsyncBegin: { Debug.Assert(state != null); Debug.Assert(_handlerExecutingContext != null); var filter = (IAsyncPageFilter)state; var handlerExecutingContext = _handlerExecutingContext; _diagnosticSource.BeforeOnPageHandlerExecution(handlerExecutingContext, filter); _logger.BeforeExecutingMethodOnFilter( PageLoggerExtensions.PageFilter, nameof(IAsyncPageFilter.OnPageHandlerExecutionAsync), filter); var task = filter.OnPageHandlerExecutionAsync(handlerExecutingContext, InvokeNextPageFilterAwaitedAsync); if (task.Status != TaskStatus.RanToCompletion) { next = State.PageAsyncEnd; return task; } goto case State.PageAsyncEnd; } case State.PageAsyncEnd: { Debug.Assert(state != null); Debug.Assert(_handlerExecutingContext != null); var filter = (IAsyncPageFilter)state; if (_handlerExecutedContext == null) { // If we get here then the filter didn't call 'next' indicating a short circuit. _logger.PageFilterShortCircuited(filter); _handlerExecutedContext = new PageHandlerExecutedContext( _pageContext, _filters, _handler, _instance) { Canceled = true, Result = _handlerExecutingContext.Result, }; } _diagnosticSource.AfterOnPageHandlerExecution(_handlerExecutedContext, filter); _logger.AfterExecutingMethodOnFilter( PageLoggerExtensions.PageFilter, nameof(IAsyncPageFilter.OnPageHandlerExecutionAsync), filter); goto case State.PageEnd; } case State.PageSyncBegin: { Debug.Assert(state != null); Debug.Assert(_handlerExecutingContext != null); var filter = (IPageFilter)state; var handlerExecutingContext = _handlerExecutingContext; _diagnosticSource.BeforeOnPageHandlerExecuting(handlerExecutingContext, filter); _logger.BeforeExecutingMethodOnFilter( PageLoggerExtensions.PageFilter, nameof(IPageFilter.OnPageHandlerExecuting), filter); filter.OnPageHandlerExecuting(handlerExecutingContext); _diagnosticSource.AfterOnPageHandlerExecuting(handlerExecutingContext, filter); _logger.AfterExecutingMethodOnFilter( PageLoggerExtensions.PageFilter, nameof(IPageFilter.OnPageHandlerExecuting), filter); if (handlerExecutingContext.Result != null) { // Short-circuited by setting a result. _logger.PageFilterShortCircuited(filter); _handlerExecutedContext = new PageHandlerExecutedContext( _pageContext, _filters, _handler, _instance) { Canceled = true, Result = _handlerExecutingContext.Result, }; goto case State.PageEnd; } var task = InvokeNextPageFilterAsync(); if (task.Status != TaskStatus.RanToCompletion) { next = State.PageSyncEnd; return task; } goto case State.PageSyncEnd; } case State.PageSyncEnd: { Debug.Assert(state != null); Debug.Assert(_handlerExecutingContext != null); Debug.Assert(_handlerExecutedContext != null); var filter = (IPageFilter)state; var handlerExecutedContext = _handlerExecutedContext; _diagnosticSource.BeforeOnPageHandlerExecuted(handlerExecutedContext, filter); _logger.BeforeExecutingMethodOnFilter( PageLoggerExtensions.PageFilter, nameof(IPageFilter.OnPageHandlerExecuted), filter); filter.OnPageHandlerExecuted(handlerExecutedContext); _diagnosticSource.AfterOnPageHandlerExecuted(handlerExecutedContext, filter); _logger.AfterExecutingMethodOnFilter( PageLoggerExtensions.PageFilter, nameof(IPageFilter.OnPageHandlerExecuted), filter); goto case State.PageEnd; } case State.PageInside: { var task = InvokeHandlerMethodAsync(); if (task.Status != TaskStatus.RanToCompletion) { next = State.PageEnd; return task; } goto case State.PageEnd; } case State.PageEnd: { if (scope == Scope.Page) { if (_handlerExecutedContext == null) { _handlerExecutedContext = new PageHandlerExecutedContext(_pageContext, _filters, _handler, _instance) { Result = _result, }; } isCompleted = true; return Task.CompletedTask; } var handlerExecutedContext = _handlerExecutedContext; Rethrow(handlerExecutedContext); if (handlerExecutedContext != null) { _result = handlerExecutedContext.Result; } isCompleted = true; return Task.CompletedTask; } default: throw new InvalidOperationException(); } } private async Task InvokeNextPageFilterAsync() { try { var next = State.PageNext; var state = (object)null; var scope = Scope.Page; var isCompleted = false; while (!isCompleted) { await Next(ref next, ref scope, ref state, ref isCompleted); } } catch (Exception exception) { _handlerExecutedContext = new PageHandlerExecutedContext(_pageContext, _filters, _handler, _instance) { ExceptionDispatchInfo = ExceptionDispatchInfo.Capture(exception), }; } Debug.Assert(_handlerExecutedContext != null); } private async Task<PageHandlerExecutedContext> InvokeNextPageFilterAwaitedAsync() { Debug.Assert(_handlerExecutingContext != null); if (_handlerExecutingContext.Result != null) { // If we get here, it means that an async filter set a result AND called next(). This is forbidden. var message = Resources.FormatAsyncPageFilter_InvalidShortCircuit( typeof(IAsyncPageFilter).Name, nameof(PageHandlerExecutingContext.Result), typeof(PageHandlerExecutingContext).Name, typeof(PageHandlerExecutionDelegate).Name); throw new InvalidOperationException(message); } await InvokeNextPageFilterAsync(); Debug.Assert(_handlerExecutedContext != null); return _handlerExecutedContext; } private static void Rethrow(PageHandlerExecutedContext context) { if (context == null) { return; } if (context.ExceptionHandled) { return; } if (context.ExceptionDispatchInfo != null) { context.ExceptionDispatchInfo.Throw(); } if (context.Exception != null) { throw context.Exception; } } private enum Scope { Invoker, Page, } private enum State { PageBegin, PageSelectHandlerBegin, PageSelectHandlerNext, PageSelectHandlerAsyncBegin, PageSelectHandlerAsyncEnd, PageSelectHandlerSync, PageSelectHandlerEnd, PageNext, PageAsyncBegin, PageAsyncEnd, PageSyncBegin, PageSyncEnd, PageInside, PageEnd, } } }
38.651685
148
0.498001
[ "Apache-2.0" ]
ratcorz/Mvc
src/Microsoft.AspNetCore.Mvc.RazorPages/Internal/PageActionInvoker.cs
27,522
C#
using Castle.Core.Logging; using Plus.Configuration.Startup; using Plus.Dependency; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; namespace Plus.Modules { /// <summary> /// 模块管理 /// </summary> public class PlusModuleManager : IPlusModuleManager { public PlusModuleInfo StartupModule { get; private set; } public IReadOnlyList<PlusModuleInfo> Modules => _modules.ToImmutableList(); public ILogger Logger { get; set; } private PlusModuleCollection _modules; private readonly IIocManager _iocManager; private readonly IPlusStartupConfiguration _startupConfiguration; public PlusModuleManager(IIocManager iocManager, IPlusStartupConfiguration startupConfiguration) { _iocManager = iocManager; _startupConfiguration = startupConfiguration; Logger = NullLogger.Instance; } public virtual void Initialize(Type startupModule) { _modules = new PlusModuleCollection(startupModule); LoadAllModules(); } public virtual void StartModules() { var sortedModules = _modules.GetSortedModuleListByDependency(); sortedModules.ForEach(module => module.Instance.PreInitialize()); sortedModules.ForEach(module => module.Instance.Initialize()); sortedModules.ForEach(module => module.Instance.PostInitialize()); } public virtual void ShutdownModules() { Logger.Debug("开始关闭模块"); List<PlusModuleInfo> sortedModuleListByDependency = _modules.GetSortedModuleListByDependency(); sortedModuleListByDependency.Reverse(); sortedModuleListByDependency.ForEach(delegate (PlusModuleInfo sm) { sm.Instance.Shutdown(); }); Logger.Debug("模块关闭完成"); } private void LoadAllModules() { Logger.Debug("加载模块..."); var moduleTypes = FindAllModuleTypes().Distinct().ToList(); Logger.Debug("找到 " + moduleTypes.Count + " 个模块."); RegisterModules(moduleTypes); CreateModules(moduleTypes); _modules.EnsureLeadershipToBeFirst(); _modules.EnsureStartupModuleToBeLast(); SetDependencies(); Logger.DebugFormat("{0} 个模块已加载.", _modules.Count); } private List<Type> FindAllModuleTypes() { return PlusModule.FindDependedModuleTypesRecursivelyIncludingGivenModule(_modules.StartupModuleType); } private void CreateModules(ICollection<Type> moduleTypes) { foreach (var moduleType in moduleTypes) { if (!(_iocManager.Resolve(moduleType) is PlusModule moduleObject)) { throw new PlusInitializationException("从类型不是 Plus 模块: " + moduleType.AssemblyQualifiedName); } moduleObject.IocManager = _iocManager; moduleObject.Configuration = _iocManager.Resolve<IPlusStartupConfiguration>(); var moduleInfo = new PlusModuleInfo(moduleType, moduleObject); _modules.Add(moduleInfo); if (moduleType == _modules.StartupModuleType) { StartupModule = moduleInfo; } Logger.DebugFormat("加载模块: " + moduleType.AssemblyQualifiedName); } } private void RegisterModules(ICollection<Type> moduleTypes) { foreach (Type moduleType in moduleTypes) { _iocManager.RegisterIfNot(moduleType); } } private void SetDependencies() { foreach (PlusModuleInfo module in _modules) { module.Dependencies.Clear(); foreach (Type dependedModuleType in PlusModule.FindDependedModuleTypes(module.Type)) { PlusModuleInfo PlusModuleInfo = _modules.FirstOrDefault((PlusModuleInfo m) => m.Type == dependedModuleType); if (PlusModuleInfo == null) { throw new PlusInitializationException("无法找到依赖的模块 " + dependedModuleType.AssemblyQualifiedName + " for " + module.Type.AssemblyQualifiedName); } if (module.Dependencies.FirstOrDefault((PlusModuleInfo dm) => dm.Type == dependedModuleType) == null) { module.Dependencies.Add(PlusModuleInfo); } } } } } }
34.268116
165
0.596743
[ "MIT" ]
Meowv/.netcoreplus
src/Plus/Modules/PlusModuleManager.cs
4,833
C#
namespace Protobuild.Tests { using System.IO; using Prototest.Library.Version1; public class NuGetPortableLibraryDetectedWithRootPathDotSlashTest : ProtobuildTest { private readonly IAssert _assert; public NuGetPortableLibraryDetectedWithRootPathDotSlashTest(IAssert assert) : base(assert) { _assert = assert; } public void GenerationIsCorrect() { this.SetupTest("NuGetPortableLibraryDetectedWithRootPathDotSlash"); this.Generate("Windows"); _assert.True(File.Exists(this.GetPath(@"Module.Windows.sln"))); _assert.True(File.Exists(this.GetPath(@"Console.Windows.csproj"))); var consoleContents = this.ReadFile(@"Console.Windows.csproj"); _assert.Contains("portable-net4+sl5+wp8+win8+wpa81+MonoTouch+MonoAndroid", consoleContents); _assert.Contains("Test.dll", consoleContents); _assert.Contains("<HintPath>packages", consoleContents); _assert.DoesNotContain("<HintPath>..\\packages", consoleContents); } } }
34.71875
104
0.663366
[ "MIT" ]
Protobuild/Protobuild
Protobuild.FunctionalTests/NuGetPortableLibraryDetectedWithRootPathDotSlashTest.cs
1,113
C#
using AvaloniaHelp.Core; using ReactiveUI; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AvaloniaHelp.ViewModels { public class HelpViewModel : BaseViewModel { public HelpViewModel() { OpenedTopics = new ReactiveList<Topic>(); } private Topic _activeTopic; /// <summary> /// Alle topics in the tabs. /// </summary> public ReactiveList<Topic> OpenedTopics { get; private set; } /// <summary> /// The active topic-tab. /// </summary> public Topic ActiveTopic { get { return _activeTopic; } set { this.RaiseAndSetIfChanged(ref _activeTopic, value); } } public object TopicContent { get { if (SelectedSection != null) return HelpManager.Instance.GetContentForTopic(SelectedSection.Topic); return null; } } } }
23.673913
90
0.548209
[ "MIT" ]
KeKl/AvaloniaHelp
Source/AvaloniaHelp/ViewModels/HelpViewModel.cs
1,091
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AfterburnerDataHandler.Servers.RTSS { public class FrametimeDataEventArgs : EventArgs { public uint appID; public uint frametime; public FrametimeDataEventArgs(uint appID, uint frametime) { this.appID = appID; this.frametime = frametime; } } }
21.380952
65
0.665924
[ "MIT" ]
busayn/Afterburner-Data-Handler
Servers/RTSS/FrametimeDataEventArgs.cs
451
C#
using System; using System.Collections.Generic; using System.Text; using Stencil.Domain; namespace Stencil.Primary.Business.Direct { // WARNING: THIS FILE IS GENERATED public partial interface IPaymentDetailBusiness { PaymentDetail GetById(Guid paymentdetail_id); List<PaymentDetail> GetByAccountId(Guid account_id); void InvalidateForAccountId(Guid account_id, string reason);PaymentDetail Insert(PaymentDetail insertPaymentDetail); PaymentDetail Update(PaymentDetail updatePaymentDetail); void Delete(Guid paymentdetail_id); void SynchronizationUpdate(Guid paymentdetail_id, bool success, DateTime sync_date_utc, string sync_log); List<Guid?> SynchronizationGetInvalid(int retryPriorityThreshold, string sync_agent); void SynchronizationHydrateUpdate(Guid paymentdetail_id, bool success, DateTime sync_date_utc, string sync_log); List<Guid?> SynchronizationHydrateGetInvalid(int retryPriorityThreshold, string sync_agent); void Invalidate(Guid paymentdetail_id, string reason); } }
41.074074
124
0.756537
[ "MIT" ]
DanMasterson1/stencil
Source/Stencil.Server/Stencil.Primary/Business/Direct/IPaymentDetailBusiness_Crud.cs
1,109
C#
// // ImapUtils.cs // // Author: Jeffrey Stedfast <jestedfa@microsoft.com> // // Copyright (c) 2013-2020 Xamarin Inc. (www.xamarin.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // using System; using System.Linq; using System.Text; using System.Threading; using System.Diagnostics; using System.Globalization; using System.Threading.Tasks; using System.Collections.Generic; using System.Collections.ObjectModel; using MimeKit; using MimeKit.Utils; namespace MailKit.Net.Imap { /// <summary> /// IMAP utility functions. /// </summary> static class ImapUtils { const FolderAttributes SpecialUseAttributes = FolderAttributes.All | FolderAttributes.Archive | FolderAttributes.Drafts | FolderAttributes.Flagged | FolderAttributes.Inbox | FolderAttributes.Junk | FolderAttributes.Sent | FolderAttributes.Trash; const string QuotedSpecials = " \t()<>@,;:\\\"/[]?="; static readonly int InboxLength = "INBOX".Length; static readonly string[] Months = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; /// <summary> /// Formats a date in a format suitable for use with the APPEND command. /// </summary> /// <returns>The formatted date string.</returns> /// <param name="date">The date.</param> public static string FormatInternalDate (DateTimeOffset date) { return string.Format (CultureInfo.InvariantCulture, "{0:D2}-{1}-{2:D4} {3:D2}:{4:D2}:{5:D2} {6:+00;-00}{7:00}", date.Day, Months[date.Month - 1], date.Year, date.Hour, date.Minute, date.Second, date.Offset.Hours, date.Offset.Minutes); } class UniqueHeaderSet : HashSet<string> { public UniqueHeaderSet () : base (StringComparer.Ordinal) { } } public static HashSet<string> GetUniqueHeaders (IEnumerable<string> headers) { if (headers == null) throw new ArgumentNullException (nameof (headers)); // check if this list of headers is already unique (e.g. created by GetUniqueHeaders (IEnumerable<HeaderId>)) if (headers is UniqueHeaderSet unique) return unique; var hash = new UniqueHeaderSet (); foreach (var header in headers) { if (header.Length == 0) throw new ArgumentException ($"Invalid header field: {header}", nameof (headers)); for (int i = 0; i < header.Length; i++) { char c = header[i]; if (c <= 32 || c >= 127 || c == ':') throw new ArgumentException ($"Illegal characters in header field: {header}", nameof (headers)); } hash.Add (header.ToUpperInvariant ()); } return hash; } public static HashSet<string> GetUniqueHeaders (IEnumerable<HeaderId> headers) { if (headers == null) throw new ArgumentNullException (nameof (headers)); var hash = new UniqueHeaderSet (); foreach (var header in headers) { if (header == HeaderId.Unknown) continue; hash.Add (header.ToHeaderName ().ToUpperInvariant ()); } return hash; } static bool TryGetInt32 (string text, ref int index, out int value) { int startIndex = index; value = 0; while (index < text.Length && text[index] >= '0' && text[index] <= '9') { int digit = text[index] - '0'; if (value > int.MaxValue / 10 || (value == int.MaxValue / 10 && digit > int.MaxValue % 10)) { // integer overflow return false; } value = (value * 10) + digit; index++; } return index > startIndex; } static bool TryGetInt32 (string text, ref int index, char delim, out int value) { return TryGetInt32 (text, ref index, out value) && index < text.Length && text[index] == delim; } static bool TryGetMonth (string text, ref int index, char delim, out int month) { int startIndex = index; month = 0; if ((index = text.IndexOf (delim, index)) == -1 || (index - startIndex) != 3) return false; for (int i = 0; i < Months.Length; i++) { if (string.Compare (Months[i], 0, text, startIndex, 3, StringComparison.OrdinalIgnoreCase) == 0) { month = i + 1; return true; } } return false; } static bool TryGetTimeZone (string text, ref int index, out TimeSpan timezone) { int tzone, sign = 1; if (text[index] == '-') { sign = -1; index++; } else if (text[index] == '+') { index++; } if (!TryGetInt32 (text, ref index, out tzone)) { timezone = new TimeSpan (); return false; } tzone *= sign; while (tzone < -1400) tzone += 2400; while (tzone > 1400) tzone -= 2400; int minutes = tzone % 100; int hours = tzone / 100; timezone = new TimeSpan (hours, minutes, 0); return true; } static Exception InvalidInternalDateFormat (string text) { return new FormatException ("Invalid INTERNALDATE format: " + text); } /// <summary> /// Parses the internal date string. /// </summary> /// <returns>The date.</returns> /// <param name="text">The text to parse.</param> public static DateTimeOffset ParseInternalDate (string text) { int day, month, year, hour, minute, second; TimeSpan timezone; int index = 0; while (index < text.Length && char.IsWhiteSpace (text[index])) index++; if (index >= text.Length || !TryGetInt32 (text, ref index, '-', out day) || day < 1 || day > 31) throw InvalidInternalDateFormat (text); index++; if (index >= text.Length || !TryGetMonth (text, ref index, '-', out month)) throw InvalidInternalDateFormat (text); index++; if (index >= text.Length || !TryGetInt32 (text, ref index, ' ', out year) || year < 1969) throw InvalidInternalDateFormat (text); index++; if (index >= text.Length || !TryGetInt32 (text, ref index, ':', out hour) || hour > 23) throw InvalidInternalDateFormat (text); index++; if (index >= text.Length || !TryGetInt32 (text, ref index, ':', out minute) || minute > 59) throw InvalidInternalDateFormat (text); index++; if (index >= text.Length || !TryGetInt32 (text, ref index, ' ', out second) || second > 59) throw InvalidInternalDateFormat (text); index++; if (index >= text.Length || !TryGetTimeZone (text, ref index, out timezone)) throw InvalidInternalDateFormat (text); while (index < text.Length && char.IsWhiteSpace (text[index])) index++; if (index < text.Length) throw InvalidInternalDateFormat (text); // return DateTimeOffset.ParseExact (text.Trim (), "d-MMM-yyyy HH:mm:ss zzz", CultureInfo.InvariantCulture.DateTimeFormat); return new DateTimeOffset (year, month, day, hour, minute, second, timezone); } /// <summary> /// Formats a list of annotations for a STORE or APPEND command. /// </summary> /// <param name="command">The command builder.</param> /// <param name="annotations">The annotations.</param> /// <param name="args">the argument list.</param> /// <param name="throwOnError">Throw an exception if there are any annotations without properties.</param> public static void FormatAnnotations (StringBuilder command, IList<Annotation> annotations, List<object> args, bool throwOnError) { int length = command.Length; int added = 0; command.Append ("ANNOTATION ("); for (int i = 0; i < annotations.Count; i++) { var annotation = annotations[i]; if (annotation.Properties.Count == 0) { if (throwOnError) throw new ArgumentException ("One or more annotations does not define any attributes.", nameof (annotations)); continue; } command.Append (annotation.Entry); command.Append (" ("); foreach (var property in annotation.Properties) { command.AppendFormat ("{0} %S ", property.Key); args.Add (property.Value); } command[command.Length - 1] = ')'; command.Append (' '); added++; } if (added > 0) command[command.Length - 1] = ')'; else command.Length = length; } /// <summary> /// Formats the array of indexes as a string suitable for use with IMAP commands. /// </summary> /// <returns>The index set.</returns> /// <param name="indexes">The indexes.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="indexes"/> is <c>null</c>. /// </exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// One or more of the indexes has a negative value. /// </exception> public static string FormatIndexSet (IList<int> indexes) { if (indexes == null) throw new ArgumentNullException (nameof (indexes)); if (indexes.Count == 0) throw new ArgumentException ("No indexes were specified.", nameof (indexes)); var builder = new StringBuilder (); int index = 0; while (index < indexes.Count) { if (indexes[index] < 0) throw new ArgumentException ("One or more of the indexes is negative.", nameof (indexes)); int begin = indexes[index]; int end = indexes[index]; int i = index + 1; if (i < indexes.Count) { if (indexes[i] == end + 1) { end = indexes[i++]; while (i < indexes.Count && indexes[i] == end + 1) { end++; i++; } } else if (indexes[i] == end - 1) { end = indexes[i++]; while (i < indexes.Count && indexes[i] == end - 1) { end--; i++; } } } if (builder.Length > 0) builder.Append (','); if (begin != end) builder.AppendFormat (CultureInfo.InvariantCulture, "{0}:{1}", begin + 1, end + 1); else builder.Append ((begin + 1).ToString (CultureInfo.InvariantCulture)); index = i; } return builder.ToString (); } /// <summary> /// Parses an untagged ID response. /// </summary> /// <param name="engine">The IMAP engine.</param> /// <param name="ic">The IMAP command.</param> /// <param name="index">The index.</param> /// <param name="doAsync">Whether or not asynchronous IO methods should be used.</param> public static async Task ParseImplementationAsync (ImapEngine engine, ImapCommand ic, int index, bool doAsync) { var format = string.Format (ImapEngine.GenericUntaggedResponseSyntaxErrorFormat, "ID", "{0}"); var token = await engine.ReadTokenAsync (doAsync, ic.CancellationToken).ConfigureAwait (false); ImapImplementation implementation; if (token.Type == ImapTokenType.Nil) return; ImapEngine.AssertToken (token, ImapTokenType.OpenParen, format, token); token = await engine.PeekTokenAsync (doAsync, ic.CancellationToken).ConfigureAwait (false); implementation = new ImapImplementation (); while (token.Type != ImapTokenType.CloseParen) { var property = await ReadStringTokenAsync (engine, format, doAsync, ic.CancellationToken).ConfigureAwait (false); var value = await ReadNStringTokenAsync (engine, format, false, doAsync, ic.CancellationToken).ConfigureAwait (false); implementation.Properties[property] = value; token = await engine.PeekTokenAsync (doAsync, ic.CancellationToken).ConfigureAwait (false); } ic.UserData = implementation; // read the ')' token await engine.ReadTokenAsync (doAsync, ic.CancellationToken).ConfigureAwait (false); } /// <summary> /// Canonicalize the name of the mailbox. /// </summary> /// <remarks> /// Canonicalizes the name of the mailbox by replacing various /// capitalizations of "INBOX" with the literal "INBOX" string. /// </remarks> /// <returns>The mailbox name.</returns> /// <param name="mailboxName">The encoded mailbox name.</param> /// <param name="directorySeparator">The directory separator.</param> public static string CanonicalizeMailboxName (string mailboxName, char directorySeparator) { if (!mailboxName.StartsWith ("INBOX", StringComparison.OrdinalIgnoreCase)) return mailboxName; if (mailboxName.Length > InboxLength && mailboxName[InboxLength] == directorySeparator) return "INBOX" + mailboxName.Substring (InboxLength); if (mailboxName.Length == InboxLength) return "INBOX"; return mailboxName; } /// <summary> /// Determines whether the specified mailbox is the Inbox. /// </summary> /// <returns><c>true</c> if the specified mailbox name is the Inbox; otherwise, <c>false</c>.</returns> /// <param name="mailboxName">The mailbox name.</param> public static bool IsInbox (string mailboxName) { return string.Compare (mailboxName, "INBOX", StringComparison.OrdinalIgnoreCase) == 0; } static async Task<string> ReadFolderNameAsync (ImapEngine engine, char delim, string format, bool doAsync, CancellationToken cancellationToken) { var token = await engine.ReadTokenAsync (ImapStream.AtomSpecials, doAsync, cancellationToken).ConfigureAwait (false); string encodedName; switch (token.Type) { case ImapTokenType.Literal: encodedName = await engine.ReadLiteralAsync (doAsync, cancellationToken).ConfigureAwait (false); break; case ImapTokenType.QString: case ImapTokenType.Atom: encodedName = (string) token.Value; // Note: Exchange apparently doesn't quote folder names that contain tabs. // // See https://github.com/jstedfast/MailKit/issues/945 for details. if (engine.QuirksMode == ImapQuirksMode.Exchange) { var line = await engine.ReadLineAsync (doAsync, cancellationToken); int eoln = line.IndexOf ("\r\n", StringComparison.Ordinal); eoln = eoln != -1 ? eoln : line.Length - 1; // unget the \r\n sequence token = new ImapToken (ImapTokenType.Eoln); engine.Stream.UngetToken (token); if (eoln > 0) encodedName += line.Substring (0, eoln); } break; case ImapTokenType.Nil: // Note: according to rfc3501, section 4.5, NIL is acceptable as a mailbox name. return "NIL"; default: throw ImapEngine.UnexpectedToken (format, token); } return encodedName.TrimEnd (delim); } /// <summary> /// Parses an untagged LIST or LSUB response. /// </summary> /// <param name="engine">The IMAP engine.</param> /// <param name="list">The list of folders to be populated.</param> /// <param name="isLsub"><c>true</c> if it is an LSUB response; otherwise, <c>false</c>.</param> /// <param name="returnsSubscribed"><c>true</c> if the LIST response is expected to return \Subscribed flags; otherwise, <c>false</c>.</param> /// <param name="doAsync">Whether or not asynchronous IO methods should be used.</param> /// <param name="cancellationToken">The cancellation token.</param> public static async Task ParseFolderListAsync (ImapEngine engine, List<ImapFolder> list, bool isLsub, bool returnsSubscribed, bool doAsync, CancellationToken cancellationToken) { var format = string.Format (ImapEngine.GenericUntaggedResponseSyntaxErrorFormat, isLsub ? "LSUB" : "LIST", "{0}"); var token = await engine.ReadTokenAsync (doAsync, cancellationToken).ConfigureAwait (false); var attrs = FolderAttributes.None; ImapFolder folder = null; string encodedName; char delim; // parse the folder attributes list ImapEngine.AssertToken (token, ImapTokenType.OpenParen, format, token); token = await engine.ReadTokenAsync (doAsync, cancellationToken).ConfigureAwait (false); while (token.Type == ImapTokenType.Flag || token.Type == ImapTokenType.Atom) { var atom = (string) token.Value; switch (atom) { case "\\NoInferiors": attrs |= FolderAttributes.NoInferiors; break; case "\\Noselect": attrs |= FolderAttributes.NoSelect; break; case "\\Marked": attrs |= FolderAttributes.Marked; break; case "\\Unmarked": attrs |= FolderAttributes.Unmarked; break; case "\\NonExistent": attrs |= FolderAttributes.NonExistent; break; case "\\Subscribed": attrs |= FolderAttributes.Subscribed; break; case "\\Remote": attrs |= FolderAttributes.Remote; break; case "\\HasChildren": attrs |= FolderAttributes.HasChildren; break; case "\\HasNoChildren": attrs |= FolderAttributes.HasNoChildren; break; case "\\All": attrs |= FolderAttributes.All; break; case "\\Archive": attrs |= FolderAttributes.Archive; break; case "\\Drafts": attrs |= FolderAttributes.Drafts; break; case "\\Flagged": attrs |= FolderAttributes.Flagged; break; case "\\Junk": attrs |= FolderAttributes.Junk; break; case "\\Sent": attrs |= FolderAttributes.Sent; break; case "\\Trash": attrs |= FolderAttributes.Trash; break; // XLIST flags: case "\\AllMail": attrs |= FolderAttributes.All; break; case "\\Important": attrs |= FolderAttributes.Flagged; break; case "\\Inbox": attrs |= FolderAttributes.Inbox; break; case "\\Spam": attrs |= FolderAttributes.Junk; break; case "\\Starred": attrs |= FolderAttributes.Flagged; break; } token = await engine.ReadTokenAsync (doAsync, cancellationToken).ConfigureAwait (false); } ImapEngine.AssertToken (token, ImapTokenType.CloseParen, format, token); // parse the path delimeter token = await engine.ReadTokenAsync (doAsync, cancellationToken).ConfigureAwait (false); if (token.Type == ImapTokenType.QString) { var qstring = (string) token.Value; delim = qstring[0]; } else if (token.Type == ImapTokenType.Nil) { delim = '\0'; } else { throw ImapEngine.UnexpectedToken (format, token); } encodedName = await ReadFolderNameAsync (engine, delim, format, doAsync, cancellationToken).ConfigureAwait (false); if (IsInbox (encodedName)) attrs |= FolderAttributes.Inbox; // peek at the next token to see if we have a LIST extension token = await engine.PeekTokenAsync (doAsync, cancellationToken).ConfigureAwait (false); if (token.Type == ImapTokenType.OpenParen) { var renamed = false; // read the '(' token token = await engine.ReadTokenAsync (doAsync, cancellationToken).ConfigureAwait (false); do { token = await engine.ReadTokenAsync (doAsync, cancellationToken).ConfigureAwait (false); if (token.Type == ImapTokenType.CloseParen) break; // a LIST extension ImapEngine.AssertToken (token, ImapTokenType.Atom, ImapTokenType.QString, format, token); var atom = (string) token.Value; token = await engine.ReadTokenAsync (doAsync, cancellationToken).ConfigureAwait (false); ImapEngine.AssertToken (token, ImapTokenType.OpenParen, format, token); do { token = await engine.ReadTokenAsync (doAsync, cancellationToken).ConfigureAwait (false); if (token.Type == ImapTokenType.CloseParen) break; engine.Stream.UngetToken (token); if (!renamed && atom.Equals ("OLDNAME", StringComparison.OrdinalIgnoreCase)) { var oldEncodedName = await ReadFolderNameAsync (engine, delim, format, doAsync, cancellationToken).ConfigureAwait (false); if (engine.FolderCache.TryGetValue (oldEncodedName, out ImapFolder oldFolder)) { var args = new ImapFolderConstructorArgs (engine, encodedName, attrs, delim); engine.FolderCache.Remove (oldEncodedName); engine.FolderCache[encodedName] = oldFolder; oldFolder.OnRenamed (args); folder = oldFolder; } renamed = true; } else { await ReadNStringTokenAsync (engine, format, false, doAsync, cancellationToken).ConfigureAwait (false); } } while (true); } while (true); } else { ImapEngine.AssertToken (token, ImapTokenType.Eoln, format, token); } if (folder != null || engine.GetCachedFolder (encodedName, out folder)) { if ((attrs & FolderAttributes.NonExistent) != 0) { folder.UpdatePermanentFlags (MessageFlags.None); folder.UpdateAcceptedFlags (MessageFlags.None); folder.UpdateUidNext (UniqueId.Invalid); folder.UpdateHighestModSeq (0); folder.UpdateUidValidity (0); folder.UpdateUnread (0); } if (isLsub) { // Note: merge all pre-existing attributes since the LSUB response will not contain them attrs |= folder.Attributes | FolderAttributes.Subscribed; } else { // Note: only merge the SPECIAL-USE and \Subscribed attributes for a LIST command attrs |= folder.Attributes & SpecialUseAttributes; // Note: only merge \Subscribed if the LIST command isn't expected to include it if (!returnsSubscribed) attrs |= folder.Attributes & FolderAttributes.Subscribed; } folder.UpdateAttributes (attrs); } else { folder = engine.CreateImapFolder (encodedName, attrs, delim); engine.CacheFolder (folder); if (list == null) engine.OnFolderCreated (folder); } // Note: list will be null if this is an unsolicited LIST response due to an active NOTIFY request list?.Add (folder); } /// <summary> /// Parses an untagged LIST or LSUB response. /// </summary> /// <param name="engine">The IMAP engine.</param> /// <param name="ic">The IMAP command.</param> /// <param name="index">The index.</param> /// <param name="doAsync">Whether or not asynchronous IO methods should be used.</param> public static Task ParseFolderListAsync (ImapEngine engine, ImapCommand ic, int index, bool doAsync) { var list = (List<ImapFolder>) ic.UserData; return ParseFolderListAsync (engine, list, ic.Lsub, ic.ListReturnsSubscribed, doAsync, ic.CancellationToken); } /// <summary> /// Parses an untagged METADATA response. /// </summary> /// <returns>The encoded name of the folder that the metadata belongs to.</returns> /// <param name="engine">The IMAP engine.</param> /// <param name="metadata">The metadata collection to be populated.</param> /// <param name="doAsync">Whether or not asynchronous IO methods should be used.</param> /// <param name="cancellationToken">The cancellation token.</param> public static async Task ParseMetadataAsync (ImapEngine engine, MetadataCollection metadata, bool doAsync, CancellationToken cancellationToken) { var format = string.Format (ImapEngine.GenericUntaggedResponseSyntaxErrorFormat, "METADATA", "{0}"); var encodedName = await ReadStringTokenAsync (engine, format, doAsync, cancellationToken).ConfigureAwait (false); var token = await engine.ReadTokenAsync (doAsync, cancellationToken).ConfigureAwait (false); ImapEngine.AssertToken (token, ImapTokenType.OpenParen, format, token); while (token.Type != ImapTokenType.CloseParen) { var tag = await ReadStringTokenAsync (engine, format, doAsync, cancellationToken).ConfigureAwait (false); var value = await ReadStringTokenAsync (engine, format, doAsync, cancellationToken).ConfigureAwait (false); metadata.Add (new Metadata (MetadataTag.Create (tag), value) { EncodedName = encodedName }); token = await engine.PeekTokenAsync (doAsync, cancellationToken).ConfigureAwait (false); } // read the closing paren await engine.ReadTokenAsync (doAsync, cancellationToken).ConfigureAwait (false); } /// <summary> /// Parses an untagged METADATA response. /// </summary> /// <param name="engine">The IMAP engine.</param> /// <param name="ic">The IMAP command.</param> /// <param name="index">The index.</param> /// <param name="doAsync">Whether or not asynchronous IO methods should be used.</param> public static Task ParseMetadataAsync (ImapEngine engine, ImapCommand ic, int index, bool doAsync) { var metadata = (MetadataCollection) ic.UserData; return ParseMetadataAsync (engine, metadata, doAsync, ic.CancellationToken); } internal static async Task<string> ReadStringTokenAsync (ImapEngine engine, string format, bool doAsync, CancellationToken cancellationToken) { var token = await engine.ReadTokenAsync (doAsync, cancellationToken).ConfigureAwait (false); switch (token.Type) { case ImapTokenType.Literal: return await engine.ReadLiteralAsync (doAsync, cancellationToken).ConfigureAwait (false); case ImapTokenType.QString: case ImapTokenType.Atom: return (string) token.Value; default: throw ImapEngine.UnexpectedToken (format, token); } } static async Task<string> ReadNStringTokenAsync (ImapEngine engine, string format, bool rfc2047, bool doAsync, CancellationToken cancellationToken) { var token = await engine.ReadTokenAsync (doAsync, cancellationToken).ConfigureAwait (false); string value; switch (token.Type) { case ImapTokenType.Literal: value = await engine.ReadLiteralAsync (doAsync, cancellationToken).ConfigureAwait (false); break; case ImapTokenType.QString: case ImapTokenType.Atom: value = (string) token.Value; break; case ImapTokenType.Nil: return null; default: throw ImapEngine.UnexpectedToken (format, token); } if (rfc2047) { var encoding = engine.UTF8Enabled ? ImapEngine.UTF8 : ImapEngine.Latin1; return Rfc2047.DecodeText (encoding.GetBytes (value)); } return value; } static async Task<uint> ReadNumberAsync (ImapEngine engine, string format, bool doAsync, CancellationToken cancellationToken) { var token = await engine.ReadTokenAsync (doAsync, cancellationToken).ConfigureAwait (false); // Note: this is a work-around for broken IMAP servers that return negative integer values for things // like octet counts and line counts. if (token.Type == ImapTokenType.Atom) { var atom = (string) token.Value; if (atom.Length > 0 && atom[0] == '-') { if (!int.TryParse (atom, NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out var negative)) throw ImapEngine.UnexpectedToken (format, token); // Note: since Octets & Lines are the only 2 values this method is responsible for parsing, // it seems the only sane value to return would be 0. return 0; } } return ImapEngine.ParseNumber (token, false, format, token); } static bool NeedsQuoting (string value) { for (int i = 0; i < value.Length; i++) { if (value[i] > 127 || char.IsControl (value[i])) return true; if (QuotedSpecials.IndexOf (value[i]) != -1) return true; } return value.Length == 0; } static async Task ParseParameterListAsync (StringBuilder builder, ImapEngine engine, string format, bool doAsync, CancellationToken cancellationToken) { ImapToken token; do { token = await engine.PeekTokenAsync (doAsync, cancellationToken).ConfigureAwait (false); if (token.Type == ImapTokenType.CloseParen) break; var name = await ReadStringTokenAsync (engine, format, doAsync, cancellationToken).ConfigureAwait (false); // Note: technically, the value should also be a 'string' token and not an 'nstring', // but issue #124 reveals a server that is sending NIL for boundary values. var value = await ReadNStringTokenAsync (engine, format, false, doAsync, cancellationToken).ConfigureAwait (false) ?? string.Empty; builder.Append ("; ").Append (name).Append ('='); if (NeedsQuoting (value)) builder.Append (MimeUtils.Quote (value)); else builder.Append (value); } while (true); // read the ')' await engine.ReadTokenAsync (doAsync, cancellationToken).ConfigureAwait (false); } static async Task<object> ParseContentTypeAsync (ImapEngine engine, string format, bool doAsync, CancellationToken cancellationToken) { var type = await ReadNStringTokenAsync (engine, format, false, doAsync, cancellationToken).ConfigureAwait (false) ?? "application"; var token = await engine.PeekTokenAsync (doAsync, cancellationToken).ConfigureAwait (false); ContentType contentType; string subtype; if (token.Type == ImapTokenType.OpenParen || token.Type == ImapTokenType.Nil) { // Note: work around broken IMAP server implementations... if (engine.QuirksMode == ImapQuirksMode.GMail) { // Note: GMail's IMAP server implementation breaks when it encounters // nested multiparts with the same boundary and returns a BODYSTRUCTURE // like the example in https://github.com/jstedfast/MailKit/issues/205 or // like the example in https://github.com/jstedfast/MailKit/issues/777 // // Note: this token is either '(' to start the Content-Type parameter values // or it is a NIL to specify that there are no parameter values. return type; } if (token.Type != ImapTokenType.Nil) { // Note: In other IMAP server implementations, such as the one found in // https://github.com/jstedfast/MailKit/issues/371, if the server comes // across something like "Content-Type: X-ZIP", it will only send a // media-subtype token and completely fail to send a media-type token. subtype = type; type = "application"; } else { await engine.ReadTokenAsync (doAsync, cancellationToken).ConfigureAwait (false); subtype = string.Empty; } } else { subtype = await ReadStringTokenAsync (engine, format, doAsync, cancellationToken).ConfigureAwait (false); } token = await engine.ReadTokenAsync (doAsync, cancellationToken).ConfigureAwait (false); if (token.Type == ImapTokenType.Nil) return new ContentType (type, subtype); ImapEngine.AssertToken (token, ImapTokenType.OpenParen, format, token); var builder = new StringBuilder (); builder.AppendFormat ("{0}/{1}", type, subtype); await ParseParameterListAsync (builder, engine, format, doAsync, cancellationToken).ConfigureAwait (false); if (!ContentType.TryParse (builder.ToString (), out contentType)) contentType = new ContentType (type, subtype); return contentType; } static async Task<ContentDisposition> ParseContentDispositionAsync (ImapEngine engine, string format, bool doAsync, CancellationToken cancellationToken) { // body-fld-dsp = "(" string SP body-fld-param ")" / nil var token = await engine.ReadTokenAsync (doAsync, cancellationToken).ConfigureAwait (false); if (token.Type == ImapTokenType.Nil) return null; if (token.Type != ImapTokenType.OpenParen) { // Note: this is a work-around for issue #919 where Exchange sends `"inline"` instead of `("inline" NIL)` if (token.Type == ImapTokenType.Atom || token.Type == ImapTokenType.QString) return new ContentDisposition ((string) token.Value); throw ImapEngine.UnexpectedToken (format, token); } // Exchange bug: ... (NIL NIL) ... var dsp = await ReadNStringTokenAsync (engine, format, false, doAsync, cancellationToken).ConfigureAwait (false); var builder = new StringBuilder (); ContentDisposition disposition; bool isNil = false; // Note: These are work-arounds for some bugs in some mail clients that // either leave out the disposition value or quote it. // // See https://github.com/jstedfast/MailKit/issues/486 for details. if (string.IsNullOrEmpty (dsp)) builder.Append (ContentDisposition.Attachment); else builder.Append (dsp.Trim ('"')); token = await engine.ReadTokenAsync (doAsync, cancellationToken).ConfigureAwait (false); if (token.Type == ImapTokenType.OpenParen) await ParseParameterListAsync (builder, engine, format, doAsync, cancellationToken).ConfigureAwait (false); else if (token.Type != ImapTokenType.Nil) throw ImapEngine.UnexpectedToken (format, token); else isNil = true; token = await engine.ReadTokenAsync (doAsync, cancellationToken).ConfigureAwait (false); ImapEngine.AssertToken (token, ImapTokenType.CloseParen, format, token); if (dsp == null && isNil) return null; ContentDisposition.TryParse (builder.ToString (), out disposition); return disposition; } static async Task<string[]> ParseContentLanguageAsync (ImapEngine engine, string format, bool doAsync, CancellationToken cancellationToken) { var token = await engine.ReadTokenAsync (doAsync, cancellationToken).ConfigureAwait (false); var languages = new List<string> (); string language; switch (token.Type) { case ImapTokenType.Literal: language = await engine.ReadLiteralAsync (doAsync, cancellationToken).ConfigureAwait (false); languages.Add (language); break; case ImapTokenType.QString: case ImapTokenType.Atom: language = (string) token.Value; languages.Add (language); break; case ImapTokenType.Nil: return null; case ImapTokenType.OpenParen: do { token = await engine.PeekTokenAsync (doAsync, cancellationToken).ConfigureAwait (false); if (token.Type == ImapTokenType.CloseParen) break; // Note: Some broken IMAP servers send `NIL` tokens in this list. Just ignore them. // // See https://github.com/jstedfast/MailKit/issues/953 language = await ReadNStringTokenAsync (engine, format, false, doAsync, cancellationToken).ConfigureAwait (false); if (language != null) languages.Add (language); } while (true); // read the ')' await engine.ReadTokenAsync (doAsync, cancellationToken).ConfigureAwait (false); break; default: throw ImapEngine.UnexpectedToken (format, token); } return languages.ToArray (); } static async Task<Uri> ParseContentLocationAsync (ImapEngine engine, string format, bool doAsync, CancellationToken cancellationToken) { var location = await ReadNStringTokenAsync (engine, format, false, doAsync, cancellationToken).ConfigureAwait (false); if (string.IsNullOrWhiteSpace (location)) return null; if (Uri.IsWellFormedUriString (location, UriKind.Absolute)) return new Uri (location, UriKind.Absolute); if (Uri.IsWellFormedUriString (location, UriKind.Relative)) return new Uri (location, UriKind.Relative); return null; } static async Task SkipBodyExtensionAsync (ImapEngine engine, string format, bool doAsync, CancellationToken cancellationToken) { var token = await engine.ReadTokenAsync (doAsync, cancellationToken).ConfigureAwait (false); switch (token.Type) { case ImapTokenType.OpenParen: do { token = await engine.PeekTokenAsync (doAsync, cancellationToken).ConfigureAwait (false); if (token.Type == ImapTokenType.CloseParen) break; await SkipBodyExtensionAsync (engine, format, doAsync, cancellationToken).ConfigureAwait (false); } while (true); // read the ')' await engine.ReadTokenAsync (doAsync, cancellationToken).ConfigureAwait (false); break; case ImapTokenType.Literal: await engine.ReadLiteralAsync (doAsync, cancellationToken).ConfigureAwait (false); break; case ImapTokenType.QString: case ImapTokenType.Atom: case ImapTokenType.Nil: break; default: throw ImapEngine.UnexpectedToken (format, token); } } static async Task<BodyPart> ParseMultipartAsync (ImapEngine engine, string format, string path, string subtype, bool doAsync, CancellationToken cancellationToken) { var prefix = path.Length > 0 ? path + "." : string.Empty; var body = new BodyPartMultipart (); ImapToken token; int index = 1; // Note: if subtype is not null, then we are working around a GMail bug... if (subtype == null) { do { body.BodyParts.Add (await ParseBodyAsync (engine, format, prefix + index, doAsync, cancellationToken).ConfigureAwait (false)); token = await engine.PeekTokenAsync (doAsync, cancellationToken).ConfigureAwait (false); index++; } while (token.Type == ImapTokenType.OpenParen); subtype = await ReadStringTokenAsync (engine, format, doAsync, cancellationToken).ConfigureAwait (false); } body.ContentType = new ContentType ("multipart", subtype); body.PartSpecifier = path; token = await engine.PeekTokenAsync (doAsync, cancellationToken).ConfigureAwait (false); if (token.Type != ImapTokenType.CloseParen) { token = await engine.ReadTokenAsync (doAsync, cancellationToken).ConfigureAwait (false); ImapEngine.AssertToken (token, ImapTokenType.OpenParen, ImapTokenType.Nil, format, token); var builder = new StringBuilder (); ContentType contentType; builder.AppendFormat ("{0}/{1}", body.ContentType.MediaType, body.ContentType.MediaSubtype); if (token.Type == ImapTokenType.OpenParen) await ParseParameterListAsync (builder, engine, format, doAsync, cancellationToken).ConfigureAwait (false); if (ContentType.TryParse (builder.ToString (), out contentType)) body.ContentType = contentType; token = await engine.PeekTokenAsync (doAsync, cancellationToken).ConfigureAwait (false); } if (token.Type == ImapTokenType.QString) { // Note: This is a work-around for broken Exchange servers. // // See https://stackoverflow.com/questions/33481604/mailkit-fetch-unexpected-token-in-imap-response-qstring-multipart-message // for details. // Read what appears to be a Content-Description. token = await engine.ReadTokenAsync (doAsync, cancellationToken).ConfigureAwait (false); // Peek ahead at the next token. It has been suggested that this next token seems to be the Content-Language value. token = await engine.PeekTokenAsync (doAsync, cancellationToken).ConfigureAwait (false); } else if (token.Type != ImapTokenType.CloseParen) { body.ContentDisposition = await ParseContentDispositionAsync (engine, format, doAsync, cancellationToken).ConfigureAwait (false); token = await engine.PeekTokenAsync (doAsync, cancellationToken).ConfigureAwait (false); } if (token.Type != ImapTokenType.CloseParen) { body.ContentLanguage = await ParseContentLanguageAsync (engine, format, doAsync, cancellationToken).ConfigureAwait (false); token = await engine.PeekTokenAsync (doAsync, cancellationToken).ConfigureAwait (false); } if (token.Type != ImapTokenType.CloseParen) { body.ContentLocation = await ParseContentLocationAsync (engine, format, doAsync, cancellationToken).ConfigureAwait (false); token = await engine.PeekTokenAsync (doAsync, cancellationToken).ConfigureAwait (false); } while (token.Type != ImapTokenType.CloseParen) { await SkipBodyExtensionAsync (engine, format, doAsync, cancellationToken).ConfigureAwait (false); token = await engine.PeekTokenAsync (doAsync, cancellationToken).ConfigureAwait (false); } // read the ')' token = await engine.ReadTokenAsync (doAsync, cancellationToken).ConfigureAwait (false); return body; } public static async Task<BodyPart> ParseBodyAsync (ImapEngine engine, string format, string path, bool doAsync, CancellationToken cancellationToken) { var token = await engine.ReadTokenAsync (doAsync, cancellationToken).ConfigureAwait (false); if (token.Type == ImapTokenType.Nil) return null; ImapEngine.AssertToken (token, ImapTokenType.OpenParen, format, token); token = await engine.PeekTokenAsync (doAsync, cancellationToken).ConfigureAwait (false); // Note: If we immediately get a closing ')', then treat it the same as if we had gotten a `NIL` `body` token. // // See https://github.com/jstedfast/MailKit/issues/944 for details. if (token.Type == ImapTokenType.CloseParen) { await engine.ReadTokenAsync (doAsync, cancellationToken).ConfigureAwait (false); return null; } if (token.Type == ImapTokenType.OpenParen) return await ParseMultipartAsync (engine, format, path, null, doAsync, cancellationToken).ConfigureAwait (false); var result = await ParseContentTypeAsync (engine, format, doAsync, cancellationToken).ConfigureAwait (false); if (result is string) { // GMail breakage... yay! What we have is a nested multipart with // the same boundary as its parent. return await ParseMultipartAsync (engine, format, path, (string) result, doAsync, cancellationToken).ConfigureAwait (false); } var id = await ReadNStringTokenAsync (engine, format, false, doAsync, cancellationToken).ConfigureAwait (false); var desc = await ReadNStringTokenAsync (engine, format, true, doAsync, cancellationToken).ConfigureAwait (false); // Note: technically, body-fld-enc, is not allowed to be NIL, but we need to deal with broken servers... var enc = await ReadNStringTokenAsync (engine, format, false, doAsync, cancellationToken).ConfigureAwait (false); var octets = await ReadNumberAsync (engine, format, doAsync, cancellationToken).ConfigureAwait (false); var type = (ContentType) result; var isMultipart = false; BodyPartBasic body; if (type.IsMimeType ("message", "rfc822")) { var mesg = new BodyPartMessage (); // Note: GMail (and potentially other IMAP servers) will send body-part-basic // expressions instead of body-part-msg expressions when they encounter // message/rfc822 MIME parts that are illegally encoded using base64 (or // quoted-printable?). According to rfc3501, IMAP servers are REQUIRED to // send body-part-msg expressions for message/rfc822 parts, however, it is // understandable why GMail (and other IMAP servers?) do what they do in this // particular case. // // For examples, see issue #32 and issue #59. // // The workaround is to check for the expected '(' signifying an envelope token. // If we do not get an '(', then we are likely looking at the Content-MD5 token // which gets handled below. token = await engine.PeekTokenAsync (doAsync, cancellationToken).ConfigureAwait (false); if (token.Type == ImapTokenType.OpenParen) { mesg.Envelope = await ParseEnvelopeAsync (engine, doAsync, cancellationToken).ConfigureAwait (false); mesg.Body = await ParseBodyAsync (engine, format, path, doAsync, cancellationToken).ConfigureAwait (false); mesg.Lines = await ReadNumberAsync (engine, format, doAsync, cancellationToken).ConfigureAwait (false); } body = mesg; } else if (type.IsMimeType ("text", "*")) { var text = new BodyPartText (); text.Lines = await ReadNumberAsync (engine, format, doAsync, cancellationToken).ConfigureAwait (false); body = text; } else { isMultipart = type.IsMimeType ("multipart", "*"); body = new BodyPartBasic (); } body.ContentTransferEncoding = enc; body.ContentDescription = desc; body.PartSpecifier = path; body.ContentType = type; body.ContentId = id; body.Octets = octets; // if we are parsing a BODYSTRUCTURE, we may get some more tokens before the ')' token = await engine.PeekTokenAsync (doAsync, cancellationToken).ConfigureAwait (false); if (!isMultipart) { if (token.Type != ImapTokenType.CloseParen) { body.ContentMd5 = await ReadNStringTokenAsync (engine, format, false, doAsync, cancellationToken).ConfigureAwait (false); token = await engine.PeekTokenAsync (doAsync, cancellationToken).ConfigureAwait (false); } if (token.Type != ImapTokenType.CloseParen) { body.ContentDisposition = await ParseContentDispositionAsync (engine, format, doAsync, cancellationToken).ConfigureAwait (false); token = await engine.PeekTokenAsync (doAsync, cancellationToken).ConfigureAwait (false); } if (token.Type != ImapTokenType.CloseParen) { body.ContentLanguage = await ParseContentLanguageAsync (engine, format, doAsync, cancellationToken).ConfigureAwait (false); token = await engine.PeekTokenAsync (doAsync, cancellationToken).ConfigureAwait (false); } if (token.Type != ImapTokenType.CloseParen) { body.ContentLocation = await ParseContentLocationAsync (engine, format, doAsync, cancellationToken).ConfigureAwait (false); token = await engine.PeekTokenAsync (doAsync, cancellationToken).ConfigureAwait (false); } } while (token.Type != ImapTokenType.CloseParen) { await SkipBodyExtensionAsync (engine, format, doAsync, cancellationToken).ConfigureAwait (false); token = await engine.PeekTokenAsync (doAsync, cancellationToken).ConfigureAwait (false); } // read the ')' token = await engine.ReadTokenAsync (doAsync, cancellationToken).ConfigureAwait (false); return body; } struct EnvelopeAddress { public readonly string Name; public readonly string Route; public readonly string Mailbox; public readonly string Domain; public EnvelopeAddress (string[] values) { Name = values[0]; Route = values[1]; Mailbox = values[2]; Domain = values[3]; } public bool IsGroupStart { get { return Name == null && Route == null && Mailbox != null && Domain == null; } } public bool IsGroupEnd { get { return Name == null && Route == null && Mailbox == null && Domain == null; } } public MailboxAddress ToMailboxAddress (ImapEngine engine) { var mailbox = Mailbox; var domain = Domain; string name = null; if (Name != null) { var encoding = engine.UTF8Enabled ? ImapEngine.UTF8 : ImapEngine.Latin1; name = Rfc2047.DecodePhrase (encoding.GetBytes (Name)); } // Note: When parsing mailbox addresses w/o a domain, Dovecot will // use "MISSING_DOMAIN" as the domain string to prevent it from // appearing as a group address in the IMAP ENVELOPE response. if (domain == "MISSING_DOMAIN" || domain == ".MISSING-HOST-NAME.") domain = null; else if (domain != null) domain = domain.TrimEnd ('>'); if (mailbox != null) mailbox = mailbox.TrimStart ('<'); string address = domain != null ? mailbox + "@" + domain : mailbox; DomainList route; if (Route != null && DomainList.TryParse (Route, out route)) return new MailboxAddress (name, route, address); return new MailboxAddress (name, address); } public GroupAddress ToGroupAddress (ImapEngine engine) { var name = string.Empty; if (Mailbox != null) { var encoding = engine.UTF8Enabled ? ImapEngine.UTF8 : ImapEngine.Latin1; name = Rfc2047.DecodePhrase (encoding.GetBytes (Mailbox)); } return new GroupAddress (name); } } static async Task<EnvelopeAddress> ParseEnvelopeAddressAsync (ImapEngine engine, string format, bool doAsync, CancellationToken cancellationToken) { var values = new string[4]; ImapToken token; int index = 0; do { token = await engine.ReadTokenAsync (doAsync, cancellationToken).ConfigureAwait (false); switch (token.Type) { case ImapTokenType.Literal: values[index] = await engine.ReadLiteralAsync (doAsync, cancellationToken).ConfigureAwait (false); break; case ImapTokenType.QString: case ImapTokenType.Atom: values[index] = (string) token.Value; break; case ImapTokenType.Nil: break; default: throw ImapEngine.UnexpectedToken (format, token); } index++; } while (index < 4); token = await engine.ReadTokenAsync (doAsync, cancellationToken).ConfigureAwait (false); ImapEngine.AssertToken (token, ImapTokenType.CloseParen, format, token); return new EnvelopeAddress (values); } static async Task ParseEnvelopeAddressListAsync (InternetAddressList list, ImapEngine engine, string format, bool doAsync, CancellationToken cancellationToken) { var token = await engine.ReadTokenAsync (doAsync, cancellationToken).ConfigureAwait (false); if (token.Type == ImapTokenType.Nil) return; ImapEngine.AssertToken (token, ImapTokenType.OpenParen, format, token); var stack = new List<InternetAddressList> (); int sp = 0; stack.Add (list); do { token = await engine.ReadTokenAsync (doAsync, cancellationToken).ConfigureAwait (false); if (token.Type == ImapTokenType.CloseParen) break; // Note: As seen in https://github.com/jstedfast/MailKit/issues/991, some IMAP servers // will include a NIL address token within the address list. Just ignore it. if (token.Type == ImapTokenType.Nil) continue; ImapEngine.AssertToken (token, ImapTokenType.OpenParen, format, token); var address = await ParseEnvelopeAddressAsync (engine, format, doAsync, cancellationToken).ConfigureAwait (false); if (address.IsGroupStart && engine.QuirksMode != ImapQuirksMode.GMail) { var group = address.ToGroupAddress (engine); stack[sp].Add (group); stack.Add (group.Members); sp++; } else if (address.IsGroupEnd) { if (sp > 0) { stack.RemoveAt (sp); sp--; } } else { try { // Note: We need to do a try/catch around ToMailboxAddress() because some addresses // returned by the IMAP server might be completely horked. For an example, see the // second error report in https://github.com/jstedfast/MailKit/issues/494 where one // of the addresses in the ENVELOPE has the name and address tokens flipped. var mailbox = address.ToMailboxAddress (engine); stack[sp].Add (mailbox); } catch { continue; } } } while (true); } static async Task<DateTimeOffset?> ParseEnvelopeDateAsync (ImapEngine engine, string format, bool doAsync, CancellationToken cancellationToken) { var token = await engine.ReadTokenAsync (doAsync, cancellationToken).ConfigureAwait (false); DateTimeOffset date; string value; switch (token.Type) { case ImapTokenType.Literal: value = await engine.ReadLiteralAsync (doAsync, cancellationToken).ConfigureAwait (false); break; case ImapTokenType.QString: case ImapTokenType.Atom: value = (string) token.Value; break; case ImapTokenType.Nil: return null; default: throw ImapEngine.UnexpectedToken (format, token); } if (!DateUtils.TryParse (value, out date)) return null; return date; } /// <summary> /// Parses the ENVELOPE parenthesized list. /// </summary> /// <returns>The envelope.</returns> /// <param name="engine">The IMAP engine.</param> /// <param name="doAsync">Whether or not asynchronous IO methods should be used.</param> /// <param name="cancellationToken">The cancellation token.</param> public static async Task<Envelope> ParseEnvelopeAsync (ImapEngine engine, bool doAsync, CancellationToken cancellationToken) { string format = string.Format (ImapEngine.GenericItemSyntaxErrorFormat, "ENVELOPE", "{0}"); var token = await engine.ReadTokenAsync (doAsync, cancellationToken).ConfigureAwait (false); string nstring; ImapEngine.AssertToken (token, ImapTokenType.OpenParen, format, token); var envelope = new Envelope (); envelope.Date = await ParseEnvelopeDateAsync (engine, format, doAsync, cancellationToken).ConfigureAwait (false); envelope.Subject = await ReadNStringTokenAsync (engine, format, true, doAsync, cancellationToken).ConfigureAwait (false); await ParseEnvelopeAddressListAsync (envelope.From, engine, format, doAsync, cancellationToken).ConfigureAwait (false); await ParseEnvelopeAddressListAsync (envelope.Sender, engine, format, doAsync, cancellationToken).ConfigureAwait (false); await ParseEnvelopeAddressListAsync (envelope.ReplyTo, engine, format, doAsync, cancellationToken).ConfigureAwait (false); await ParseEnvelopeAddressListAsync (envelope.To, engine, format, doAsync, cancellationToken).ConfigureAwait (false); await ParseEnvelopeAddressListAsync (envelope.Cc, engine, format, doAsync, cancellationToken).ConfigureAwait (false); await ParseEnvelopeAddressListAsync (envelope.Bcc, engine, format, doAsync, cancellationToken).ConfigureAwait (false); // Note: Some broken IMAP servers will forget to include the In-Reply-To token (I guess if the header isn't set?). // // See https://github.com/jstedfast/MailKit/issues/932 token = await engine.PeekTokenAsync (doAsync, cancellationToken).ConfigureAwait (false); if (token.Type != ImapTokenType.CloseParen) { if ((nstring = await ReadNStringTokenAsync (engine, format, false, doAsync, cancellationToken).ConfigureAwait (false)) != null) envelope.InReplyTo = MimeUtils.EnumerateReferences (nstring).FirstOrDefault (); // Note: Some broken IMAP servers will forget to include the Message-Id token (I guess if the header isn't set?). // // See https://github.com/jstedfast/MailKit/issues/669 token = await engine.PeekTokenAsync (doAsync, cancellationToken).ConfigureAwait (false); if (token.Type != ImapTokenType.CloseParen) { if ((nstring = await ReadNStringTokenAsync (engine, format, false, doAsync, cancellationToken).ConfigureAwait (false)) != null) { try { envelope.MessageId = MimeUtils.ParseMessageId (nstring); } catch { envelope.MessageId = nstring; } } } } token = await engine.ReadTokenAsync (doAsync, cancellationToken).ConfigureAwait (false); ImapEngine.AssertToken (token, ImapTokenType.CloseParen, format, token); return envelope; } /// <summary> /// Formats a flags list suitable for use with the APPEND command. /// </summary> /// <returns>The flags list string.</returns> /// <param name="flags">The message flags.</param> /// <param name="numUserFlags">The number of user-defined flags.</param> public static string FormatFlagsList (MessageFlags flags, int numUserFlags) { var builder = new StringBuilder (); builder.Append ('('); if ((flags & MessageFlags.Answered) != 0) builder.Append ("\\Answered "); if ((flags & MessageFlags.Deleted) != 0) builder.Append ("\\Deleted "); if ((flags & MessageFlags.Draft) != 0) builder.Append ("\\Draft "); if ((flags & MessageFlags.Flagged) != 0) builder.Append ("\\Flagged "); if ((flags & MessageFlags.Seen) != 0) builder.Append ("\\Seen "); for (int i = 0; i < numUserFlags; i++) builder.Append ("%S "); if (builder.Length > 1) builder.Length--; builder.Append (')'); return builder.ToString (); } /// <summary> /// Parses the flags list. /// </summary> /// <returns>The message flags.</returns> /// <param name="engine">The IMAP engine.</param> /// <param name="name">The name of the flags being parsed.</param> /// <param name="keywords">A hash set of user-defined message flags that will be populated if non-null.</param> /// <param name="doAsync">Whether or not asynchronous IO methods should be used.</param> /// <param name="cancellationToken">The cancellation token.</param> public static async Task<MessageFlags> ParseFlagsListAsync (ImapEngine engine, string name, HashSet<string> keywords, bool doAsync, CancellationToken cancellationToken) { var token = await engine.ReadTokenAsync (doAsync, cancellationToken).ConfigureAwait (false); var flags = MessageFlags.None; ImapEngine.AssertToken (token, ImapTokenType.OpenParen, ImapEngine.GenericItemSyntaxErrorFormat, name, token); token = await engine.ReadTokenAsync (ImapStream.AtomSpecials, doAsync, cancellationToken).ConfigureAwait (false); while (token.Type == ImapTokenType.Atom || token.Type == ImapTokenType.Flag || token.Type == ImapTokenType.QString) { var flag = (string) token.Value; switch (flag) { case "\\Answered": flags |= MessageFlags.Answered; break; case "\\Deleted": flags |= MessageFlags.Deleted; break; case "\\Draft": flags |= MessageFlags.Draft; break; case "\\Flagged": flags |= MessageFlags.Flagged; break; case "\\Seen": flags |= MessageFlags.Seen; break; case "\\Recent": flags |= MessageFlags.Recent; break; case "\\*": flags |= MessageFlags.UserDefined; break; default: if (keywords != null) keywords.Add (flag); break; } token = await engine.ReadTokenAsync (ImapStream.AtomSpecials, doAsync, cancellationToken).ConfigureAwait (false); } ImapEngine.AssertToken (token, ImapTokenType.CloseParen, ImapEngine.GenericItemSyntaxErrorFormat, name, token); return flags; } /// <summary> /// Parses the ANNOTATION list. /// </summary> /// <returns>The list of annotations.</returns> /// <param name="engine">The IMAP engine.</param> /// <param name="doAsync">Whether or not asynchronous IO methods should be used.</param> /// <param name="cancellationToken">The cancellation token.</param> public static async Task<ReadOnlyCollection<Annotation>> ParseAnnotationsAsync (ImapEngine engine, bool doAsync, CancellationToken cancellationToken) { var format = string.Format (ImapEngine.GenericUntaggedResponseSyntaxErrorFormat, "ANNOTATION", "{0}"); var token = await engine.ReadTokenAsync (doAsync, cancellationToken).ConfigureAwait (false); var annotations = new List<Annotation> (); ImapEngine.AssertToken (token, ImapTokenType.OpenParen, ImapEngine.GenericItemSyntaxErrorFormat, "ANNOTATION", token); do { token = await engine.PeekTokenAsync (ImapStream.AtomSpecials, doAsync, cancellationToken).ConfigureAwait (false); if (token.Type == ImapTokenType.CloseParen) break; var path = await ReadStringTokenAsync (engine, format, doAsync, cancellationToken).ConfigureAwait (false); var entry = AnnotationEntry.Parse (path); var annotation = new Annotation (entry); annotations.Add (annotation); token = await engine.PeekTokenAsync (doAsync, cancellationToken).ConfigureAwait (false); // Note: Unsolicited FETCH responses that include ANNOTATION data do not include attribute values. if (token.Type == ImapTokenType.OpenParen) { // consume the '(' await engine.ReadTokenAsync (doAsync, cancellationToken).ConfigureAwait (false); // read the attribute/value pairs do { token = await engine.PeekTokenAsync (ImapStream.AtomSpecials, doAsync, cancellationToken).ConfigureAwait (false); if (token.Type == ImapTokenType.CloseParen) break; var name = await ReadStringTokenAsync (engine, format, doAsync, cancellationToken).ConfigureAwait (false); var value = await ReadNStringTokenAsync (engine, format, false, doAsync, cancellationToken).ConfigureAwait (false); var attribute = new AnnotationAttribute (name); annotation.Properties[attribute] = value; } while (true); // consume the ')' await engine.ReadTokenAsync (doAsync, cancellationToken).ConfigureAwait (false); } } while (true); // consume the ')' await engine.ReadTokenAsync (doAsync, cancellationToken).ConfigureAwait (false); return new ReadOnlyCollection<Annotation> (annotations); } /// <summary> /// Parses the X-GM-LABELS list. /// </summary> /// <returns>The message labels.</returns> /// <param name="engine">The IMAP engine.</param> /// <param name="doAsync">Whether or not asynchronous IO methods should be used.</param> /// <param name="cancellationToken">The cancellation token.</param> public static async Task<ReadOnlyCollection<string>> ParseLabelsListAsync (ImapEngine engine, bool doAsync, CancellationToken cancellationToken) { var token = await engine.ReadTokenAsync (doAsync, cancellationToken).ConfigureAwait (false); var labels = new List<string> (); ImapEngine.AssertToken (token, ImapTokenType.OpenParen, ImapEngine.GenericItemSyntaxErrorFormat, "X-GM-LABELS", token); token = await engine.ReadTokenAsync (ImapStream.AtomSpecials, doAsync, cancellationToken).ConfigureAwait (false); while (token.Type == ImapTokenType.Flag || token.Type == ImapTokenType.Atom || token.Type == ImapTokenType.QString || token.Type == ImapTokenType.Nil) { // Apparently it's possible to set a NIL label in GMail... // // See https://github.com/jstedfast/MailKit/issues/244 for an example. if (token.Type != ImapTokenType.Nil) { var label = engine.DecodeMailboxName ((string) token.Value); labels.Add (label); } else { labels.Add ("NIL"); } token = await engine.ReadTokenAsync (ImapStream.AtomSpecials, doAsync, cancellationToken).ConfigureAwait (false); } ImapEngine.AssertToken (token, ImapTokenType.CloseParen, ImapEngine.GenericItemSyntaxErrorFormat, "X-GM-LABELS", token); return new ReadOnlyCollection<string> (labels); } static async Task<MessageThread> ParseThreadAsync (ImapEngine engine, uint uidValidity, bool doAsync, CancellationToken cancellationToken) { var token = await engine.ReadTokenAsync (doAsync, cancellationToken).ConfigureAwait (false); MessageThread thread, node, child; uint uid; if (token.Type == ImapTokenType.OpenParen) { thread = new MessageThread (UniqueId.Invalid); do { child = await ParseThreadAsync (engine, uidValidity, doAsync, cancellationToken).ConfigureAwait (false); thread.Children.Add (child); token = await engine.ReadTokenAsync (doAsync, cancellationToken).ConfigureAwait (false); } while (token.Type != ImapTokenType.CloseParen); return thread; } uid = ImapEngine.ParseNumber (token, true, ImapEngine.GenericUntaggedResponseSyntaxErrorFormat, "THREAD", token); node = thread = new MessageThread (new UniqueId (uidValidity, uid)); do { token = await engine.ReadTokenAsync (doAsync, cancellationToken).ConfigureAwait (false); if (token.Type == ImapTokenType.CloseParen) break; if (token.Type == ImapTokenType.OpenParen) { child = await ParseThreadAsync (engine, uidValidity, doAsync, cancellationToken).ConfigureAwait (false); node.Children.Add (child); } else { uid = ImapEngine.ParseNumber (token, true, ImapEngine.GenericUntaggedResponseSyntaxErrorFormat, "THREAD", token); child = new MessageThread (new UniqueId (uidValidity, uid)); node.Children.Add (child); node = child; } } while (true); return thread; } /// <summary> /// Parses the threads. /// </summary> /// <returns>The threads.</returns> /// <param name="engine">The IMAP engine.</param> /// <param name="uidValidity">The UIDVALIDITY of the folder.</param> /// <param name="doAsync">Whether or not asynchronous IO methods should be used.</param> /// <param name="cancellationToken">The cancellation token.</param> public static async Task<IList<MessageThread>> ParseThreadsAsync (ImapEngine engine, uint uidValidity, bool doAsync, CancellationToken cancellationToken) { var threads = new List<MessageThread> (); ImapToken token; do { token = await engine.PeekTokenAsync (doAsync, cancellationToken).ConfigureAwait (false); if (token.Type == ImapTokenType.Eoln) break; token = await engine.ReadTokenAsync (doAsync, cancellationToken).ConfigureAwait (false); ImapEngine.AssertToken (token, ImapTokenType.OpenParen, ImapEngine.GenericUntaggedResponseSyntaxErrorFormat, "THREAD", token); threads.Add (await ParseThreadAsync (engine, uidValidity, doAsync, cancellationToken).ConfigureAwait (false)); } while (true); return threads; } } }
37.880096
178
0.700969
[ "MIT" ]
FintanRoche/Mail
MailKit/Net/Imap/ImapUtils.cs
63,186
C#
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Microsoft.WindowsAzure.Storage.Table; using Orleans.Runtime; using Orleans.Clustering.AzureStorage; using Orleans.Clustering.AzureStorage.Utilities; namespace Orleans.AzureUtils { internal class OrleansSiloInstanceManager { public string TableName { get; } private readonly string INSTANCE_STATUS_CREATED = SiloStatus.Created.ToString(); //"Created"; private readonly string INSTANCE_STATUS_ACTIVE = SiloStatus.Active.ToString(); //"Active"; private readonly string INSTANCE_STATUS_DEAD = SiloStatus.Dead.ToString(); //"Dead"; private readonly AzureTableDataManager<SiloInstanceTableEntry> storage; private readonly ILogger logger; internal static TimeSpan initTimeout = AzureTableDefaultPolicies.TableCreationTimeout; public string DeploymentId { get; private set; } private OrleansSiloInstanceManager(string clusterId, string storageConnectionString, string tableName, ILoggerFactory loggerFactory) { DeploymentId = clusterId; TableName = tableName; logger = loggerFactory.CreateLogger<OrleansSiloInstanceManager>(); storage = new AzureTableDataManager<SiloInstanceTableEntry>( tableName, storageConnectionString, loggerFactory); } public static async Task<OrleansSiloInstanceManager> GetManager(string clusterId, string storageConnectionString, string tableName, ILoggerFactory loggerFactory) { var instance = new OrleansSiloInstanceManager(clusterId, storageConnectionString, tableName, loggerFactory); try { await instance.storage.InitTableAsync() .WithTimeout(initTimeout); } catch (TimeoutException te) { string errorMsg = String.Format("Unable to create or connect to the Azure table in {0}", initTimeout); instance.logger.Error((int)TableStorageErrorCode.AzureTable_32, errorMsg, te); throw new OrleansException(errorMsg, te); } catch (Exception ex) { string errorMsg = String.Format("Exception trying to create or connect to the Azure table: {0}", ex.Message); instance.logger.Error((int)TableStorageErrorCode.AzureTable_33, errorMsg, ex); throw new OrleansException(errorMsg, ex); } return instance; } public SiloInstanceTableEntry CreateTableVersionEntry(int tableVersion) { return new SiloInstanceTableEntry { DeploymentId = DeploymentId, PartitionKey = DeploymentId, RowKey = SiloInstanceTableEntry.TABLE_VERSION_ROW, MembershipVersion = tableVersion.ToString(CultureInfo.InvariantCulture) }; } public void RegisterSiloInstance(SiloInstanceTableEntry entry) { entry.Status = INSTANCE_STATUS_CREATED; logger.Info(ErrorCode.Runtime_Error_100270, "Registering silo instance: {0}", entry.ToString()); storage.UpsertTableEntryAsync(entry) .WaitWithThrow(AzureTableDefaultPolicies.TableOperationTimeout); } public void UnregisterSiloInstance(SiloInstanceTableEntry entry) { entry.Status = INSTANCE_STATUS_DEAD; logger.Info(ErrorCode.Runtime_Error_100271, "Unregistering silo instance: {0}", entry.ToString()); storage.UpsertTableEntryAsync(entry) .WaitWithThrow(AzureTableDefaultPolicies.TableOperationTimeout); } public void ActivateSiloInstance(SiloInstanceTableEntry entry) { logger.Info(ErrorCode.Runtime_Error_100272, "Activating silo instance: {0}", entry.ToString()); entry.Status = INSTANCE_STATUS_ACTIVE; storage.UpsertTableEntryAsync(entry) .WaitWithThrow(AzureTableDefaultPolicies.TableOperationTimeout); } public async Task<IList<Uri>> FindAllGatewayProxyEndpoints() { IEnumerable<SiloInstanceTableEntry> gatewaySiloInstances = await FindAllGatewaySilos(); return gatewaySiloInstances.Select(ConvertToGatewayUri).ToList(); } /// <summary> /// Represent a silo instance entry in the gateway URI format. /// </summary> /// <param name="gateway">The input silo instance</param> /// <returns></returns> private static Uri ConvertToGatewayUri(SiloInstanceTableEntry gateway) { int proxyPort = 0; if (!string.IsNullOrEmpty(gateway.ProxyPort)) int.TryParse(gateway.ProxyPort, out proxyPort); int gen = 0; if (!string.IsNullOrEmpty(gateway.Generation)) int.TryParse(gateway.Generation, out gen); SiloAddress address = SiloAddress.New(new IPEndPoint(IPAddress.Parse(gateway.Address), proxyPort), gen); return address.ToGatewayUri(); } private async Task<IEnumerable<SiloInstanceTableEntry>> FindAllGatewaySilos() { if (logger.IsEnabled(LogLevel.Debug)) logger.Debug(ErrorCode.Runtime_Error_100277, "Searching for active gateway silos for deployment {0}.", this.DeploymentId); const string zeroPort = "0"; try { string filterOnPartitionKey = TableQuery.GenerateFilterCondition(nameof(SiloInstanceTableEntry.PartitionKey), QueryComparisons.Equal, this.DeploymentId); string filterOnStatus = TableQuery.GenerateFilterCondition(nameof(SiloInstanceTableEntry.Status), QueryComparisons.Equal, INSTANCE_STATUS_ACTIVE); string filterOnProxyPort = TableQuery.GenerateFilterCondition(nameof(SiloInstanceTableEntry.ProxyPort), QueryComparisons.NotEqual, zeroPort); string query = TableQuery.CombineFilters(filterOnPartitionKey, TableOperators.And, TableQuery.CombineFilters(filterOnStatus, TableOperators.And, filterOnProxyPort)); var queryResults = await storage.ReadTableEntriesAndEtagsAsync(query) .WithTimeout(AzureTableDefaultPolicies.TableOperationTimeout); List<SiloInstanceTableEntry> gatewaySiloInstances = queryResults.Select(entity => entity.Item1).ToList(); logger.Info(ErrorCode.Runtime_Error_100278, "Found {0} active Gateway Silos for deployment {1}.", gatewaySiloInstances.Count, this.DeploymentId); return gatewaySiloInstances; }catch(Exception exc) { logger.Error(ErrorCode.Runtime_Error_100331, string.Format("Error searching for active gateway silos for deployment {0} ", this.DeploymentId), exc); throw; } } public async Task<string> DumpSiloInstanceTable() { var queryResults = await storage.ReadAllTableEntriesForPartitionAsync(this.DeploymentId); SiloInstanceTableEntry[] entries = queryResults.Select(entry => entry.Item1).ToArray(); var sb = new StringBuilder(); sb.Append(String.Format("Deployment {0}. Silos: ", DeploymentId)); // Loop through the results, displaying information about the entity Array.Sort(entries, (e1, e2) => { if (e1 == null) return (e2 == null) ? 0 : -1; if (e2 == null) return (e1 == null) ? 0 : 1; if (e1.SiloName == null) return (e2.SiloName == null) ? 0 : -1; if (e2.SiloName == null) return (e1.SiloName == null) ? 0 : 1; return String.CompareOrdinal(e1.SiloName, e2.SiloName); }); foreach (SiloInstanceTableEntry entry in entries) { sb.AppendLine(String.Format("[IP {0}:{1}:{2}, {3}, Instance={4}, Status={5}]", entry.Address, entry.Port, entry.Generation, entry.HostName, entry.SiloName, entry.Status)); } return sb.ToString(); } internal Task<string> MergeTableEntryAsync(SiloInstanceTableEntry data) { return storage.MergeTableEntryAsync(data, AzureStorageUtils.ANY_ETAG); // we merge this without checking eTags. } internal Task<Tuple<SiloInstanceTableEntry, string>> ReadSingleTableEntryAsync(string partitionKey, string rowKey) { return storage.ReadSingleTableEntryAsync(partitionKey, rowKey); } internal async Task<int> DeleteTableEntries(string clusterId) { if (clusterId == null) throw new ArgumentNullException(nameof(clusterId)); var entries = await storage.ReadAllTableEntriesForPartitionAsync(clusterId); var entriesList = new List<Tuple<SiloInstanceTableEntry, string>>(entries); if (entriesList.Count <= AzureTableDefaultPolicies.MAX_BULK_UPDATE_ROWS) { await storage.DeleteTableEntriesAsync(entriesList); }else { List<Task> tasks = new List<Task>(); foreach (var batch in entriesList.BatchIEnumerable(AzureTableDefaultPolicies.MAX_BULK_UPDATE_ROWS)) { tasks.Add(storage.DeleteTableEntriesAsync(batch)); } await Task.WhenAll(tasks); } return entriesList.Count(); } internal async Task<List<Tuple<SiloInstanceTableEntry, string>>> FindSiloEntryAndTableVersionRow(SiloAddress siloAddress) { string rowKey = SiloInstanceTableEntry.ConstructRowKey(siloAddress); string filterOnPartitionKey = TableQuery.GenerateFilterCondition(nameof(SiloInstanceTableEntry.PartitionKey), QueryComparisons.Equal, this.DeploymentId); string filterOnRowKey1 = TableQuery.GenerateFilterCondition(nameof(SiloInstanceTableEntry.RowKey), QueryComparisons.Equal, rowKey); string filterOnRowKey2 = TableQuery.GenerateFilterCondition(nameof(SiloInstanceTableEntry.RowKey), QueryComparisons.Equal, SiloInstanceTableEntry.TABLE_VERSION_ROW); string query = TableQuery.CombineFilters(filterOnPartitionKey, TableOperators.And, TableQuery.CombineFilters(filterOnRowKey1, TableOperators.Or, filterOnRowKey2)); var queryResults = await storage.ReadTableEntriesAndEtagsAsync(query); var asList = queryResults.ToList(); if (asList.Count < 1 || asList.Count > 2) throw new KeyNotFoundException(string.Format("Could not find table version row or found too many entries. Was looking for key {0}, found = {1}", siloAddress.ToLongString(), Utils.EnumerableToString(asList))); int numTableVersionRows = asList.Count(tuple => tuple.Item1.RowKey == SiloInstanceTableEntry.TABLE_VERSION_ROW); if (numTableVersionRows < 1) throw new KeyNotFoundException(string.Format("Did not read table version row. Read = {0}", Utils.EnumerableToString(asList))); if (numTableVersionRows > 1) throw new KeyNotFoundException(string.Format("Read {0} table version rows, while was expecting only 1. Read = {1}", numTableVersionRows, Utils.EnumerableToString(asList))); return asList; } internal async Task<List<Tuple<SiloInstanceTableEntry, string>>> FindAllSiloEntries() { var queryResults = await storage.ReadAllTableEntriesForPartitionAsync(this.DeploymentId); var asList = queryResults.ToList(); if (asList.Count < 1) throw new KeyNotFoundException(string.Format("Could not find enough rows in the FindAllSiloEntries call. Found = {0}", Utils.EnumerableToString(asList))); int numTableVersionRows = asList.Count(tuple => tuple.Item1.RowKey == SiloInstanceTableEntry.TABLE_VERSION_ROW); if (numTableVersionRows < 1) throw new KeyNotFoundException(string.Format("Did not find table version row. Read = {0}", Utils.EnumerableToString(asList))); if (numTableVersionRows > 1) throw new KeyNotFoundException(string.Format("Read {0} table version rows, while was expecting only 1. Read = {1}", numTableVersionRows, Utils.EnumerableToString(asList))); return asList; } /// <summary> /// Insert (create new) row entry /// </summary> internal async Task<bool> TryCreateTableVersionEntryAsync() { try { var versionRow = await storage.ReadSingleTableEntryAsync(DeploymentId, SiloInstanceTableEntry.TABLE_VERSION_ROW); if (versionRow != null && versionRow.Item1 != null) { return false; } SiloInstanceTableEntry entry = CreateTableVersionEntry(0); await storage.CreateTableEntryAsync(entry); return true; } catch (Exception exc) { HttpStatusCode httpStatusCode; string restStatus; if (!AzureStorageUtils.EvaluateException(exc, out httpStatusCode, out restStatus)) throw; if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("InsertSiloEntryConditionally failed with httpStatusCode={0}, restStatus={1}", httpStatusCode, restStatus); if (AzureStorageUtils.IsContentionError(httpStatusCode)) return false; throw; } } /// <summary> /// Insert (create new) row entry /// </summary> /// <param name="siloEntry">Silo Entry to be written</param> /// <param name="tableVersionEntry">Version row to update</param> /// <param name="tableVersionEtag">Version row eTag</param> internal async Task<bool> InsertSiloEntryConditionally(SiloInstanceTableEntry siloEntry, SiloInstanceTableEntry tableVersionEntry, string tableVersionEtag) { try { await storage.InsertTwoTableEntriesConditionallyAsync(siloEntry, tableVersionEntry, tableVersionEtag); return true; } catch (Exception exc) { HttpStatusCode httpStatusCode; string restStatus; if (!AzureStorageUtils.EvaluateException(exc, out httpStatusCode, out restStatus)) throw; if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("InsertSiloEntryConditionally failed with httpStatusCode={0}, restStatus={1}", httpStatusCode, restStatus); if (AzureStorageUtils.IsContentionError(httpStatusCode)) return false; throw; } } /// <summary> /// Conditionally update the row for this entry, but only if the eTag matches with the current record in data store /// </summary> /// <param name="siloEntry">Silo Entry to be written</param> /// <param name="entryEtag">ETag value for the entry being updated</param> /// <param name="tableVersionEntry">Version row to update</param> /// <param name="versionEtag">ETag value for the version row</param> /// <returns></returns> internal async Task<bool> UpdateSiloEntryConditionally(SiloInstanceTableEntry siloEntry, string entryEtag, SiloInstanceTableEntry tableVersionEntry, string versionEtag) { try { await storage.UpdateTwoTableEntriesConditionallyAsync(siloEntry, entryEtag, tableVersionEntry, versionEtag); return true; } catch (Exception exc) { HttpStatusCode httpStatusCode; string restStatus; if (!AzureStorageUtils.EvaluateException(exc, out httpStatusCode, out restStatus)) throw; if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("UpdateSiloEntryConditionally failed with httpStatusCode={0}, restStatus={1}", httpStatusCode, restStatus); if (AzureStorageUtils.IsContentionError(httpStatusCode)) return false; throw; } } } }
49.360119
224
0.644739
[ "MIT" ]
AzureMentor/orleans
src/Azure/Orleans.Clustering.AzureStorage/OrleansSiloInstanceManager.cs
16,585
C#
using System; using System.Collections.Generic; namespace Nez { public abstract class PassiveSystem : EntitySystem { public override void onChange(Entity entity) { // We do not manage any notification of entities changing state and avoid polluting our list of entities as we want to keep it empty } protected override void process(List<Entity> entities) { // We replace the basic entity system with our own that doesn't take into account entities begin(); end(); } } }
29
145
0.631034
[ "MIT" ]
RaiderSoap/Warband
Nez.Portable/ECS/Systems/PassiveSystem.cs
582
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _11.MaxSequenceOfEqualElements { class MaxSequenceOfEqualElements { static void Main(string[] args) { int[] numbers = Console.ReadLine().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries) .Select(int.Parse) .ToArray(); int counter = 1; int maxCount = 1; int n = numbers[0]; for (int i = 0; i < numbers.Length -1; i++) { if (numbers[i] == numbers[i + 1]) { counter++; if (maxCount < counter) { maxCount = counter; n = numbers[i]; } } else { counter = 1; } } int[] result = new int[maxCount]; for (int i = 0; i < result.Length; i++) { result[i] = n; } Console.WriteLine(string.Join(" ", result)); } } }
27.613636
111
0.415638
[ "MIT" ]
Tedo74/SoftUni-fundamentals
Lists/11.MaxSequenceOfEqualElements/MaxSequenceOfEqualElements.cs
1,217
C#
namespace Andreys.Controllers { using Andreys.Services; using Andreys.ViewModels.Products; using SIS.HTTP; using SIS.MvcFramework; public class ProductsController : Controller { private readonly IProductsService productsService; public ProductsController(IProductsService productsService) { this.productsService = productsService; } public HttpResponse Add() { if (!this.IsUserLoggedIn()) { return this.Redirect("/Users/Login"); } return this.View(); } [HttpPost] public HttpResponse Add(ProductAddInputModel inputModel) { if (!this.IsUserLoggedIn()) { return this.Redirect("/Users/Login"); } if (inputModel.Name.Length < 4 || inputModel.Name.Length > 20) { return this.View(); } if (string.IsNullOrEmpty(inputModel.Description) || inputModel.Description.Length > 10) { return this.View(); } var productId = this.productsService.Add(inputModel); return this.Redirect($"/Products/Details?id={productId}"); } public HttpResponse Details(int id) { if (!this.IsUserLoggedIn()) { return this.Redirect("/Users/Login"); } var product = this.productsService.GetById(id); return this.View(product); } public HttpResponse Delete(int id) { if (!this.IsUserLoggedIn()) { return this.Redirect("/Users/Login"); } this.productsService.DeleteById(id); return this.Redirect("/"); } } }
25.142857
101
0.5
[ "MIT" ]
Avanguarde/csharp-web
2020-Jan-Season/SoftUni-Information-Services/SIS/Andreys/Controllers/ProductsController.cs
1,938
C#
using Cabinet.Core.Progress; using ManyConsole; using System; using System.IO; namespace Cabinet.ConsoleTest { public class DownloadCommand : ConsoleCommand { private string configName; private string key; private string filePath; public DownloadCommand() { IsCommand("download", "Gets a file from the cabinet"); HasRequiredOption("cabinet=|c=", "Cabinet to download the file from", c => configName = c); HasRequiredOption("key=|k=", "Key to of the file to download", k => key = k); HasRequiredOption("file-path=|f=", "File Path to save file to", f => filePath = f); } public override int Run(string[] remainingArguments) { var config = Program.CabinetConfigStore.GetConfig(configName); var cabinet = Program.CabinetFactory.GetCabinet(config); Console.WriteLine($"Starting download {key}..."); Nito.AsyncEx.AsyncContext.Run(async () => { using(var writeStream = File.OpenWrite(filePath)) { using(var readStream = await cabinet.OpenReadStreamAsync(key)) { long? length = readStream.TryGetStreamLength(); var progressStream = new ProgressStream(key, writeStream, length, new ConsoleProgress()); await readStream.CopyToAsync(progressStream); } } }); Console.WriteLine(); Console.WriteLine($"Completed downloading {key} to {filePath}"); return 0; } } }
37.44186
113
0.588199
[ "MIT" ]
johncmckim/cabinet
test/Cabinet.ConsoleTest/DownloadCommand.cs
1,612
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.Kusto.V20191109 { /// <summary> /// Class representing a Kusto cluster. /// </summary> [AzureNativeResourceType("azure-native:kusto/v20191109:Cluster")] public partial class Cluster : Pulumi.CustomResource { /// <summary> /// The cluster data ingestion URI. /// </summary> [Output("dataIngestionUri")] public Output<string> DataIngestionUri { get; private set; } = null!; /// <summary> /// A boolean value that indicates if the cluster's disks are encrypted. /// </summary> [Output("enableDiskEncryption")] public Output<bool?> EnableDiskEncryption { get; private set; } = null!; /// <summary> /// A boolean value that indicates if the streaming ingest is enabled. /// </summary> [Output("enableStreamingIngest")] public Output<bool?> EnableStreamingIngest { get; private set; } = null!; /// <summary> /// The identity of the cluster, if configured. /// </summary> [Output("identity")] public Output<Outputs.IdentityResponse?> Identity { get; private set; } = null!; /// <summary> /// KeyVault properties for the cluster encryption. /// </summary> [Output("keyVaultProperties")] public Output<Outputs.KeyVaultPropertiesResponse?> KeyVaultProperties { get; private set; } = null!; /// <summary> /// The geo-location where the resource lives /// </summary> [Output("location")] public Output<string> Location { get; private set; } = null!; /// <summary> /// The name of the resource /// </summary> [Output("name")] public Output<string> Name { get; private set; } = null!; /// <summary> /// Optimized auto scale definition. /// </summary> [Output("optimizedAutoscale")] public Output<Outputs.OptimizedAutoscaleResponse?> OptimizedAutoscale { get; private set; } = null!; /// <summary> /// The provisioned state of the resource. /// </summary> [Output("provisioningState")] public Output<string> ProvisioningState { get; private set; } = null!; /// <summary> /// The SKU of the cluster. /// </summary> [Output("sku")] public Output<Outputs.AzureSkuResponse> Sku { get; private set; } = null!; /// <summary> /// The state of the resource. /// </summary> [Output("state")] public Output<string> State { get; private set; } = null!; /// <summary> /// The reason for the cluster's current state. /// </summary> [Output("stateReason")] public Output<string> StateReason { get; private set; } = null!; /// <summary> /// Resource tags. /// </summary> [Output("tags")] public Output<ImmutableDictionary<string, string>?> Tags { get; private set; } = null!; /// <summary> /// The cluster's external tenants. /// </summary> [Output("trustedExternalTenants")] public Output<ImmutableArray<Outputs.TrustedExternalTenantResponse>> TrustedExternalTenants { get; private set; } = null!; /// <summary> /// The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" /// </summary> [Output("type")] public Output<string> Type { get; private set; } = null!; /// <summary> /// The cluster URI. /// </summary> [Output("uri")] public Output<string> Uri { get; private set; } = null!; /// <summary> /// Virtual network definition. /// </summary> [Output("virtualNetworkConfiguration")] public Output<Outputs.VirtualNetworkConfigurationResponse?> VirtualNetworkConfiguration { get; private set; } = null!; /// <summary> /// The availability zones of the cluster. /// </summary> [Output("zones")] public Output<ImmutableArray<string>> Zones { get; private set; } = null!; /// <summary> /// Create a Cluster resource with the given unique name, arguments, and options. /// </summary> /// /// <param name="name">The unique name of the resource</param> /// <param name="args">The arguments used to populate this resource's properties</param> /// <param name="options">A bag of options that control this resource's behavior</param> public Cluster(string name, ClusterArgs args, CustomResourceOptions? options = null) : base("azure-native:kusto/v20191109:Cluster", name, args ?? new ClusterArgs(), MakeResourceOptions(options, "")) { } private Cluster(string name, Input<string> id, CustomResourceOptions? options = null) : base("azure-native:kusto/v20191109:Cluster", name, null, MakeResourceOptions(options, id)) { } private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id) { var defaultOptions = new CustomResourceOptions { Version = Utilities.Version, Aliases = { new Pulumi.Alias { Type = "azure-nextgen:kusto/v20191109:Cluster"}, new Pulumi.Alias { Type = "azure-native:kusto:Cluster"}, new Pulumi.Alias { Type = "azure-nextgen:kusto:Cluster"}, new Pulumi.Alias { Type = "azure-native:kusto/v20170907privatepreview:Cluster"}, new Pulumi.Alias { Type = "azure-nextgen:kusto/v20170907privatepreview:Cluster"}, new Pulumi.Alias { Type = "azure-native:kusto/v20180907preview:Cluster"}, new Pulumi.Alias { Type = "azure-nextgen:kusto/v20180907preview:Cluster"}, new Pulumi.Alias { Type = "azure-native:kusto/v20190121:Cluster"}, new Pulumi.Alias { Type = "azure-nextgen:kusto/v20190121:Cluster"}, new Pulumi.Alias { Type = "azure-native:kusto/v20190515:Cluster"}, new Pulumi.Alias { Type = "azure-nextgen:kusto/v20190515:Cluster"}, new Pulumi.Alias { Type = "azure-native:kusto/v20190907:Cluster"}, new Pulumi.Alias { Type = "azure-nextgen:kusto/v20190907:Cluster"}, new Pulumi.Alias { Type = "azure-native:kusto/v20200215:Cluster"}, new Pulumi.Alias { Type = "azure-nextgen:kusto/v20200215:Cluster"}, new Pulumi.Alias { Type = "azure-native:kusto/v20200614:Cluster"}, new Pulumi.Alias { Type = "azure-nextgen:kusto/v20200614:Cluster"}, new Pulumi.Alias { Type = "azure-native:kusto/v20200918:Cluster"}, new Pulumi.Alias { Type = "azure-nextgen:kusto/v20200918:Cluster"}, new Pulumi.Alias { Type = "azure-native:kusto/v20210101:Cluster"}, new Pulumi.Alias { Type = "azure-nextgen:kusto/v20210101:Cluster"}, }, }; var merged = CustomResourceOptions.Merge(defaultOptions, options); // Override the ID if one was specified for consistency with other language SDKs. merged.Id = id ?? merged.Id; return merged; } /// <summary> /// Get an existing Cluster resource's state with the given name, ID, and optional extra /// properties used to qualify the lookup. /// </summary> /// /// <param name="name">The unique name of the resulting resource.</param> /// <param name="id">The unique provider ID of the resource to lookup.</param> /// <param name="options">A bag of options that control this resource's behavior</param> public static Cluster Get(string name, Input<string> id, CustomResourceOptions? options = null) { return new Cluster(name, id, options); } } public sealed class ClusterArgs : Pulumi.ResourceArgs { /// <summary> /// The name of the Kusto cluster. /// </summary> [Input("clusterName")] public Input<string>? ClusterName { get; set; } /// <summary> /// A boolean value that indicates if the cluster's disks are encrypted. /// </summary> [Input("enableDiskEncryption")] public Input<bool>? EnableDiskEncryption { get; set; } /// <summary> /// A boolean value that indicates if the streaming ingest is enabled. /// </summary> [Input("enableStreamingIngest")] public Input<bool>? EnableStreamingIngest { get; set; } /// <summary> /// The identity of the cluster, if configured. /// </summary> [Input("identity")] public Input<Inputs.IdentityArgs>? Identity { get; set; } /// <summary> /// KeyVault properties for the cluster encryption. /// </summary> [Input("keyVaultProperties")] public Input<Inputs.KeyVaultPropertiesArgs>? KeyVaultProperties { get; set; } /// <summary> /// The geo-location where the resource lives /// </summary> [Input("location")] public Input<string>? Location { get; set; } /// <summary> /// Optimized auto scale definition. /// </summary> [Input("optimizedAutoscale")] public Input<Inputs.OptimizedAutoscaleArgs>? OptimizedAutoscale { get; set; } /// <summary> /// The name of the resource group containing the Kusto cluster. /// </summary> [Input("resourceGroupName", required: true)] public Input<string> ResourceGroupName { get; set; } = null!; /// <summary> /// The SKU of the cluster. /// </summary> [Input("sku", required: true)] public Input<Inputs.AzureSkuArgs> Sku { get; set; } = null!; [Input("tags")] private InputMap<string>? _tags; /// <summary> /// Resource tags. /// </summary> public InputMap<string> Tags { get => _tags ?? (_tags = new InputMap<string>()); set => _tags = value; } [Input("trustedExternalTenants")] private InputList<Inputs.TrustedExternalTenantArgs>? _trustedExternalTenants; /// <summary> /// The cluster's external tenants. /// </summary> public InputList<Inputs.TrustedExternalTenantArgs> TrustedExternalTenants { get => _trustedExternalTenants ?? (_trustedExternalTenants = new InputList<Inputs.TrustedExternalTenantArgs>()); set => _trustedExternalTenants = value; } /// <summary> /// Virtual network definition. /// </summary> [Input("virtualNetworkConfiguration")] public Input<Inputs.VirtualNetworkConfigurationArgs>? VirtualNetworkConfiguration { get; set; } [Input("zones")] private InputList<string>? _zones; /// <summary> /// The availability zones of the cluster. /// </summary> public InputList<string> Zones { get => _zones ?? (_zones = new InputList<string>()); set => _zones = value; } public ClusterArgs() { EnableStreamingIngest = false; } } }
39.885522
130
0.581378
[ "Apache-2.0" ]
sebtelko/pulumi-azure-native
sdk/dotnet/Kusto/V20191109/Cluster.cs
11,846
C#
// Copyright (c) Arctium. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Arctium.Manager { class Program { static void Main(string[] args) { } } }
17.928571
101
0.625498
[ "MIT" ]
World0fWarcraft/WoW-Core
src/Arctium.Manager/src/ServerManager.cs
253
C#
namespace EntityFx.BenchmarkDb.Contracts.Cpu { public class MemorySpecs { public uint? Controllers { get; set; } public uint? Channels { get; set; } public decimal? BandwidthInMbPerSec { get; set; } public decimal? MaxMemorySizeInMb { get; set; } public MemoryType? MemoryType { get; set; } public string Details { get; set; } public bool? EccOnly { get; set; } } }
23.157895
57
0.606818
[ "MIT" ]
EntityFX/BenchmarksWeb
src/EntityFx.BenchmarkDb.Contracts/Cpu/MemorySpecs.cs
442
C#
namespace GameMain { public enum FlyWordType { None, //无 NormalHurt, //普通受伤 CritHurt, //暴击受伤 HpHeal, //血量回复 MpHeal, //魔法回复 Miss, //闪避 Parry, //格挡 } }
17.571429
27
0.414634
[ "MIT" ]
feng1995911/demo_tankWar3D
Assets/GameMain/UI/Define/FlyWordType.cs
290
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Runtime.CompilerServices; using System.Threading.Tasks; using Microsoft.UI.Dispatching; using Microsoft.UI.Xaml; using Windows.Foundation.Metadata; using Windows.UI.ViewManagement; // TODO: Fix tests for WinUI3 // [assembly: InternalsVisibleTo("UnitTests.XamlIslands.UWPApp")] namespace CommunityToolkit.WinUI.UI.Helpers { /// <summary> /// The Delegate for a ThemeChanged Event. /// </summary> /// <param name="sender">Sender ThemeListener</param> public delegate void ThemeChangedEvent(ThemeListener sender); /// <summary> /// Class which listens for changes to Application Theme or High Contrast Modes /// and Signals an Event when they occur. /// </summary> [AllowForWeb] public sealed class ThemeListener : IDisposable { /// <summary> /// Gets the Name of the Current Theme. /// </summary> public string CurrentThemeName { get { return this.CurrentTheme.ToString(); } } /// <summary> /// Gets or sets the Current Theme. /// </summary> public ApplicationTheme CurrentTheme { get; set; } /// <summary> /// Gets or sets a value indicating whether the current theme is high contrast. /// </summary> public bool IsHighContrast { get; set; } /// <summary> /// Gets or sets which DispatcherQueue is used to dispatch UI updates. /// </summary> public DispatcherQueue DispatcherQueue { get; set; } /// <summary> /// An event that fires if the Theme changes. /// </summary> public event ThemeChangedEvent ThemeChanged; private AccessibilitySettings _accessible = new AccessibilitySettings(); private UISettings _settings = new UISettings(); /// <summary> /// Initializes a new instance of the <see cref="ThemeListener"/> class. /// </summary> /// <param name="dispatcherQueue">The DispatcherQueue that should be used to dispatch UI updates, or null if this is being called from the UI thread.</param> public ThemeListener(DispatcherQueue dispatcherQueue = null) { CurrentTheme = Application.Current.RequestedTheme; IsHighContrast = _accessible.HighContrast; DispatcherQueue = dispatcherQueue ?? DispatcherQueue.GetForCurrentThread(); if (Window.Current != null) { _accessible.HighContrastChanged += Accessible_HighContrastChanged; _settings.ColorValuesChanged += Settings_ColorValuesChanged; Window.Current.CoreWindow.Activated += CoreWindow_Activated; } } private async void Accessible_HighContrastChanged(AccessibilitySettings sender, object args) { #if DEBUG global::System.Diagnostics.Debug.WriteLine("HighContrast Changed"); #endif await OnThemePropertyChangedAsync(); } // Note: This can get called multiple times during HighContrast switch, do we care? private async void Settings_ColorValuesChanged(UISettings sender, object args) { await OnThemePropertyChangedAsync(); } /// <summary> /// Dispatches an update for the public properties and the firing of <see cref="ThemeChanged"/> on <see cref="DispatcherQueue"/>. /// </summary> /// <returns>A <see cref="Task"/> that indicates when the dispatching has completed.</returns> internal Task OnThemePropertyChangedAsync() { // Getting called off thread, so we need to dispatch to request value. return DispatcherQueue.EnqueueAsync( () => { // TODO: This doesn't stop the multiple calls if we're in our faked 'White' HighContrast Mode below. if (CurrentTheme != Application.Current.RequestedTheme || IsHighContrast != _accessible.HighContrast) { #if DEBUG global::System.Diagnostics.Debug.WriteLine("Color Values Changed"); #endif UpdateProperties(); } }, DispatcherQueuePriority.Normal); } private void CoreWindow_Activated(Windows.UI.Core.CoreWindow sender, Windows.UI.Core.WindowActivatedEventArgs args) { if (CurrentTheme != Application.Current.RequestedTheme || IsHighContrast != _accessible.HighContrast) { #if DEBUG global::System.Diagnostics.Debug.WriteLine("CoreWindow Activated Changed"); #endif UpdateProperties(); } } /// <summary> /// Set our current properties and fire a change notification. /// </summary> private void UpdateProperties() { // TODO: Not sure if HighContrastScheme names are localized? if (_accessible.HighContrast && _accessible.HighContrastScheme.IndexOf("white", StringComparison.OrdinalIgnoreCase) != -1) { // If our HighContrastScheme is ON & a lighter one, then we should remain in 'Light' theme mode for Monaco Themes Perspective IsHighContrast = false; CurrentTheme = ApplicationTheme.Light; } else { // Otherwise, we just set to what's in the system as we'd expect. IsHighContrast = _accessible.HighContrast; CurrentTheme = Application.Current.RequestedTheme; } ThemeChanged?.Invoke(this); } /// <inheritdoc/> public void Dispose() { _accessible.HighContrastChanged -= Accessible_HighContrastChanged; _settings.ColorValuesChanged -= Settings_ColorValuesChanged; if (Window.Current != null) { Window.Current.CoreWindow.Activated -= CoreWindow_Activated; } } } }
37.951515
165
0.615937
[ "MIT" ]
w-ahmad/WindowsCommunityToolkit
CommunityToolkit.WinUI.UI/Helpers/ThemeListener.cs
6,262
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System; using System.Globalization; using System.Reflection; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure.WebJobs.Host.Protocols; namespace Microsoft.Azure.WebJobs.Host.Bindings { internal class TraceWriterBinding : IBinding { private readonly ParameterInfo _parameter; public TraceWriterBinding(ParameterInfo parameter) { _parameter = parameter; } public bool FromAttribute { get { return false; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "TraceWriter")] public Task<IValueProvider> BindAsync(object value, ValueBindingContext context) { if (value == null || !_parameter.ParameterType.IsAssignableFrom(value.GetType())) { throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "Unable to convert value to {0}.", _parameter.ParameterType)); } IValueProvider valueProvider = new ValueBinder(value, _parameter.ParameterType); return Task.FromResult<IValueProvider>(valueProvider); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] public Task<IValueProvider> BindAsync(BindingContext context) { if (context == null) { throw new ArgumentNullException("context"); } object tracer = null; if (_parameter.ParameterType == typeof(TraceWriter)) { // bind directly to the context TraceWriter tracer = context.Trace; } else { // bind to an adapter tracer = new TextWriterTraceAdapter(context.Trace); } return BindAsync(tracer, context.ValueContext); } public ParameterDescriptor ToParameterDescriptor() { return new ParameterDescriptor { Name = _parameter.Name }; } private sealed class ValueBinder : IValueBinder { private readonly object _tracer; private readonly Type _type; public ValueBinder(object tracer, Type type) { _tracer = tracer; _type = type; } public Type Type { get { return _type; } } public Task<object> GetValueAsync() { return Task.FromResult(_tracer); } public string ToInvokeString() { return null; } public Task SetValueAsync(object value, CancellationToken cancellationToken) { TextWriterTraceAdapter traceAdapter = value as TextWriterTraceAdapter; if (traceAdapter != null) { traceAdapter.Flush(); } return Task.FromResult(0); } } } }
31.203704
158
0.572107
[ "MIT" ]
StoneFinch/azure-webjobs-sdk
src/Microsoft.Azure.WebJobs.Host/Bindings/TraceWriter/TraceWriterBinding.cs
3,372
C#
using System; using Newtonsoft.Json; namespace TdLib { /// <summary> /// AUTOGENERATED: DO NOT EDIT! /// </summary> public partial class TdApi { public class SetPassportElementErrors : Function<Ok> { [JsonProperty("@type")] public override string DataType { get; set; } = "setPassportElementErrors"; [JsonProperty("@extra")] public override string Extra { get; set; } [JsonConverter(typeof(Converter))] [JsonProperty("user_id")] public int UserId { get; set; } [JsonConverter(typeof(Converter))] [JsonProperty("errors")] public InputPassportElementError[] Errors { get; set; } } } }
28.076923
111
0.584932
[ "MIT" ]
Behnam-Emamian/tdsharp
TDLib.Api/Functions/SetPassportElementErrors.cs
730
C#
using System; using System.Collections.Generic; using System.Text; using AutoFixture.NUnit3; using FluentAssertions; using NUnit.Framework; using SFA.DAS.Campaign.Domain.Content.HtmlControl; using SFA.DAS.Campaign.Infrastructure.Api.Converters; using SFA.DAS.Campaign.Web.Renderers; namespace SFA.DAS.Campaign.UnitTests.Web.Renderers { public class WhenRelatedArticlesRenderer { [Test, AutoData] public void Is_Passed_An_Object_Of_IHtmlControl_That_Is_Of_RelatedArticle_Then_Supports_Content_Returns_True(ArticleRelated article, ArticleRelatedControlRenderer renderer) { var actual = renderer.SupportsContent(article); actual.Should().BeTrue(); } [Test, AutoData] public void Is_Passed_An_Object_Of_IHtmlControl_That_Is_Not_Of_Attachment_Then_Supports_Content_Returns_False(Table table, ArticleRelatedControlRenderer renderer) { var actual = renderer.SupportsContent(table); actual.Should().BeFalse(); } [Test, AutoData] public void Is_Passed_An_Object_Of_Attachment_Then_Render_Returns_The_Html(ArticleRelatedControlRenderer renderer) { var attachment = new ArticleRelated() { Description = "description", Title = "title", HubType = "hub", Slug = "slug", Summary = "summary" }; var actual = renderer.Render(attachment); actual.Value.Should().NotBeNullOrWhiteSpace(); actual.Value.Should().Be("<div class=\"govuk-grid-column-one-half\"><div class=\"fiu-card\"><span class=\"fiu-card__category\"><a class=\"fiu-card__category-link\" href=\"/hub/slug\">title</a></span><h3 class=\"fiu-card__heading\">title</h3><p class=\"fiu-card__content\">description</p><a href=\"/hub/slug\" class=\"fiu-card__link\">Learn more <span class=\"fiu-vh\"> about title</span></a></div></div>"); } } }
40.14
418
0.66567
[ "MIT" ]
SkillsFundingAgency/das-campaign
src/SFA.DAS.Campaign.UnitTests/Web/Renderers/WhenRelatedArticlesRenderer.cs
2,009
C#
using Documentor.Config; using Documentor.Constants; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Options; using System; using System.IO; using System.Linq; using System.Threading.Tasks; namespace Documentor.Services.Impl { public class CacheManager : ICacheManager { private readonly CacheSettings _cacheSettings; private readonly IHostingEnvironment _hostingEnvironment; public CacheManager(IOptionsSnapshot<IOConfig> configOptions, IHostingEnvironment hostingEnvironment) { if (configOptions == null) throw new ArgumentNullException(nameof(configOptions)); if (hostingEnvironment == null) throw new ArgumentNullException(nameof(hostingEnvironment)); _cacheSettings = configOptions.Value.Cache; _hostingEnvironment = hostingEnvironment; } public DirectoryInfo GetCacheDirectory() { if (string.IsNullOrWhiteSpace(_cacheSettings.Path)) throw new InvalidOperationException("Cache directory undefined"); DirectoryInfo cacheDirectory = new DirectoryInfo(Path.Combine(_hostingEnvironment.ContentRootPath, _cacheSettings.Path)); if (!cacheDirectory.Exists) cacheDirectory.Create(); return cacheDirectory; } public async Task SaveToCacheAsync(string cachename, string cache) { if (string.IsNullOrWhiteSpace(cachename)) throw new ArgumentNullException(nameof(cachename)); DirectoryInfo cacheDirectory = GetCacheDirectory(); await File.WriteAllTextAsync(Path.Combine(cacheDirectory.FullName, GetCacheFilename(cachename)), cache); } public async Task<string> LoadFromCacheAsync(string cachename) { if (string.IsNullOrWhiteSpace(cachename)) throw new ArgumentNullException(nameof(cachename)); FileInfo cacheFile = GetCacheFile(cachename); if (cacheFile == null || !cacheFile.Exists) return null; return await File.ReadAllTextAsync(cacheFile.FullName); } public void ClearCache() { DirectoryInfo cacheDirectory = GetCacheDirectory(); cacheDirectory.GetFiles() .Where(f => f.CreationTime < DateTime.Now.AddSeconds(0 - _cacheSettings.Expire)) .ToList() .ForEach(f => f.Delete()); } public void ClearCache(string pattern) { if (string.IsNullOrWhiteSpace(pattern)) ClearCache(); DirectoryInfo cacheDirectory = GetCacheDirectory(); cacheDirectory.GetFiles(GetCacheFilename(pattern), SearchOption.TopDirectoryOnly) .ToList() .ForEach(f => f.Delete()); } private FileInfo GetCacheFile(string cachename) { return GetCacheDirectory() .GetFiles(GetCacheFilename(cachename), SearchOption.TopDirectoryOnly) .FirstOrDefault(); } private static string GetCacheFilename(string cachename) { return Path.GetFileNameWithoutExtension(cachename) + Cache.FileExtension; } } }
35.073684
133
0.633553
[ "MIT" ]
askalione/documentor
src/Documentor/Services/Impl/CacheManager.cs
3,334
C#
using System.Collections.Generic; using DsmSuite.DsmViewer.Model.Interfaces; namespace DsmSuite.DsmViewer.Model.Persistency { public interface IDsmRelationModelFileCallback { IDsmRelation ImportRelation(int id, IDsmElement consumer, IDsmElement provider, string type, int weight, bool deleted); IEnumerable<IDsmRelation> GetExportedRelations(); int GetExportedRelationCount(); } }
30
127
0.764286
[ "MIT" ]
dsmsuite/dsmsuite.sourcecode
DsmSuite.DsmViewer.Model/Persistency/IDsmRelationModelFileCallback.cs
422
C#
private static ISldWorks StartSwAppBackground(string appPath, int timeoutSec = 20) { var timeout = TimeSpan.FromSeconds(timeoutSec); var startTime = DateTime.Now; var prcInfo = new ProcessStartInfo() { FileName = appPath, Arguments = "/r", //no splash screen CreateNoWindow = true, WindowStyle = ProcessWindowStyle.Hidden }; var prc = Process.Start(prcInfo); ISldWorks app = null; var isLoaded = false; var onIdleFunc = new DSldWorksEvents_OnIdleNotifyEventHandler(() => { isLoaded = true; return 0; }); try { while (!isLoaded) { if (DateTime.Now - startTime > timeout) { throw new TimeoutException(); } if (app == null) { app = GetSwAppFromProcess(prc.Id); if (app != null) { (app as SldWorks).OnIdleNotify += onIdleFunc; } } System.Threading.Thread.Sleep(100); } if (app != null) { const int HIDE = 0; ShowWindow(new IntPtr(app.IFrameObject().GetHWnd()), HIDE); } } catch { throw; } finally { if (app != null) { (app as SldWorks).OnIdleNotify -= onIdleFunc; } } return app; }
20.666667
82
0.490884
[ "MIT" ]
EddyAlleman/codestack
solidworks-api/getting-started/stand-alone/start-background/Program.cs
1,426
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from um/winnetwk.h in the Windows SDK for Windows 10.0.20348.0 // Original source is Copyright © Microsoft. All rights reserved. using NUnit.Framework; using System.Runtime.InteropServices; namespace TerraFX.Interop.UnitTests { /// <summary>Provides validation of the <see cref="NETCONNECTINFOSTRUCT" /> struct.</summary> public static unsafe partial class NETCONNECTINFOSTRUCTTests { /// <summary>Validates that the <see cref="NETCONNECTINFOSTRUCT" /> struct is blittable.</summary> [Test] public static void IsBlittableTest() { Assert.That(Marshal.SizeOf<NETCONNECTINFOSTRUCT>(), Is.EqualTo(sizeof(NETCONNECTINFOSTRUCT))); } /// <summary>Validates that the <see cref="NETCONNECTINFOSTRUCT" /> struct has the right <see cref="LayoutKind" />.</summary> [Test] public static void IsLayoutSequentialTest() { Assert.That(typeof(NETCONNECTINFOSTRUCT).IsLayoutSequential, Is.True); } /// <summary>Validates that the <see cref="NETCONNECTINFOSTRUCT" /> struct has the correct size.</summary> [Test] public static void SizeOfTest() { Assert.That(sizeof(NETCONNECTINFOSTRUCT), Is.EqualTo(20)); } } }
39.583333
145
0.678596
[ "MIT" ]
DaZombieKiller/terrafx.interop.windows
tests/Interop/Windows/um/winnetwk/NETCONNECTINFOSTRUCTTests.cs
1,427
C#
using CompanySales.Model.Entity; using CompanySales.Model; using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; using CompanySales.Common; using CompanySales.Model.Parameter; namespace CompanySales.DAL { public class ProductDAO { public static List<Product> GetList() { using (SaleContext db = new SaleContext()) { return db.Product.ToList(); } } public static bool AddProduct(Product entity) { using (SaleContext db = new SaleContext()) { db.Product.Add(entity); db.SaveChanges(); return true; } } /// <summary> /// 根据产品编号返回产品对象 /// 如果不存在该产品则返回null /// </summary> /// <param name="id"></param> /// <returns></returns> public static Product GetProductById(int id) { using (SaleContext db = new SaleContext()) { var res = db.Product.Find(id); return res; } } public static bool Update(Product entity) { using (SaleContext db = new SaleContext()) { var dbEntity = db.Product.Find(entity.ProductID); if (null == dbEntity) { Log4Helper.InfoLog.Warn("未找到该product id:" + entity.ProductID); return false; } else { dbEntity.Price = entity.Price; dbEntity.ProductName = entity.ProductName; // 更新时不更新库存和已销售数量 //dbEntity.ProductSellNumber = entity.ProductSellNumber; //dbEntity.ProductStockNumber = entity.ProductStockNumber; db.SaveChanges(); return true; } } } public static Pager<Product> GetListByPage(ProductParameter parameter) { Pager<Product> result = new Pager<Product>(); using (SaleContext db = new SaleContext()) { var query = db.Product.AsQueryable(); if (!string.IsNullOrEmpty(parameter.ProductName)) { query = query.Where(t => t.ProductName.Contains(parameter.ProductName)); } result.Total = query.Count(); result.Rows = query.OrderBy(t => t.ProductID) .Skip(parameter.Skip) .Take(parameter.PageSize) .ToList(); return result; } } public static bool DeleteById(int id) { using (SaleContext db = new SaleContext()) { var entity = db.Product.Find(id); if (null != entity) { db.Product.Remove(entity); db.SaveChanges(); return true; } else { Log4Helper.InfoLog.Warn("未找到该product id:" + id); return false; } } } public static bool BatchDelete(string[] ids) { using (SaleContext db = new SaleContext()) { var list = db.Product.Where(t => ids.Contains(t.ProductID.ToString())); db.Product.RemoveRange(list); db.SaveChanges(); return true; } } } }
30.72
93
0.451823
[ "Apache-2.0" ]
imwyw/.net
Src/CompanySalesDemo/CompanySales.DAL/DAO/ProductDAO.cs
3,936
C#
// ***************************************************************************** // BSD 3-Clause License (https://github.com/ComponentFactory/Krypton/blob/master/LICENSE) // Created by Peter Wagner(aka Wagnerp) & Simon Coghlan(aka Smurf-IV) 2019 - 2019. All rights reserved. (https://github.com/Wagnerp/Krypton-NET-5.472) // Version 5.472.0.0 www.ComponentFactory.com // ***************************************************************************** using System; using System.Windows.Forms; using ComponentFactory.Krypton.Toolkit; namespace TestTextClipping { public partial class Form1 : KryptonForm { public Form1() { InitializeComponent(); } private void kryptonOffice2010Blue_CheckedChanged(object sender, EventArgs e) { if (kryptonOffice2010Blue.Checked) { kryptonManager.GlobalPaletteMode = PaletteModeManager.Office2010Blue; } } private void kryptonOffice2010Silver_CheckedChanged(object sender, EventArgs e) { if (kryptonOffice2010Silver.Checked) { kryptonManager.GlobalPaletteMode = PaletteModeManager.Office2010Silver; } } private void kryptonOffice2010Black_CheckedChanged(object sender, EventArgs e) { if (kryptonOffice2010Black.Checked) { kryptonManager.GlobalPaletteMode = PaletteModeManager.Office2010Black; } } private void kryptonOffice2007Blue_CheckedChanged(object sender, EventArgs e) { if (kryptonOffice2007Blue.Checked) { kryptonManager.GlobalPaletteMode = PaletteModeManager.Office2007Blue; } } private void kryptonOffice2007Silver_CheckedChanged(object sender, EventArgs e) { if (kryptonOffice2007Silver.Checked) { kryptonManager.GlobalPaletteMode = PaletteModeManager.Office2007Silver; } } private void kryptonOffice2007Black_CheckedChanged(object sender, EventArgs e) { if (kryptonOffice2007Black.Checked) { kryptonManager.GlobalPaletteMode = PaletteModeManager.Office2007Black; } } private void kryptonOffice2003_CheckedChanged(object sender, EventArgs e) { if (kryptonOffice2003.Checked) { kryptonManager.GlobalPaletteMode = PaletteModeManager.ProfessionalOffice2003; } } private void kryptonSystem_CheckedChanged(object sender, EventArgs e) { if (kryptonSystem.Checked) { kryptonManager.GlobalPaletteMode = PaletteModeManager.ProfessionalSystem; } } private void kryptonSparkleBlue_CheckedChanged(object sender, EventArgs e) { if (kryptonSparkleBlue.Checked) { kryptonManager.GlobalPaletteMode = PaletteModeManager.SparkleBlue; } } private void kryptonSparkleOrange_CheckedChanged(object sender, EventArgs e) { if (kryptonSparkleOrange.Checked) { kryptonManager.GlobalPaletteMode = PaletteModeManager.SparkleOrange; } } private void kryptonSparklePurple_CheckedChanged(object sender, EventArgs e) { if (kryptonSparklePurple.Checked) { kryptonManager.GlobalPaletteMode = PaletteModeManager.SparklePurple; } } private void kryptonCustom_CheckedChanged(object sender, EventArgs e) { if (kryptonCustom.Checked) { kryptonManager.GlobalPalette = kryptonPaletteCustom; } } private void OnClick(object sender, EventArgs e) { KryptonMessageBox.Show(this, ((Control)sender).Name, @"Single click detected on ..."); } private void OnMouseClick(object sender, MouseEventArgs e) { KryptonMessageBox.Show(this, ((Control)sender).Name, @"Mouse click detected on ..."); } private void kryptonOffice2013_CheckedChanged(object sender, EventArgs e) { if (kryptonOffice2013.Checked) { kryptonManager.GlobalPaletteMode = PaletteModeManager.Office2013; } } private void kryptonOffice2013White_CheckedChanged(object sender, EventArgs e) { if (kryptonOffice2013White.Checked) { kryptonManager.GlobalPaletteMode = PaletteModeManager.Office2013White; } } private void InnerControl_MouseEnter(object sender, EventArgs e) { kryptonListBox1.Items.Add($"MouseEnter- {sender}"); } private void InnerControl_MouseLeave(object sender, EventArgs e) { kryptonListBox1.Items.Add("MouseLeave"); } } }
32.735484
151
0.58987
[ "BSD-3-Clause" ]
dave-w-au/Krypton-NET-5.472
Source/Krypton Toolkit Examples/Test Text Clipping/Form1.cs
5,076
C#
using System; using System.Diagnostics.CodeAnalysis; using Infrastructure.Extensions; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using NLog.Web; namespace API { public class Program { public static void Main(string[] args) { var logger = NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger(); try { logger.Debug("Starting service"); CreateHostBuilder(args).Build().Run(); } catch (Exception e) { logger.Error(e, "Stopped service because of an exception"); throw; } finally { NLog.LogManager.Shutdown(); } } public static IWebHostBuilder CreateHostBuilder([AllowNull] string[] args = null) => WebHost .CreateDefaultBuilder(args) .UseLogging() .ConfigureShutdownTimeout() .UseConfigurations() .UseNLog() .UseKestrel() .UseStartup<Startup>(); } }
27.571429
92
0.518998
[ "MIT" ]
SmeeK153/PayrollPlayground
Backend/API/Program.cs
1,158
C#
using UnityEngine; namespace Utils { public static class MaterialHelper { /// <summary> /// https://docs.unity3d.com/ScriptReference/Mathf.PerlinNoise.html /// </summary> /// <returns></returns> public static Material RandomMaterial(string shaderName, int resolution=256) { var noiseTex = CalcNoise(resolution); var mat = new Material(Shader.Find(shaderName)) {mainTexture = noiseTex}; return mat; } private static Texture2D CalcNoise(int resolution) { var noiseTex = new Texture2D(resolution, resolution); var pix = new Color[noiseTex.width * noiseTex.height]; // For each pixel in the texture... var y = 0.0F; while (y < noiseTex.height) { var x = 0.0F; while (x < noiseTex.width) { var xCoords = x / noiseTex.width; var yCoords = y / noiseTex.height; var sample = Mathf.PerlinNoise(xCoords, yCoords); pix[(int) y * noiseTex.width + (int) x] = new Color(sample, sample, sample); x++; } y++; } // Copy the pixel data to the texture and load it into the GPU. noiseTex.SetPixels(pix); noiseTex.Apply(); return noiseTex; } // TODO: super ugly code ! public static Texture2D RandomTexture(Transform transform, int resolution = 256, FilterMode filterMode = FilterMode.Trilinear, int anisolevel = 9, NoiseMethodType type = NoiseMethodType.Perlin, int dimensions = 3, float frequency = 1f, int octaves = 1, float lacunarity = 2f, float persistence = 0.5f, Gradient gradient = null) { var texture = new Texture2D(resolution, resolution, TextureFormat.RGB24, true) { name = "Procedural Texture", wrapMode = TextureWrapMode.Clamp, filterMode = filterMode, anisoLevel = anisolevel }; texture.FillTexture(transform, resolution, type, dimensions, frequency, octaves, lacunarity, persistence, gradient); return texture; } public static void FillTexture (this Texture2D texture, Transform transform, int resolution = 256, NoiseMethodType type = NoiseMethodType.Perlin, int dimensions = 3, float frequency = 1f, int octaves = 1, float lacunarity = 2f, float persistence = 0.5f, Gradient gradient = null) { if (gradient == null) { gradient = new Gradient(); // Populate the color keys at the relative time 0 and 1 (0 and 100%) var colorKey = new GradientColorKey[3]; colorKey[0].color = Color.red; colorKey[0].time = 0.0f; colorKey[1].color = Color.blue; colorKey[1].time = 0.5f; colorKey[2].color = Color.green; colorKey[2].time = 1.0f; // Populate the alpha keys at relative time 0 and 1 (0 and 100%) var alphaKey = new GradientAlphaKey[3]; alphaKey[0].alpha = 1.0f; alphaKey[0].time = 0.0f; alphaKey[1].alpha = 1.0f; alphaKey[1].time = 0.5f; alphaKey[2].alpha = 1.0f; alphaKey[2].time = 1.0f; gradient.SetKeys(colorKey, alphaKey); } if (texture.width != resolution) { texture.Resize(resolution, resolution); } Vector3 point00 = transform.TransformPoint(new Vector3(-0.5f,-0.5f)); Vector3 point10 = transform.TransformPoint(new Vector3( 0.5f,-0.5f)); Vector3 point01 = transform.TransformPoint(new Vector3(-0.5f, 0.5f)); Vector3 point11 = transform.TransformPoint(new Vector3( 0.5f, 0.5f)); NoiseMethod method = Noise.methods[(int)type][dimensions - 1]; float stepSize = 1f / resolution; for (int y = 0; y < resolution; y++) { Vector3 point0 = Vector3.Lerp(point00, point01, (y + 0.5f) * stepSize); Vector3 point1 = Vector3.Lerp(point10, point11, (y + 0.5f) * stepSize); for (int x = 0; x < resolution; x++) { Vector3 point = Vector3.Lerp(point0, point1, (x + 0.5f) * stepSize); float sample = Noise.Sum(method, point, frequency, octaves, lacunarity, persistence); if (type != NoiseMethodType.Value) { sample = sample * 0.5f + 0.5f; } texture.SetPixel(x, y, gradient.Evaluate(sample)); } } texture.Apply(); } } }
42.376068
128
0.529447
[ "MIT" ]
louis030195/niwrad
Assets/Scripts/Utils/MaterialHelper.cs
4,958
C#
// <copyright file="IPhoneBook.cs" company="Jan-Willem Spuij"> // Copyright 2020 Jan-Willem Spuij // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, // modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom // the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE // WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // </copyright> namespace RedCow.Test { using System; using System.Collections.Generic; using System.Text; /// <summary> /// A phone book. /// </summary> [GenerateProducers(typeof(PhoneBook))] public partial interface IPhoneBook { /// <summary> /// Gets the phone book entries. /// </summary> public IReadOnlyDictionary<string, TestPerson> Entries { get; } } }
45.457143
129
0.727844
[ "MIT" ]
jspuij/RedCow
test/RedCow.Test/IPhoneBook.cs
1,593
C#
using System; using System.Collections.Generic; namespace MyDiet_API.Shared.Auth { public class UserManagerResponse { public string Message { get; set; } public bool IsSuccess{ get; set; } public string Token { get; set; } public IEnumerable<string> Errors { get; set; } public DateTime? ExpireDate { get; set; } } }
23.25
55
0.637097
[ "MIT" ]
FrancescoRepo/MyDietAPI
MyDiet_API.Shared/Auth/UserManagerResponse.cs
374
C#
using AutoMapper; using AycProjectBudgeting.Authorization.Users; namespace AycProjectBudgeting.Users.Dto { public class UserMapProfile : Profile { public UserMapProfile() { CreateMap<UserDto, User>(); CreateMap<UserDto, User>() .ForMember(x => x.Roles, opt => opt.Ignore()) .ForMember(x => x.CreationTime, opt => opt.Ignore()); CreateMap<CreateUserDto, User>(); CreateMap<CreateUserDto, User>().ForMember(x => x.Roles, opt => opt.Ignore()); } } }
28.3
90
0.579505
[ "MIT" ]
ZhakulIhnaac/WebProjesi2
aspnet-core/src/AycProjectBudgeting.Application/Users/Dto/UserMapProfile.cs
568
C#
using System; using MvvmHelpers; namespace VMFirstNav { public class RootTabViewModel : BaseViewModel { public RootTabViewModel() { Title = "Root Tabs"; } } }
12.357143
46
0.699422
[ "Apache-2.0" ]
codemillmatt/XamFormsVMNav
VMFirstNav/VMFirstNav/ViewModels/Tabs/RootTabViewModel.cs
175
C#
using System; using System.Drawing; using System.Runtime.InteropServices; using System.Windows.Forms; namespace MediaBrowser.Theater.DirectShow { public class CustomCursor { [DllImport("user32.dll")] public static extern IntPtr CreateIconIndirect(ref IconInfo icon); [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool GetIconInfo(IntPtr hIcon, ref IconInfo pIconInfo); public static Cursor CreateCursor(Bitmap bmp, int xHotSpot, int yHotSpot) { IconInfo tmp = new IconInfo(); GetIconInfo(bmp.GetHicon(), ref tmp); tmp.xHotspot = xHotSpot; tmp.yHotspot = yHotSpot; tmp.fIcon = false; return new Cursor(CreateIconIndirect(ref tmp)); } public struct IconInfo { public bool fIcon; public int xHotspot; public int yHotspot; public IntPtr hbmMask; public IntPtr hbmColor; } } }
28.378378
84
0.613333
[ "MIT" ]
thogil/MediaBrowser.Theater
MediaBrowser.Theater.DirectShow/CustomCursor.cs
1,052
C#
using System.Threading.Tasks; using Core.Interfaces; using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.DependencyInjection; namespace Web.Extensions { public static class ApplicationBuilderExtensions { public static async Task UseBucketInitializer(this IApplicationBuilder app) { using var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>()?.CreateScope(); var client = serviceScope?.ServiceProvider.GetRequiredService<IObjectStorageService>(); var buckets = new[] { "public" }; foreach (var bucket in buckets) if (client != null) await client.CreateBucket(bucket); } } }
32.041667
111
0.643693
[ "MIT" ]
grroma/mems
Backend/src/Web/Extensions/ApplicationBuilderExtensions.cs
769
C#
#pragma checksum "C:\Users\Rolando\Desktop\BTCPAY\btcpayserver-master\btcpayserver-master\BTCPayServer\Views\Account\SignedOut.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "6f49014d0b9f63827b0d0d922dd53a76e52fe6e4" // <auto-generated/> #pragma warning disable 1591 [assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCore.Views_Account_SignedOut), @"mvc.1.0.view", @"/Views/Account/SignedOut.cshtml")] [assembly:global::Microsoft.AspNetCore.Mvc.Razor.Compilation.RazorViewAttribute(@"/Views/Account/SignedOut.cshtml", typeof(AspNetCore.Views_Account_SignedOut))] namespace AspNetCore { #line hidden using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.AspNetCore.Mvc.ViewFeatures; #line 1 "C:\Users\Rolando\Desktop\BTCPAY\btcpayserver-master\btcpayserver-master\BTCPayServer\Views\_ViewImports.cshtml" using Microsoft.AspNetCore.Identity; #line default #line hidden #line 2 "C:\Users\Rolando\Desktop\BTCPAY\btcpayserver-master\btcpayserver-master\BTCPayServer\Views\_ViewImports.cshtml" using BTCPayServer; #line default #line hidden #line 3 "C:\Users\Rolando\Desktop\BTCPAY\btcpayserver-master\btcpayserver-master\BTCPayServer\Views\_ViewImports.cshtml" using BTCPayServer.Views; #line default #line hidden #line 4 "C:\Users\Rolando\Desktop\BTCPAY\btcpayserver-master\btcpayserver-master\BTCPayServer\Views\_ViewImports.cshtml" using BTCPayServer.Models; #line default #line hidden #line 5 "C:\Users\Rolando\Desktop\BTCPAY\btcpayserver-master\btcpayserver-master\BTCPayServer\Views\_ViewImports.cshtml" using BTCPayServer.Models.AccountViewModels; #line default #line hidden #line 6 "C:\Users\Rolando\Desktop\BTCPAY\btcpayserver-master\btcpayserver-master\BTCPayServer\Views\_ViewImports.cshtml" using BTCPayServer.Models.InvoicingModels; #line default #line hidden #line 7 "C:\Users\Rolando\Desktop\BTCPAY\btcpayserver-master\btcpayserver-master\BTCPayServer\Views\_ViewImports.cshtml" using BTCPayServer.Models.ManageViewModels; #line default #line hidden #line 8 "C:\Users\Rolando\Desktop\BTCPAY\btcpayserver-master\btcpayserver-master\BTCPayServer\Views\_ViewImports.cshtml" using BTCPayServer.Models.StoreViewModels; #line default #line hidden [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"6f49014d0b9f63827b0d0d922dd53a76e52fe6e4", @"/Views/Account/SignedOut.cshtml")] [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"d92ba4c5be7894d31e45019b21d323a2a5285d5b", @"/Views/_ViewImports.cshtml")] public class Views_Account_SignedOut : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<dynamic> { #pragma warning disable 1998 public async override global::System.Threading.Tasks.Task ExecuteAsync() { #line 1 "C:\Users\Rolando\Desktop\BTCPAY\btcpayserver-master\btcpayserver-master\BTCPayServer\Views\Account\SignedOut.cshtml" ViewData["Title"] = "Signed out"; #line default #line hidden BeginContext(43, 5, true); WriteLiteral("\n<h2>"); EndContext(); BeginContext(49, 17, false); #line 5 "C:\Users\Rolando\Desktop\BTCPAY\btcpayserver-master\btcpayserver-master\BTCPayServer\Views\Account\SignedOut.cshtml" Write(ViewData["Title"]); #line default #line hidden EndContext(); BeginContext(66, 53, true); WriteLiteral("</h2>\n<p>\n You have successfully signed out.\n</p>\n"); EndContext(); } #pragma warning restore 1998 [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<dynamic> Html { get; private set; } } } #pragma warning restore 1591
47.752577
218
0.772237
[ "MIT" ]
CristianBanexcoin/banexcoinpay
BTCPayServer/obj/Debug/netcoreapp2.1/Razor/Views/Account/SignedOut.g.cshtml.cs
4,632
C#
using BecauseImClever.PointingPoker.Models.Enums; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Duracellko.PlanningPoker.Domain.Test { [TestClass] public class MemberMessageTest { [TestMethod] public void Constructor_TypeSpecified_MessageTypeIsSet() { // Arrange var type = MessageType.MemberJoined; // Act var result = new MemberMessage(type); // Verify Assert.AreEqual<MessageType>(type, result.MessageType); } [TestMethod] public void Member_Set_MemberIsSet() { // Arrange var target = new MemberMessage(MessageType.MemberJoined); var team = new ScrumTeam("test team"); var member = new Member(team, "test"); // Act target.Member = member; // Verify Assert.AreEqual<Observer>(member, target.Member); } } }
25.789474
69
0.580612
[ "MIT" ]
Fortinbra/planningpoker4azure
test/Duracellko.PlanningPoker.Domain.Test/MemberMessageTest.cs
982
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("View Creation by Discipline for Revit 2015")] [assembly: AssemblyDescription("View Creation by Discipline for Revit 2015")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Case Design, Inc.")] [assembly: AssemblyProduct("View Creation by Discipline for Revit 2015")] [assembly: AssemblyCopyright("Copyright © Case Design, Inc. 2013")] [assembly: AssemblyTrademark("Case Design, Inc.")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("118f7279-630d-4661-afe5-c23c23acf46f")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("2014.6.2.0")] [assembly: AssemblyFileVersion("2014.6.2.0")]
42.054054
84
0.751928
[ "MIT" ]
johnpierson/case-apps
2015/Case.ViewCreator/Case.ViewCreator/Properties/AssemblyInfo.cs
1,559
C#
// Copyright 2020 Andreas Atteneder // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // namespace GLTFast.Schema { [System.Serializable] public class MaterialUnlit { } }
33
75
0.734488
[ "Apache-2.0" ]
Gfi-Innovation/UMI3D-Desktop-Browser
UMI3D-Browser-Desktop/Assets/UMI3D SDK/Dependencies/Runtime/GltFast/Runtime/Scripts/Schema/MaterialUnlit.cs
693
C#
using FubuCore; using FubuLocalization; namespace FubuMVC.Core.Navigation { public class AddBefore : IMenuPlacementStrategy { public string FormatDescription(string matcherDescription, StringToken nodeKey) { return "Insert '{0}' before '{1}'".ToFormat(nodeKey.ToLocalizationKey(), matcherDescription); } public void Apply(IMenuNode dependency, MenuNode node) { dependency.AddBefore(node); } } }
27.611111
106
0.635815
[ "Apache-2.0" ]
DovetailSoftware/fubumvc
src/FubuMVC.Core/Navigation/AddBefore.cs
497
C#
/* Copyright 2020 Research group ICT innovations in Health Care, Windesheim University of Applied Sciences Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; namespace OpenWindesheart.Models { public class ActivitySample { public byte[] RawData { get; } public DateTime Timestamp { get; } public int UnixEpochTimestamp { get; } public int Category { get; } public int RawIntensity { get; } public int Steps { get; } public int HeartRate { get; } public ActivitySample(DateTime timestamp, int category, int intensity, int steps, int heartrate, byte[] rawdata = null) { this.RawData = rawdata; this.Timestamp = timestamp; this.UnixEpochTimestamp = (Int32)(timestamp.Subtract(new DateTime(1970, 1, 1))).TotalSeconds; this.Category = category; this.RawIntensity = intensity; this.Steps = steps; this.HeartRate = heartrate; } } }
36.634146
127
0.677763
[ "Apache-2.0" ]
LuisL3/openwindesheart
OpenWindesheart/Models/ActivitySample.cs
1,504
C#
// <auto-generated /> using Cinema.WebApi.Contexts; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; namespace Cinema.WebApi.Migrations.Movie { [DbContext(typeof(MovieContext))] [Migration("20200424174214_movies")] partial class movies { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "3.0.0") .HasAnnotation("Relational:MaxIdentifierLength", 128) .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("Cinema.WebApi.Models.Movie", b => { b.Property<string>("Id") .ValueGeneratedOnAdd() .HasColumnType("nvarchar(450)"); b.Property<string>("Actors") .IsRequired() .HasColumnType("nvarchar(600)") .HasMaxLength(600); b.Property<string>("Director") .IsRequired() .HasColumnType("nvarchar(600)") .HasMaxLength(600); b.Property<string>("Genre") .IsRequired() .HasColumnType("nvarchar(40)") .HasMaxLength(40); b.Property<bool>("Playing") .HasColumnType("bit"); b.Property<string>("Plot") .IsRequired() .HasColumnType("nvarchar(600)") .HasMaxLength(600); b.Property<string>("Poster") .IsRequired() .HasColumnType("nvarchar(600)") .HasMaxLength(600); b.Property<string>("Rated") .IsRequired() .HasColumnType("nvarchar(10)") .HasMaxLength(10); b.Property<string>("Released") .IsRequired() .HasColumnType("nvarchar(20)") .HasMaxLength(20); b.Property<string>("Runtime") .IsRequired() .HasColumnType("nvarchar(10)") .HasMaxLength(10); b.Property<string>("Title") .IsRequired() .HasColumnType("nvarchar(30)") .HasMaxLength(30); b.Property<string>("Year") .IsRequired() .HasColumnType("nvarchar(4)") .HasMaxLength(4); b.HasKey("Id"); b.ToTable("Movies"); b.HasData( new { Id = "31446c42-fa95-4f38-8b8a-c5830649ca32", Actors = "Christina Milian, Adam Demos, Jeffrey Bowyer-Chapman, Anna Jullienne", Director = "Roger Kumble", Genre = "Comedy, Romance", Playing = true, Plot = "When city girl Gabriela spontaneously enters a contest and wins a rustic New Zealand inn, she teams up with bighearted contractor Jake Taylor to fix and flip it.", Poster = "https://m.media-amazon.com/images/M/MV5BNWE1NmMzNjUtMDc3NS00ZjBlLTllMTktZTVkMWQzZGVlYzdhXkEyXkFqcGdeQXVyMTkxNjUyNQ@@._V1_SX300.jpg", Rated = "TV-PG", Released = "29 Aug 2019", Runtime = "98 min", Title = "Falling Inn Love", Year = "2019" }, new { Id = "59c58d93-e15b-4d2c-94a2-03e82b82d7c2", Actors = "Alban Lenoir, Olga Kurylenko, Sébastien Lalanne, David Murgia", Director = "Fred Grivois", Genre = "Action, Drama, History, War", Playing = true, Plot = "In February 1976 in Djibouti, a school bus was taken hostage at the Somali border. The GIGN is sent on the spot. After 30 hours of tension, a rescue operation is organized.", Poster = "https://m.media-amazon.com/images/M/MV5BMDZiNDcxYzItN2JhNy00MjgxLTgyNjMtNzdiOWU1Y2MwODYxXkEyXkFqcGdeQXVyNzc0MTgzMzU@._V1_SX300.jpg", Rated = "TV-14", Released = "30 Jan 2019", Runtime = "98 min", Title = "15 Minutes of War", Year = "2019" }, new { Id = "164ca3af-4b7f-454f-bd07-9b8d6c3736cc", Actors = "Tom Holland, Samuel L. Jackson, Jake Gyllenhaal, Marisa Tomei", Director = "Jon Watts", Genre = "Action, Adventure, Sci-Fi", Playing = true, Plot = "Following the events of Avengers: Endgame (2019), Spider-Man must step up to take on new threats in a world that has changed forever.", Poster = "https://m.media-amazon.com/images/M/MV5BMGZlNTY1ZWUtYTMzNC00ZjUyLWE0MjQtMTMxN2E3ODYxMWVmXkEyXkFqcGdeQXVyMDM2NDM2MQ@@._V1_SX300.jpg", Rated = "PG-13", Released = "02 Jul 2019", Runtime = "129 min", Title = "Spider-Man: Far from Home", Year = "2019" }, new { Id = "13e6d16d-e8a9-4112-a3d0-fda72a846b17", Actors = "Karra Elejalde, Eduard Fernández, Santi Prego, Luis Bermejo", Director = "Alejandro Amenábar", Genre = "Drama, History, War", Playing = true, Plot = "July 18, 1936. Salamanca, Castilla and León (center to Spain). The Spanish army declares in the city the state of war, hoping to extend it to the rest of Spain and improve the unstable ...", Poster = "https://m.media-amazon.com/images/M/MV5BOGZjZDgxYTItMDQwYS00MWQ1LTk3ZGEtNjY1MmIwNDk5OWZjXkEyXkFqcGdeQXVyMTA0MjU0Ng@@._V1_SX300.jpg", Rated = "PG-13", Released = "27 Sep 2019", Runtime = "107 min", Title = "While at War", Year = "2019" }, new { Id = "1df1dac8-0b73-486e-b1a0-ded9d9d0849c", Actors = "Michael Roark, Trace Adkins, Ali Afshar, Allison Paige", Director = "Alex Ranarivelo", Genre = "Sport", Playing = true, Plot = "After surviving an IED explosion in combat overseas, a young soldier with the Army Motorcycle Unit is medically discharged with a broken back and leg. Against all odds he trains to make an ...", Poster = "https://m.media-amazon.com/images/M/MV5BNzM0Zjc2OWMtY2NjNS00ZmE4LWEzZTItMWE3NjQ4NmM2YzE2XkEyXkFqcGdeQXVyOTk0Mjc1MDA@._V1_SX300.jpg", Rated = "PG-13", Released = "30 Aug 2019", Runtime = "94 min", Title = "Bennett's War", Year = "2019" }, new { Id = "69e84aef-f2e8-436c-b235-7563ae1cffa2", Actors = "Thomas W. Markle, Meghan Markle, Doria Ragland, Prince Harry", Director = "David Modell", Genre = "Documentary", Playing = false, Plot = "Thomas Markle details his journey from raising Meghan Markle on his own to his heart attack days before her wedding to Prince Harry, Duke of Sussex. Due to his sudden fame as the father of ...", Poster = "https://m.media-amazon.com/images/M/MV5BMzdiMTZmNzYtMGQ0Ni00MGUxLTg4ZWYtZDc4MjBiOTdmZTllXkEyXkFqcGdeQXVyMDkwNTkwNg@@._V1_SX300.jpg", Rated = "PG-13", Released = "25 Aug 2020", Runtime = "90 min", Title = "Thomas Markle: My Story", Year = "2020" }, new { Id = "ee79a6c6-c7e6-4ff8-9668-03ebe5134767", Actors = "Italia Ricci, Chad Michael Murray, Jack Turner, Aliyah O'Brien", Director = "Pat Williams", Genre = "Drama, Romance", Playing = false, Plot = "Ally, a final contestant on a dating show, must face her high school sweetheart when she is chosen for the Hometown Date.", Poster = "https://m.media-amazon.com/images/M/MV5BNGVhMTQ5YWYtMjYyOS00OGZiLTg1OGYtN2YyZDIwOGQwYmJiXkEyXkFqcGdeQXVyNjU0NTI0Nw@@._V1_SX300.jpg", Rated = "TV-G", Released = "30 Aug 2020", Runtime = "83 min", Title = "Love in Winterland", Year = "2020" }, new { Id = "5480d3f9-0e58-45bd-927c-95fd06cd2753", Actors = "Josh Gilmer, Amber Pauline Magdesyan, Tevy Poe, Kate Durocher", Director = "Alex Magaña", Genre = "Comedy, Drama, Romance", Playing = false, Plot = "Five interwoven love stories explore the ups and downs of finding love.", Poster = "https://m.media-amazon.com/images/M/MV5BMTMxYTg4M2EtMDFjMy00MDI1LThjZGUtNjQwOGJlY2FhNjkwXkEyXkFqcGdeQXVyNDQ2MjQ2Mjk@._V1_SX300.jpg", Rated = "PG-13", Released = "19 Aug 2020", Runtime = "88 min", Title = "What Love Looks Like", Year = "2020" }, new { Id = "251759f9-a3c5-43d3-9734-39a288f2a461", Actors = "Elizabeth Debicki, Robert Pattinson, Aaron Taylor-Johnson, Kenneth Branagh", Director = "Christopher Nolan", Genre = "Action, Drama, Thriller", Playing = false, Plot = "An action epic revolving around international espionage, time travel, and evolution.", Poster = "https://m.media-amazon.com/images/M/MV5BNmMwYzFlNTEtYTc0NC00NGY4LTgzNzItZGFiYTViY2QzNzU1XkEyXkFqcGdeQXVyMTkxNjUyNQ@@._V1_SX300.jpg", Rated = "R", Released = "17 Jul 2020", Runtime = "125 min", Title = "Tenet", Year = "2020" }, new { Id = "0fe4656a-4598-4f6f-9e7c-3f9347153a10", Actors = "Manny Montana, Nora-Jane Noone, Chris Marquette, Mary Birdsong", Director = "Dustin Cook", Genre = "Comedy, Drama, Romance, Thriller", Playing = false, Plot = "After his wife's death, Claude struggles to appear normal while living with a Secret.", Poster = "https://m.media-amazon.com/images/M/MV5BMTBmYWU0ZGYtNTRjNi00MmJkLTg0OGItNjI5M2Y2ZjY4MzhkXkEyXkFqcGdeQXVyMjM2NzM3Mjc@._V1_SX300.jpg", Rated = "PG-13", Released = "15 Sep 2020", Runtime = "103 min", Title = "I Hate the Man in My Basement", Year = "2020" }, new { Id = "3a1a1424-20d5-469b-b39f-9012da50a71a", Actors = "Anne Hathaway, Ben Affleck, Rosie Perez, Willem Dafoe", Director = "Dee Rees", Genre = "Crime, Drama, Mystery, Thriller", Playing = false, Plot = "A veteran D.C. journalist loses the thread of her own narrative when a guilt-propelled errand for her father thrusts her from byline to unwitting subject in the very story she's trying to break. Adapted from Joan Didion's namesake novel.", Poster = "https://m.media-amazon.com/images/M/MV5BMWI3ODZlNjgtNWM4OC00MDFhLTg2MmYtYjk3M2I0OWJmZmE2XkEyXkFqcGdeQXVyODkzNTgxMDg@._V1_SX300.jpg", Rated = "R", Released = "8 Sep 2020", Runtime = "115 min", Title = "The Last Thing He Wanted", Year = "2020" }); }); #pragma warning restore 612, 618 } } }
56.284047
275
0.453578
[ "MIT" ]
AMisljenovic/Cinema.WebApi
Cinema.WebApi/Migrations/Movie/20200424174214_movies.Designer.cs
14,472
C#
using System; using System.Collections.Generic; using System.Runtime.Serialization; using System.Xml; namespace SerializationTestTypes { [DataContract] public class PrimitiveContainer { public PrimitiveContainer() { a = false; b = Byte.MaxValue; c = Byte.MinValue; //char //datetime e = Decimal.MaxValue; f = Decimal.MinusOne; g = Decimal.MinValue; h = Decimal.One; i = Decimal.Zero; j = default(Decimal); k = default(Double); l = Double.Epsilon; m = Double.MaxValue; n = Double.MinValue; o = Double.NaN; p = Double.NegativeInfinity; q = Double.PositiveInfinity; r = default(Single); s = Single.Epsilon; t = Single.MinValue; u = Single.MaxValue; v = Single.NaN; w = Single.NegativeInfinity; x = Single.PositiveInfinity; y = default(Int32); z = Int32.MaxValue; z1 = Int32.MinValue; z2 = default(Int64); z3 = Int64.MaxValue; z4 = Int64.MinValue; z5 = new Object(); z6 = default(SByte); z7 = SByte.MaxValue; z8 = SByte.MinValue; z9 = default(Int16); z91 = Int16.MaxValue; z92 = Int16.MinValue; z93 = "abc"; z94 = default(UInt16); z95 = UInt16.MaxValue; z96 = UInt16.MinValue; z97 = default(UInt32); z98 = UInt32.MaxValue; z99 = UInt32.MinValue; z990 = default(UInt64); z991 = UInt64.MaxValue; z992 = UInt64.MinValue; z993 = new Byte[] { 1, 2, 3, 4 }; } [DataMember] public object a; [DataMember] public object b; [DataMember] public object c; [DataMember] public object d = Char.MaxValue; [DataMember] public object f5 = DateTime.MaxValue; [DataMember] public object guidData = Guid.Parse("4bc848b1-a541-40bf-8aa9-dd6ccb6d0e56"); [DataMember] public object strData; [DataMember] public object e; [DataMember] public object f; [DataMember] public object g; [DataMember] public object h; [DataMember] public object i; [DataMember] public object j; [DataMember] public object k; [DataMember] public object l; [DataMember] public object m; [DataMember] public object n; [DataMember] public object o; [DataMember] public object p; [DataMember] public object q; [DataMember] public object r; [DataMember] public object s; [DataMember] public object t; [DataMember] public object u; [DataMember] public object v; [DataMember] public object w; [DataMember] public object x; [DataMember] public object y; [DataMember] public object z; [DataMember] public object z1; [DataMember] public object z2; [DataMember] public object z3; [DataMember] public object z4; [DataMember] public object z5; [DataMember] public object z6; [DataMember] public object z7; [DataMember] public object z8; [DataMember] public object z9; [DataMember] public object z91; [DataMember] public object z92; [DataMember] public object z93; [DataMember] public object z94; [DataMember] public object z95; [DataMember] public object z96; [DataMember] public object z97; [DataMember] public object z98; [DataMember] public object z99; [DataMember] public object z990; [DataMember] public object z991; [DataMember] public object z992; [DataMember] public Byte[] z993; [DataMember] public object xmlQualifiedName = new XmlQualifiedName("WCF", "http://www.microsoft.com"); [DataMember] public ValueType timeSpan = TimeSpan.MaxValue; [DataMember] public object obj = new object(); [DataMember] public Uri uri = new Uri("http://www.microsoft.com"); [DataMember] public Array array1 = new object[] { new object(), new object(), new object() }; [DataMember] public object nDTO = DateTimeOffset.MaxValue; [DataMember] public List<DateTimeOffset> lDTO = new List<DateTimeOffset>(); } [DataContract] [KnownType(typeof(EmptyNSAddress))] public class EmptyNsContainer { [DataMember] public object address; [DataMember] public string Name; public EmptyNsContainer(EmptyNSAddress obj) { address = obj; Name = "P1"; } } [DataContract(Namespace = "")] public class UknownEmptyNSAddress : EmptyNSAddress { public UknownEmptyNSAddress() { } } [DataContract(Namespace = "")] public class EmptyNSAddress { [DataMember] public string street; public EmptyNSAddress() { street = "downing street"; } } [DataContract(IsReference = true)] [KnownType(typeof(PreferredCustomer))] public class Customer { [DataMember] public string Name { get; set; } } [DataContract(IsReference = true)] public class PreferredCustomer : Customer { [DataMember] public string VipInfo { get; set; } } [DataContract(IsReference = true)] public class PreferredCustomerProxy : PreferredCustomer { } [DataContract] public class UnknownEmployee { [DataMember] public int id = 10000; } [DataContract] public class UserTypeContainer { [DataMember] public object unknownData = new UnknownEmployee(); } }
20.861736
97
0.523274
[ "MIT" ]
Acidburn0zzz/corefx
src/System.Runtime.Serialization.Xml/tests/SerializationTestTypes/DCRSampleType.cs
6,490
C#
using System; using System.Linq; using Rhino.Geometry; using RhinoInside.Revit.Convert.Geometry; using RhinoInside.Revit.External.DB.Extensions; using DB = Autodesk.Revit.DB; namespace RhinoInside.Revit.GH.Types { public class Roof : HostObject { public override string TypeDescription => "Represents a Revit roof element"; protected override Type ScriptVariableType => typeof(DB.RoofBase); public static explicit operator DB.RoofBase(Roof value) => value?.IsValid == true ? value.Document.GetElement(value) as DB.RoofBase : default; public Roof() { } public Roof(DB.RoofBase roof) : base(roof) { } public override Level Level { get { switch ((DB.RoofBase) this) { case DB.ExtrusionRoof extrusionRoof: return Level.FromElement(extrusionRoof.Document.GetElement(extrusionRoof.get_Parameter(DB.BuiltInParameter.ROOF_CONSTRAINT_LEVEL_PARAM).AsElementId())) as Level; } return base.Level; } } public override Plane Location { get { var roof = (DB.RoofBase) this; if (!(roof.Location is DB.LocationPoint) && !(roof.Location is DB.LocationCurve)) { if (roof.GetFirstDependent<DB.Sketch>() is DB.Sketch sketch) { var center = Point3d.Origin; var count = 0; foreach (var curveArray in sketch.Profile.Cast<DB.CurveArray>()) { foreach (var curve in curveArray.Cast<DB.Curve>()) { count++; center += curve.Evaluate(0.0, normalized: true).ToPoint3d(); count++; center += curve.Evaluate(1.0, normalized: true).ToPoint3d(); } } center /= count; var levelOffset = 0.0; switch (roof) { case DB.FootPrintRoof footPrintRoof: levelOffset = footPrintRoof.get_Parameter(DB.BuiltInParameter.ROOF_LEVEL_OFFSET_PARAM).AsDouble() * Revit.ModelUnits; break; case DB.ExtrusionRoof extrusionRoof: levelOffset = extrusionRoof.get_Parameter(DB.BuiltInParameter.ROOF_CONSTRAINT_OFFSET_PARAM).AsDouble() * Revit.ModelUnits; break; } var plane = sketch.SketchPlane.GetPlane().ToPlane(); var origin = new Point3d(center.X, center.Y, Level.Elevation + levelOffset); var xAxis = plane.XAxis; var yAxis = plane.YAxis; if (roof is DB.ExtrusionRoof) yAxis = plane.ZAxis; return new Plane(origin, xAxis, yAxis); } } return base.Location; } } } }
31.471264
173
0.591308
[ "MIT" ]
IMVVVVVIP/rhino.inside-revit
src/RhinoInside.Revit.GH/Types/Roof.cs
2,738
C#
// This file is used by Code Analysis to maintain SuppressMessage // attributes that are applied to this project. // Project-level suppressions either have no target or are given // a specific target and scoped to a namespace, type, member, etc. [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Security", "CA5374:Do Not Use XslTransform", Justification = "<Pending>", Scope = "member", Target = "~M:Xslt.ApplyOld(System.String,System.String)~System.String")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Security", "CA5374:Do Not Use XslTransform", Justification = "<Pending>", Scope = "member", Target = "~M:GxXsltImpl.ApplyToString(System.String,System.String)~System.String")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Security", "CA3075:Insecure DTD processing in XML", Justification = "<Pending>", Scope = "member", Target = "~M:GxXsltImpl.ApplyOld(System.String,System.String)~System.String")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Security", "CA5372:Use XmlReader For XPathDocument", Justification = "<Pending>", Scope = "member", Target = "~M:GxXsltImpl.ApplyOld(System.String,System.String)~System.String")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Security", "CA3075:Insecure DTD processing in XML", Justification = "<Pending>", Scope = "member", Target = "~M:GxXsltImpl.ApplyToString(System.String,System.String)~System.String")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Security", "CA5372:Use XmlReader For XPathDocument", Justification = "<Pending>", Scope = "member", Target = "~M:GxXsltImpl.ApplyToString(System.String,System.String)~System.String")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Security", "CA3076:Insecure XSLT script processing.", Justification = "<Pending>", Scope = "member", Target = "~M:GxXsltImpl.Apply(System.String,System.String)~System.String")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Security", "CA5374:Do Not Use XslTransform", Justification = "<Pending>", Scope = "member", Target = "~M:GxXsltImpl.ApplyOld(System.String,System.String)~System.String")]
142.8
243
0.773576
[ "Apache-2.0" ]
genexuslabs/DotNetClasses
dotnet/src/dotnetframework/GxXsl/GlobalSuppressions.cs
2,144
C#
using System; namespace Open_Lab_03._05 { public class Comparator { public bool MatchCaseInsensitive(string str1, string str2) => str1.ToLower() == str2.ToLower(); } }
18.090909
103
0.638191
[ "MIT" ]
MilosM33/Open-Lab-03.05
Open-Lab-03.05/Comparator.cs
201
C#
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using PuntoBanco; using Moq; using System.Runtime.CompilerServices; namespace UnitTestPuntoBanco { [TestClass] public class UnitTestGame { [TestMethod] public void TestBots() { SomeBet bet; bet.man = 0; bet.money = 0; bet.target = 1; int Rounds = 401; int callsBet = 0; int callsInput = 0; int callsReady = 0; var mock = new Mock<IInteraction>(); mock.Setup(x => x.Ready()).Returns(() => { callsReady++; if (callsReady != Rounds + 1) { Console.WriteLine("test 1"); return true; } Console.WriteLine("test 0"); return false; }); mock.Setup(x => x.GetInt()).Returns(() => { callsInput++; if (callsInput == 1) { Console.WriteLine("test 25"); return 25; } Console.WriteLine("test 1"); return 1; }); //mock.Setup(x => x.doBet(ref It.Ref<SomeBet>.IsAny, It.IsAny<int>())).Callback((ref SomeBet bet, int money) => Console.WriteLine("s")); //Problem: ref bet - must change value in do.Bet(ref SomeBet, int) mock.Setup(x => x.DoBet(It.IsAny<SomeBet>(), It.IsAny<int>())).Returns(() => { callsBet++; Console.WriteLine($"test: money{bet.money}"); return bet; }); // UserInterface user = new UserInterface(mock.Object); user.GoGame(); } [TestMethod] public void TestGame() { SomeBet bet; bet.man = 0; bet.money = 1; bet.target = 1; int Rounds = 104; int callsBet = 0; int callsInput = 0; int callsReady = 0; var mock = new Mock<IInteraction>(); mock.Setup(x => x.Ready()).Returns(() => { callsReady++; if (callsReady != Rounds + 1) { Console.WriteLine("test 1"); return true; } Console.WriteLine("test 0"); return false; }); mock.Setup(x => x.GetInt()).Returns(() => { callsInput++; if (callsInput == 1) { Console.WriteLine("test 25"); return 25; } Console.WriteLine("test 1"); return 1; }); //mock.Setup(x => x.doBet(ref It.Ref<SomeBet>.IsAny, It.IsAny<int>())).Callback((ref SomeBet bet, int money) => Console.WriteLine("s")); //Problem: ref bet - must change value in do.Bet(ref SomeBet, int) mock.Setup(x => x.DoBet(It.IsAny<SomeBet>(), It.IsAny<int>())).Returns(() => { callsBet++; Console.WriteLine($"test: money: {bet.money}$, target: {bet.target}"); return bet; }); // UserInterface user = new UserInterface(mock.Object); user.GoGame(); Console.WriteLine($"\n end-----\ncalls of Input: {callsInput}\nMade bets: {callsBet}\nRounds: {callsReady - 1}"); } } }
23.855856
139
0.5929
[ "MIT" ]
makar-pelogeiko/spbu-mm-programming
term_2/c#/PuntoBanco/UnitTestPuntoBanco/UnitTestGame.cs
2,650
C#
// // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See LICENSE file in the project root for full license information. // #region Using using System; using System.Globalization; using System.IO; using System.Runtime.CompilerServices; using System.Web; using System.Web.Compilation; using System.Web.WebPages; using DotNetNuke.Services.Exceptions; using DotNetNuke.Services.Localization; using DotNetNuke.UI.Modules; using DotNetNuke.Web.Razor.Helpers; #endregion namespace DotNetNuke.Web.Razor { [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] public class RazorEngine { [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] public RazorEngine(string razorScriptFile, ModuleInstanceContext moduleContext, string localResourceFile) { RazorScriptFile = razorScriptFile; ModuleContext = moduleContext; LocalResourceFile = localResourceFile ?? Path.Combine(Path.GetDirectoryName(razorScriptFile), Localization.LocalResourceDirectory, Path.GetFileName(razorScriptFile) + ".resx"); try { InitWebpage(); } catch (HttpParseException) { throw; } catch (HttpCompileException) { throw; } catch (Exception exc) { Exceptions.LogException(exc); } } [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] protected string RazorScriptFile { get; set; } [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] protected ModuleInstanceContext ModuleContext { get; set; } [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] protected string LocalResourceFile { get; set; } [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] public DotNetNukeWebPage Webpage { get; set; } [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] protected HttpContextBase HttpContext { get { return new HttpContextWrapper(System.Web.HttpContext.Current); } } [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] public Type RequestedModelType() { if (Webpage != null) { var webpageType = Webpage.GetType(); if (webpageType.BaseType.IsGenericType) { return webpageType.BaseType.GetGenericArguments()[0]; } } return null; } [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] public void Render<T>(TextWriter writer, T model) { try { Webpage.ExecutePageHierarchy(new WebPageContext(HttpContext, Webpage, model), writer, Webpage); } catch (Exception exc) { Exceptions.LogException(exc); } } [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] public void Render(TextWriter writer) { try { Webpage.ExecutePageHierarchy(new WebPageContext(HttpContext, Webpage, null), writer, Webpage); } catch (Exception exc) { Exceptions.LogException(exc); } } [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] public void Render(TextWriter writer, WebPageContext context) { try { Webpage.ExecutePageHierarchy(context, writer, Webpage); } catch (Exception exc) { Exceptions.LogException(exc); } } private object CreateWebPageInstance() { var compiledType = BuildManager.GetCompiledType(RazorScriptFile); object objectValue = null; if (((compiledType != null))) { objectValue = RuntimeHelpers.GetObjectValue(Activator.CreateInstance(compiledType)); } return objectValue; } private void InitHelpers(DotNetNukeWebPage webPage) { webPage.Dnn = new DnnHelper(ModuleContext); webPage.Html = new HtmlHelper(ModuleContext, LocalResourceFile); webPage.Url = new UrlHelper(ModuleContext); } private void InitWebpage() { if (!string.IsNullOrEmpty(RazorScriptFile)) { var objectValue = RuntimeHelpers.GetObjectValue(CreateWebPageInstance()); if ((objectValue == null)) { throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, "The webpage found at '{0}' was not created.", new object[] {RazorScriptFile})); } Webpage = objectValue as DotNetNukeWebPage; if ((Webpage == null)) { throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, "The webpage at '{0}' must derive from DotNetNukeWebPage.", new object[] {RazorScriptFile})); } Webpage.Context = HttpContext; Webpage.VirtualPath = VirtualPathUtility.GetDirectory(RazorScriptFile); InitHelpers(Webpage); } } } }
36.925466
192
0.567199
[ "MIT" ]
CMarius94/Dnn.Platform
DNN Platform/DotNetNuke.Web.Razor/RazorEngine.cs
5,947
C#
using System.Web; using System.Web.Optimization; namespace UCRS.WebClient { public class BundleConfig { // For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862 public static void RegisterBundles(BundleCollection bundles) { bundles.Add(new ScriptBundle("~/bundles/jquery").Include( "~/Scripts/jquery-{version}.js")); bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include( "~/Scripts/jquery.unobtrusive-ajax.js", "~/Scripts/jquery.validate*")); bundles.Add(new ScriptBundle("~/bundles/modernizr").Include( "~/Scripts/modernizr-*")); bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include( "~/Scripts/bootstrap.js", "~/Scripts/respond.js")); bundles.Add(new ScriptBundle("~/bundles/modalCourse").Include( "~/Scripts/modalCourse.js")); bundles.Add(new ScriptBundle("~/bundles/modalStudent").Include( "~/Scripts/modalStudent.js")); bundles.Add(new StyleBundle("~/Content/css").Include( "~/Content/bootstrap.css", "~/Content/site.css")); } } }
36.702703
96
0.541973
[ "MIT" ]
primas23/UniversityCoursesRegistrationSystem
UCRS.WebClient/App_Start/BundleConfig.cs
1,360
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.SecurityInsights.V20190101Preview.Outputs { [OutputType] public sealed class ActivityTimelineItemResponseResult { /// <summary> /// The grouping bucket end time. /// </summary> public readonly string BucketEndTimeUTC; /// <summary> /// The grouping bucket start time. /// </summary> public readonly string BucketStartTimeUTC; /// <summary> /// The activity timeline content. /// </summary> public readonly string Content; /// <summary> /// The time of the first activity in the grouping bucket. /// </summary> public readonly string FirstActivityTimeUTC; /// <summary> /// The entity query kind type. /// Expected value is 'Activity'. /// </summary> public readonly string Kind; /// <summary> /// The time of the last activity in the grouping bucket. /// </summary> public readonly string LastActivityTimeUTC; /// <summary> /// The activity query id. /// </summary> public readonly string QueryId; /// <summary> /// The activity timeline title. /// </summary> public readonly string Title; [OutputConstructor] private ActivityTimelineItemResponseResult( string bucketEndTimeUTC, string bucketStartTimeUTC, string content, string firstActivityTimeUTC, string kind, string lastActivityTimeUTC, string queryId, string title) { BucketEndTimeUTC = bucketEndTimeUTC; BucketStartTimeUTC = bucketStartTimeUTC; Content = content; FirstActivityTimeUTC = firstActivityTimeUTC; Kind = kind; LastActivityTimeUTC = lastActivityTimeUTC; QueryId = queryId; Title = title; } } }
29.151899
81
0.591837
[ "Apache-2.0" ]
pulumi-bot/pulumi-azure-native
sdk/dotnet/SecurityInsights/V20190101Preview/Outputs/ActivityTimelineItemResponseResult.cs
2,303
C#
using DevComponents.DotNetBar.Controls; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace core_fw_spring_dbar.widget.chekcbox { public class CheckBoxXUtils { #region genCheckBox public static CheckBoxX genCheckBox(bool bChecked, Object oTag, EventHandler oCheckedChangedCallback) { var oCheckBox = new CheckBoxX(); oCheckBox.Checked = bChecked; oCheckBox.Tag = oTag; oCheckBox.CheckedChanged += oCheckedChangedCallback; return oCheckBox; } #endregion } }
24.407407
71
0.663126
[ "Apache-2.0" ]
JHerculesqz/Hulk
cs/core-fw-spring-dbar/widget/chekcbox/CheckBoxXUtils.cs
661
C#
using System; using System.Collections.Generic; using System.Globalization; using ClearHl7.Extensions; using ClearHl7.Helpers; using ClearHl7.Serialization; using ClearHl7.V290.Types; namespace ClearHl7.V290.Segments { /// <summary> /// HL7 Version 2 Segment IAM - Patient Adverse Reaction Information. /// </summary> public class IamSegment : ISegment { /// <summary> /// Gets the ID for the Segment. This property is read-only. /// </summary> public string Id { get; } = "IAM"; /// <summary> /// Gets or sets the rank, or ordinal, which describes the place that this Segment resides in an ordered list of Segments. /// </summary> public int Ordinal { get; set; } /// <summary> /// IAM.1 - Set ID - IAM. /// </summary> public uint? SetIdIam { get; set; } /// <summary> /// IAM.2 - Allergen Type Code. /// <para>Suggested: 0127 Allergen Type -&gt; ClearHl7.Codes.V290.CodeAllergenType</para> /// </summary> public CodedWithExceptions AllergenTypeCode { get; set; } /// <summary> /// IAM.3 - Allergen Code/Mnemonic/Description. /// </summary> public CodedWithExceptions AllergenCodeMnemonicDescription { get; set; } /// <summary> /// IAM.4 - Allergy Severity Code. /// <para>Suggested: 0128 Allergy Severity -&gt; ClearHl7.Codes.V290.CodeAllergySeverity</para> /// </summary> public CodedWithExceptions AllergySeverityCode { get; set; } /// <summary> /// IAM.5 - Allergy Reaction Code. /// </summary> public IEnumerable<string> AllergyReactionCode { get; set; } /// <summary> /// IAM.6 - Allergy Action Code. /// <para>Suggested: 0206 Segment Action Code -&gt; ClearHl7.Codes.V290.CodeSegmentActionCode</para> /// </summary> public CodedWithNoExceptions AllergyActionCode { get; set; } /// <summary> /// IAM.7 - Allergy Unique Identifier. /// </summary> public EntityIdentifier AllergyUniqueIdentifier { get; set; } /// <summary> /// IAM.8 - Action Reason. /// </summary> public string ActionReason { get; set; } /// <summary> /// IAM.9 - Sensitivity to Causative Agent Code. /// <para>Suggested: 0436 Sensitivity To Causative Agent Code -&gt; ClearHl7.Codes.V290.CodeSensitivityToCausativeAgentCode</para> /// </summary> public CodedWithExceptions SensitivityToCausativeAgentCode { get; set; } /// <summary> /// IAM.10 - Allergen Group Code/Mnemonic/Description. /// </summary> public CodedWithExceptions AllergenGroupCodeMnemonicDescription { get; set; } /// <summary> /// IAM.11 - Onset Date. /// </summary> public DateTime? OnsetDate { get; set; } /// <summary> /// IAM.12 - Onset Date Text. /// </summary> public string OnsetDateText { get; set; } /// <summary> /// IAM.13 - Reported Date/Time. /// </summary> public DateTime? ReportedDateTime { get; set; } /// <summary> /// IAM.14 - Reported By. /// </summary> public ExtendedPersonName ReportedBy { get; set; } /// <summary> /// IAM.15 - Relationship to Patient Code. /// <para>Suggested: 0063 Relationship -&gt; ClearHl7.Codes.V290.CodeRelationship</para> /// </summary> public CodedWithExceptions RelationshipToPatientCode { get; set; } /// <summary> /// IAM.16 - Alert Device Code. /// <para>Suggested: 0437 Alert Device Code -&gt; ClearHl7.Codes.V290.CodeAlertDeviceCode</para> /// </summary> public CodedWithExceptions AlertDeviceCode { get; set; } /// <summary> /// IAM.17 - Allergy Clinical Status Code. /// <para>Suggested: 0438 Allergy Clinical Status -&gt; ClearHl7.Codes.V290.CodeAllergyClinicalStatus</para> /// </summary> public CodedWithExceptions AllergyClinicalStatusCode { get; set; } /// <summary> /// IAM.18 - Statused by Person. /// </summary> public ExtendedCompositeIdNumberAndNameForPersons StatusedByPerson { get; set; } /// <summary> /// IAM.19 - Statused by Organization. /// </summary> public ExtendedCompositeNameAndIdNumberForOrganizations StatusedByOrganization { get; set; } /// <summary> /// IAM.20 - Statused at Date/Time. /// </summary> public DateTime? StatusedAtDateTime { get; set; } /// <summary> /// IAM.21 - Inactivated by Person. /// </summary> public ExtendedCompositeIdNumberAndNameForPersons InactivatedByPerson { get; set; } /// <summary> /// IAM.22 - Inactivated Date/Time. /// </summary> public DateTime? InactivatedDateTime { get; set; } /// <summary> /// IAM.23 - Initially Recorded by Person. /// </summary> public ExtendedCompositeIdNumberAndNameForPersons InitiallyRecordedByPerson { get; set; } /// <summary> /// IAM.24 - Initially Recorded Date/Time. /// </summary> public DateTime? InitiallyRecordedDateTime { get; set; } /// <summary> /// IAM.25 - Modified by Person. /// </summary> public ExtendedCompositeIdNumberAndNameForPersons ModifiedByPerson { get; set; } /// <summary> /// IAM.26 - Modified Date/Time. /// </summary> public DateTime? ModifiedDateTime { get; set; } /// <summary> /// IAM.27 - Clinician Identified Code. /// </summary> public CodedWithExceptions ClinicianIdentifiedCode { get; set; } /// <summary> /// IAM.28 - Initially Recorded by Organization. /// </summary> public ExtendedCompositeNameAndIdNumberForOrganizations InitiallyRecordedByOrganization { get; set; } /// <summary> /// IAM.29 - Modified by Organization. /// </summary> public ExtendedCompositeNameAndIdNumberForOrganizations ModifiedByOrganization { get; set; } /// <summary> /// IAM.30 - Inactivated by Organization. /// </summary> public ExtendedCompositeNameAndIdNumberForOrganizations InactivatedByOrganization { get; set; } /// <summary> /// Initializes properties of this instance with values parsed from the given delimited string. Separators defined in the Configuration class are used to split the string. /// </summary> /// <param name="delimitedString">A string representation that will be deserialized into the object instance.</param> /// <exception cref="ArgumentException">delimitedString does not begin with the proper segment Id.</exception> public void FromDelimitedString(string delimitedString) { FromDelimitedString(delimitedString, null); } /// <summary> /// Initializes properties of this instance with values parsed from the given delimited string. The provided separators are used to split the string. /// </summary> /// <param name="delimitedString">A string representation that will be deserialized into the object instance.</param> /// <param name="separators">The separators to use for splitting the string.</param> /// <exception cref="ArgumentException">delimitedString does not begin with the proper segment Id.</exception> public void FromDelimitedString(string delimitedString, Separators separators) { Separators seps = separators ?? new Separators().UsingConfigurationValues(); string[] segments = delimitedString == null ? Array.Empty<string>() : delimitedString.Split(seps.FieldSeparator, StringSplitOptions.None); if (segments.Length > 0) { if (string.Compare(Id, segments[0], true, CultureInfo.CurrentCulture) != 0) { throw new ArgumentException($"{ nameof(delimitedString) } does not begin with the proper segment Id: '{ Id }{ seps.FieldSeparator }'.", nameof(delimitedString)); } } SetIdIam = segments.Length > 1 && segments[1].Length > 0 ? segments[1].ToNullableUInt() : null; AllergenTypeCode = segments.Length > 2 && segments[2].Length > 0 ? TypeSerializer.Deserialize<CodedWithExceptions>(segments[2], false, seps) : null; AllergenCodeMnemonicDescription = segments.Length > 3 && segments[3].Length > 0 ? TypeSerializer.Deserialize<CodedWithExceptions>(segments[3], false, seps) : null; AllergySeverityCode = segments.Length > 4 && segments[4].Length > 0 ? TypeSerializer.Deserialize<CodedWithExceptions>(segments[4], false, seps) : null; AllergyReactionCode = segments.Length > 5 && segments[5].Length > 0 ? segments[5].Split(seps.FieldRepeatSeparator, StringSplitOptions.None) : null; AllergyActionCode = segments.Length > 6 && segments[6].Length > 0 ? TypeSerializer.Deserialize<CodedWithNoExceptions>(segments[6], false, seps) : null; AllergyUniqueIdentifier = segments.Length > 7 && segments[7].Length > 0 ? TypeSerializer.Deserialize<EntityIdentifier>(segments[7], false, seps) : null; ActionReason = segments.Length > 8 && segments[8].Length > 0 ? segments[8] : null; SensitivityToCausativeAgentCode = segments.Length > 9 && segments[9].Length > 0 ? TypeSerializer.Deserialize<CodedWithExceptions>(segments[9], false, seps) : null; AllergenGroupCodeMnemonicDescription = segments.Length > 10 && segments[10].Length > 0 ? TypeSerializer.Deserialize<CodedWithExceptions>(segments[10], false, seps) : null; OnsetDate = segments.Length > 11 && segments[11].Length > 0 ? segments[11].ToNullableDateTime() : null; OnsetDateText = segments.Length > 12 && segments[12].Length > 0 ? segments[12] : null; ReportedDateTime = segments.Length > 13 && segments[13].Length > 0 ? segments[13].ToNullableDateTime() : null; ReportedBy = segments.Length > 14 && segments[14].Length > 0 ? TypeSerializer.Deserialize<ExtendedPersonName>(segments[14], false, seps) : null; RelationshipToPatientCode = segments.Length > 15 && segments[15].Length > 0 ? TypeSerializer.Deserialize<CodedWithExceptions>(segments[15], false, seps) : null; AlertDeviceCode = segments.Length > 16 && segments[16].Length > 0 ? TypeSerializer.Deserialize<CodedWithExceptions>(segments[16], false, seps) : null; AllergyClinicalStatusCode = segments.Length > 17 && segments[17].Length > 0 ? TypeSerializer.Deserialize<CodedWithExceptions>(segments[17], false, seps) : null; StatusedByPerson = segments.Length > 18 && segments[18].Length > 0 ? TypeSerializer.Deserialize<ExtendedCompositeIdNumberAndNameForPersons>(segments[18], false, seps) : null; StatusedByOrganization = segments.Length > 19 && segments[19].Length > 0 ? TypeSerializer.Deserialize<ExtendedCompositeNameAndIdNumberForOrganizations>(segments[19], false, seps) : null; StatusedAtDateTime = segments.Length > 20 && segments[20].Length > 0 ? segments[20].ToNullableDateTime() : null; InactivatedByPerson = segments.Length > 21 && segments[21].Length > 0 ? TypeSerializer.Deserialize<ExtendedCompositeIdNumberAndNameForPersons>(segments[21], false, seps) : null; InactivatedDateTime = segments.Length > 22 && segments[22].Length > 0 ? segments[22].ToNullableDateTime() : null; InitiallyRecordedByPerson = segments.Length > 23 && segments[23].Length > 0 ? TypeSerializer.Deserialize<ExtendedCompositeIdNumberAndNameForPersons>(segments[23], false, seps) : null; InitiallyRecordedDateTime = segments.Length > 24 && segments[24].Length > 0 ? segments[24].ToNullableDateTime() : null; ModifiedByPerson = segments.Length > 25 && segments[25].Length > 0 ? TypeSerializer.Deserialize<ExtendedCompositeIdNumberAndNameForPersons>(segments[25], false, seps) : null; ModifiedDateTime = segments.Length > 26 && segments[26].Length > 0 ? segments[26].ToNullableDateTime() : null; ClinicianIdentifiedCode = segments.Length > 27 && segments[27].Length > 0 ? TypeSerializer.Deserialize<CodedWithExceptions>(segments[27], false, seps) : null; InitiallyRecordedByOrganization = segments.Length > 28 && segments[28].Length > 0 ? TypeSerializer.Deserialize<ExtendedCompositeNameAndIdNumberForOrganizations>(segments[28], false, seps) : null; ModifiedByOrganization = segments.Length > 29 && segments[29].Length > 0 ? TypeSerializer.Deserialize<ExtendedCompositeNameAndIdNumberForOrganizations>(segments[29], false, seps) : null; InactivatedByOrganization = segments.Length > 30 && segments[30].Length > 0 ? TypeSerializer.Deserialize<ExtendedCompositeNameAndIdNumberForOrganizations>(segments[30], false, seps) : null; } /// <summary> /// Returns a delimited string representation of this instance. /// </summary> /// <returns>A string.</returns> public string ToDelimitedString() { CultureInfo culture = CultureInfo.CurrentCulture; return string.Format( culture, StringHelper.StringFormatSequence(0, 31, Configuration.FieldSeparator), Id, SetIdIam.HasValue ? SetIdIam.Value.ToString(culture) : null, AllergenTypeCode?.ToDelimitedString(), AllergenCodeMnemonicDescription?.ToDelimitedString(), AllergySeverityCode?.ToDelimitedString(), AllergyReactionCode != null ? string.Join(Configuration.FieldRepeatSeparator, AllergyReactionCode) : null, AllergyActionCode?.ToDelimitedString(), AllergyUniqueIdentifier?.ToDelimitedString(), ActionReason, SensitivityToCausativeAgentCode?.ToDelimitedString(), AllergenGroupCodeMnemonicDescription?.ToDelimitedString(), OnsetDate.HasValue ? OnsetDate.Value.ToString(Consts.DateFormatPrecisionDay, culture) : null, OnsetDateText, ReportedDateTime.HasValue ? ReportedDateTime.Value.ToString(Consts.DateTimeFormatPrecisionSecond, culture) : null, ReportedBy?.ToDelimitedString(), RelationshipToPatientCode?.ToDelimitedString(), AlertDeviceCode?.ToDelimitedString(), AllergyClinicalStatusCode?.ToDelimitedString(), StatusedByPerson?.ToDelimitedString(), StatusedByOrganization?.ToDelimitedString(), StatusedAtDateTime.HasValue ? StatusedAtDateTime.Value.ToString(Consts.DateTimeFormatPrecisionSecond, culture) : null, InactivatedByPerson?.ToDelimitedString(), InactivatedDateTime.HasValue ? InactivatedDateTime.Value.ToString(Consts.DateTimeFormatPrecisionSecond, culture) : null, InitiallyRecordedByPerson?.ToDelimitedString(), InitiallyRecordedDateTime.HasValue ? InitiallyRecordedDateTime.Value.ToString(Consts.DateTimeFormatPrecisionSecond, culture) : null, ModifiedByPerson?.ToDelimitedString(), ModifiedDateTime.HasValue ? ModifiedDateTime.Value.ToString(Consts.DateTimeFormatPrecisionSecond, culture) : null, ClinicianIdentifiedCode?.ToDelimitedString(), InitiallyRecordedByOrganization?.ToDelimitedString(), ModifiedByOrganization?.ToDelimitedString(), InactivatedByOrganization?.ToDelimitedString() ).TrimEnd(Configuration.FieldSeparator.ToCharArray()); } } }
56.869416
207
0.624811
[ "MIT" ]
davebronson/clear-hl7-net
src/ClearHl7/V290/Segments/IamSegment.cs
16,551
C#
using Albedo; using AutoFixture.Idioms; using Restaurant.Server.Models; using Xunit; namespace Restaurant.Server.Api.UnitTests.Models { public class OrderItemTest { [Theory, AutoDomainData] public void Test_order_item_auto_properties(WritablePropertyAssertion assertion) { assertion.Verify(new Properties<OrderItem>().Select(d => d.Quantity)); assertion.Verify(new Properties<OrderItem>().Select(d => d.FoodId)); assertion.Verify(new Properties<OrderItem>().Select(d => d.OderId)); } } }
28.105263
85
0.724719
[ "MIT" ]
masgeek/Restaurant-App
src/Server/Tests/Restaurant.Server.Api.UnitTests/Models/OrderItemTest.cs
536
C#
#region Copyright & License /* Copyright (c) 2022, Integrated Solutions, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Integrated Solutions, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ISI.Extensions.Documents { public interface IDocumentStyle { void Remove(); string Name { get; set; } StyleIdentifier StyleIdentifier { get; } string[] Aliases { get; } bool IsHeading { get; } StyleType Type { get; } string LinkedStyleName { get; } string BaseStyleName { get; set; } string NextParagraphStyleName { get; set; } bool BuiltIn { get; } IDocumentFont Font { get; } IDocumentParagraphFormat ParagraphFormat { get; } IDocumentStyleCollection Styles { get; } } }
53.243902
754
0.783784
[ "BSD-3-Clause" ]
ISI-Extensions/ISI.Extensions
src/ISI.Extensions/Documents/IDocumentStyle.cs
2,183
C#
using System.Collections.Generic; using System.Runtime.Serialization; using Cofra.AbstractIL.Common.Types; using JetBrains.Annotations; namespace Cofra.AbstractIL.Common.ControlStructures { public interface IInstructionsContainer { InstructionBlock GetInstructionBlock(); bool IsEmpty(); } [DataContract] public class InstructionBlock : IInstructionsContainer { [NotNull] [DataMember] public readonly List<Continuation> Continuations; [NotNull] [DataMember] public readonly List<InstructionId> InitialInstructions; [NotNull] [DataMember] public readonly List<Instruction> Instructions; //public readonly Dictionary<InstructionId,Instruction> IdToInstruction; public InstructionBlock(List<InstructionId> initialInstructions, List<Instruction> instructions, List<Continuation> continuations) { Continuations = continuations ?? new List<Continuation>(); Instructions = instructions ?? new List<Instruction>(); InitialInstructions = initialInstructions ?? new List<InstructionId>(); } public InstructionBlock(Instruction instruction) { Continuations = new List<Continuation> {instruction.Continuation}; Instructions = new List<Instruction> {instruction}; InitialInstructions = new List<InstructionId> {instruction.Id}; } public InstructionBlock() { Continuations = new List<Continuation>(); Instructions = new List<Instruction>(); InitialInstructions = new List<InstructionId>(); } public bool AreContinuationsEmpty() { if (Continuations.Count == 0) return true; return !Continuations.Exists(cont => cont.NextInstructions.Count > 0); } public InstructionBlock GetInstructionBlock() { return this; } public bool IsEmpty() { return InitialInstructions.Count == 0; } } }
34.316667
104
0.65323
[ "Apache-2.0" ]
JetBrains-Research/CoFRA
src/AbstractIL.Common/ControlStructures/InstructionBlock.cs
2,059
C#
using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.UI; public class MainMenuManager : MonoBehaviour { private string _sceneToUnload; [SerializeField] private GameObject _mainMenu; private void Update() { if (Input.GetKeyDown(KeyCode.M)) { _mainMenu.SetActive(true); } if (Input.GetKeyDown(KeyCode.C)) { _mainMenu.SetActive(false); } } public void LoadScene(string sceneName) { if(_sceneToUnload != null) { SceneManager.UnloadSceneAsync(_sceneToUnload); _sceneToUnload = null; } if (!string.IsNullOrEmpty(sceneName)) { SceneManager.LoadSceneAsync(sceneName, LoadSceneMode.Additive); _sceneToUnload = sceneName; } } }
21.692308
75
0.598109
[ "MIT" ]
artem-karaman/UnityUI
Assets/!Scripts/MainMenuManager.cs
846
C#
using System; using System.Linq; using Confuser.Core; using dnlib.DotNet; using Microsoft.VisualBasic.CompilerServices; using Microsoft.VisualBasic; using System.Collections.Generic; using dnlib.DotNet.Emit; using System.Security.Cryptography; using Confuser.Protections.Compress; using dnlib.DotNet.Writer; using dnlib.DotNet.MD; namespace Confuser.Protections { // Token: 0x02000002 RID: 2 internal class NamePhaseProc : Protection { // Token: 0x06000006 RID: 6 RVA: 0x000020EF File Offset: 0x000002EF protected override void Initialize(ConfuserContext context) { } // Token: 0x06000007 RID: 7 RVA: 0x000020F1 File Offset: 0x000002F1 protected override void PopulatePipeline(ProtectionPipeline pipeline) { pipeline.InsertPreStage(PipelineStage.WriteModule, new NamePhaseProc.NamePhase(this)); } // Token: 0x17000002 RID: 2 public override string Description { // Token: 0x06000002 RID: 2 RVA: 0x000020D7 File Offset: 0x000002D7 get { return "Renames the module and assembly."; } } // Token: 0x17000004 RID: 4 public override string FullId { // Token: 0x06000004 RID: 4 RVA: 0x000020E5 File Offset: 0x000002E5 get { return "Ki.RenameModule"; } } // Token: 0x17000003 RID: 3 public override string Id { // Token: 0x06000003 RID: 3 RVA: 0x000020DE File Offset: 0x000002DE get { return "Rename Module"; } } // Token: 0x17000001 RID: 1 public override string Name { // Token: 0x06000001 RID: 1 RVA: 0x000020D0 File Offset: 0x000002D0 get { return "Rename Module"; } } // Token: 0x17000005 RID: 5 public override ProtectionPreset Preset { // Token: 0x06000005 RID: 5 RVA: 0x000020EC File Offset: 0x000002EC get { return ProtectionPreset.Minimum; } } // Token: 0x04000002 RID: 2 public const string _FullId = "Ki.RenameModule"; // Token: 0x04000001 RID: 1 public const string _Id = "Rename"; //public static string Random(int len) //{ // string str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRST123456789他是说汉语的Ⓟⓡⓞⓣⓔⓒⓣア尺Ծイ乇ζイ123456789αβγδεζηθικλμνξοπρστυφχψω卍卍卍卍卍卍卍"; // char[] chArray = new char[(len - 1) + 1]; // int num = len - 1; // for (int i = 0; i <= num; i++) // { // chArray[i] = str[(int)Math.Round((double)Conversion.Int((float)(VBMath.Rnd() * str.Length)))]; // } // return new string(chArray); //} // Token: 0x02000003 RID: 3 private class NamePhase : ProtectionPhase { // Token: 0x06000009 RID: 9 RVA: 0x00002108 File Offset: 0x00000308 public NamePhase(NamePhaseProc parent) : base(parent) { } Random cheekycunt = new Random(); // Token: 0x0600000C RID: 12 RVA: 0x0000211C File Offset: 0x0000031C protected override void Execute(ConfuserContext context, ProtectionParameters parameters) { foreach (ModuleDefMD module in parameters.Targets.OfType<ModuleDef>()) { // Invisible Name and Assembly name module.Name = "SkiDzEX | .NET Protector & Obfuscator"; module.Assembly.Name = "SkiDzEX | .NET Protector & Obfuscator"; } } // Token: 0x17000007 RID: 7 public override string Name { // Token: 0x0600000B RID: 11 RVA: 0x00002115 File Offset: 0x00000315 get { return "Renaming"; } } // Token: 0x17000006 RID: 6 public override ProtectionTargets Targets { // Token: 0x0600000A RID: 10 RVA: 0x00002111 File Offset: 0x00000311 get { return ProtectionTargets.Modules; } } } } }
32.26087
145
0.539308
[ "MPL-2.0" ]
binarysafe/SkiDzEX
Confuser.Protections/Name.cs
4,530
C#
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("SFA.DAS.Provider.Events.Api.IntegrationTestsV2")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("SFA.DAS.Provider.Events.Api.IntegrationTestsV2")] [assembly: AssemblyCopyright("Copyright © 2021")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("90b672aa-b958-4a1e-9fcb-148e05fc3779")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
39.472222
84
0.749472
[ "MIT" ]
SkillsFundingAgency/das-providerevents
src/api/SFA.DAS.Provider.Events.Api.IntegrationTestsV2/Properties/AssemblyInfo.cs
1,424
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable enable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Notification; using Microsoft.CodeAnalysis.Shared.TestHooks; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.SolutionCrawler { internal sealed partial class SolutionCrawlerRegistrationService { internal sealed partial class WorkCoordinator { private sealed partial class IncrementalAnalyzerProcessor { private sealed class LowPriorityProcessor : AbstractPriorityProcessor { private readonly AsyncProjectWorkItemQueue _workItemQueue; public LowPriorityProcessor( IAsynchronousOperationListener listener, IncrementalAnalyzerProcessor processor, Lazy<ImmutableArray<IIncrementalAnalyzer>> lazyAnalyzers, IGlobalOperationNotificationService globalOperationNotificationService, int backOffTimeSpanInMs, CancellationToken shutdownToken) : base(listener, processor, lazyAnalyzers, globalOperationNotificationService, backOffTimeSpanInMs, shutdownToken) { _workItemQueue = new AsyncProjectWorkItemQueue(processor._registration.ProgressReporter, processor._registration.Workspace); Start(); } public int WorkItemCount => _workItemQueue.WorkItemCount; protected override Task WaitAsync(CancellationToken cancellationToken) => _workItemQueue.WaitAsync(cancellationToken); protected override async Task ExecuteAsync() { try { // we wait for global operation, higher and normal priority processor to finish its working await WaitForHigherPriorityOperationsAsync().ConfigureAwait(false); // process any available project work, preferring the active project. if (_workItemQueue.TryTakeAnyWork( Processor.GetActiveProjectId(), Processor.DependencyGraph, Processor.DiagnosticAnalyzerService, out var workItem, out var projectCancellation)) { await ProcessProjectAsync(Analyzers, workItem, projectCancellation).ConfigureAwait(false); } } catch (Exception e) when (FatalError.ReportUnlessCanceled(e)) { throw ExceptionUtilities.Unreachable; } } protected override Task HigherQueueOperationTask { get { return Task.WhenAll(Processor._highPriorityProcessor.Running, Processor._normalPriorityProcessor.Running); } } protected override bool HigherQueueHasWorkItem { get { return Processor._highPriorityProcessor.HasAnyWork || Processor._normalPriorityProcessor.HasAnyWork; } } protected override void PauseOnGlobalOperation() { base.PauseOnGlobalOperation(); _workItemQueue.RequestCancellationOnRunningTasks(); } public void Enqueue(WorkItem item) { UpdateLastAccessTime(); // Project work item = item.ToProjectWorkItem(Processor._listener.BeginAsyncOperation("WorkItem")); var added = _workItemQueue.AddOrReplace(item); // lower priority queue gets lowest time slot possible. if there is any activity going on in higher queue, it drop whatever it has // and let higher work item run CancelRunningTaskIfHigherQueueHasWorkItem(); Logger.Log(FunctionId.WorkCoordinator_Project_Enqueue, s_enqueueLogger, Environment.TickCount, item.ProjectId, !added); SolutionCrawlerLogger.LogWorkItemEnqueue(Processor._logAggregator, item.ProjectId); } private void CancelRunningTaskIfHigherQueueHasWorkItem() { if (!HigherQueueHasWorkItem) { return; } _workItemQueue.RequestCancellationOnRunningTasks(); } private async Task ProcessProjectAsync(ImmutableArray<IIncrementalAnalyzer> analyzers, WorkItem workItem, CancellationToken cancellationToken) { if (CancellationToken.IsCancellationRequested) { return; } // we do have work item for this project var projectId = workItem.ProjectId; var processedEverything = false; var processingSolution = Processor.CurrentSolution; try { using (Logger.LogBlock(FunctionId.WorkCoordinator_ProcessProjectAsync, w => w.ToString(), workItem, cancellationToken)) { var project = processingSolution.GetProject(projectId); if (project != null) { var reasons = workItem.InvocationReasons; var semanticsChanged = reasons.Contains(PredefinedInvocationReasons.SemanticChanged) || reasons.Contains(PredefinedInvocationReasons.SolutionRemoved); using (Processor.EnableCaching(project.Id)) { await Processor.RunAnalyzersAsync(analyzers, project, workItem, (a, p, c) => a.AnalyzeProjectAsync(p, semanticsChanged, reasons, c), cancellationToken).ConfigureAwait(false); } } else { SolutionCrawlerLogger.LogProcessProjectNotExist(Processor._logAggregator); await RemoveProjectAsync(projectId, cancellationToken).ConfigureAwait(false); } if (!cancellationToken.IsCancellationRequested) { processedEverything = true; } } } catch (Exception e) when (FatalError.ReportUnlessCanceled(e)) { throw ExceptionUtilities.Unreachable; } finally { // we got cancelled in the middle of processing the project. // let's make sure newly enqueued work item has all the flag needed. // Avoid retry attempts after cancellation is requested, since work will not be processed // after that point. if (!processedEverything && !CancellationToken.IsCancellationRequested) { _workItemQueue.AddOrReplace(workItem.Retry(Listener.BeginAsyncOperation("ReenqueueWorkItem"))); } SolutionCrawlerLogger.LogProcessProject(Processor._logAggregator, projectId.Id, processedEverything); // remove one that is finished running _workItemQueue.MarkWorkItemDoneFor(projectId); } } private async Task RemoveProjectAsync(ProjectId projectId, CancellationToken cancellationToken) { foreach (var analyzer in Analyzers) { await analyzer.RemoveProjectAsync(projectId, cancellationToken).ConfigureAwait(false); } } public override void Shutdown() { base.Shutdown(); _workItemQueue.Dispose(); } internal TestAccessor GetTestAccessor() { return new TestAccessor(this); } internal readonly struct TestAccessor { private readonly LowPriorityProcessor _lowPriorityProcessor; internal TestAccessor(LowPriorityProcessor lowPriorityProcessor) { _lowPriorityProcessor = lowPriorityProcessor; } internal void WaitUntilCompletion(ImmutableArray<IIncrementalAnalyzer> analyzers, List<WorkItem> items) { var uniqueIds = new HashSet<ProjectId>(); foreach (var item in items) { if (uniqueIds.Add(item.ProjectId)) { _lowPriorityProcessor.ProcessProjectAsync(analyzers, item, CancellationToken.None).Wait(); } } } internal void WaitUntilCompletion() { // this shouldn't happen. would like to get some diagnostic while (_lowPriorityProcessor._workItemQueue.HasAnyWork) { FailFast.Fail("How?"); } } } } } } } }
46.983193
214
0.491683
[ "MIT" ]
06needhamt/roslyn
src/Features/Core/Portable/SolutionCrawler/WorkCoordinator.LowPriorityProcessor.cs
11,184
C#
using System.IO; using System.Linq; using System.Net.Http.Headers; using System.Threading.Tasks; using GraphQL; using GraphQL.Http; using GraphQL.Validation; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace CoreSharp.GraphQL.AspNetCore { public class GraphQLMiddleware<TSchema> : IMiddleware where TSchema : CqrsSchema { private const string JsonContentType = "application/json"; private const string GraphQLContentType = "application/graphql"; private const string FormUrlEncodedContentType = "application/x-www-form-urlencoded"; private readonly ILogger<GraphQLMiddleware<TSchema>> _logger; private readonly TSchema _schema; private readonly IComplexityConfigurationFactory _complexityConfigurationFactory; private readonly IUserContextBuilder _userContextBuilder; private readonly PathString _path = "/graphql"; public GraphQLMiddleware( ILogger<GraphQLMiddleware<TSchema>> logger, TSchema schema, IComplexityConfigurationFactory complexityConfigurationFactory, IUserContextBuilder userContextBuilder) { _logger = logger; _schema = schema; _complexityConfigurationFactory = complexityConfigurationFactory; _userContextBuilder = userContextBuilder; } public async Task InvokeAsync(HttpContext context, RequestDelegate next) { if (context.WebSockets.IsWebSocketRequest || !context.Request.Path.StartsWithSegments(_path)) { await next(context); return; } // Handle requests as per recommendation at http://graphql.org/learn/serving-over-http/ var httpRequest = context.Request; var gqlRequest = new GraphQLRequest(); var documentWriter = new DocumentWriter(Formatting.Indented, _schema.GetJsonSerializerSettings()); if (HttpMethods.IsGet(httpRequest.Method) || (HttpMethods.IsPost(httpRequest.Method) && httpRequest.Query.ContainsKey(GraphQLRequest.QueryKey))) { ExtractGraphQLRequestFromQueryString(httpRequest.Query, gqlRequest); } else if (HttpMethods.IsPost(httpRequest.Method)) { if (!MediaTypeHeaderValue.TryParse(httpRequest.ContentType, out var mediaTypeHeader)) { await WriteBadRequestResponseAsync(context, documentWriter, $"Invalid 'Content-Type' header: value '{httpRequest.ContentType}' could not be parsed."); return; } switch (mediaTypeHeader.MediaType) { case JsonContentType: gqlRequest = Deserialize<GraphQLRequest>(httpRequest.Body); break; case GraphQLContentType: gqlRequest.Query = await ReadAsStringAsync(httpRequest.Body); break; case FormUrlEncodedContentType: var formCollection = await httpRequest.ReadFormAsync(); ExtractGraphQLRequestFromPostBody(formCollection, gqlRequest); break; default: await WriteBadRequestResponseAsync(context, documentWriter, $"Invalid 'Content-Type' header: non-supported media type. Must be of '{JsonContentType}', '{GraphQLContentType}', or '{FormUrlEncodedContentType}'. See: http://graphql.org/learn/serving-over-http/."); return; } } var executer = new DocumentExecuter(); var result = await executer.ExecuteAsync(x => { x.Schema = _schema; x.OperationName = gqlRequest.OperationName; x.Query = gqlRequest.Query; x.Inputs = gqlRequest.GetInputs(); x.UserContext = _userContextBuilder.BuildContext(); x.ValidationRules = new[] { new AuthenticationValidationRule() }.Concat(DocumentValidator.CoreRules); x.CancellationToken = context.RequestAborted; x.ComplexityConfiguration = _complexityConfigurationFactory.GetComplexityConfiguration(); }); if (result.Errors != null) { _logger.LogError("GraphQL execution error(s): {Errors}", result.Errors); } await WriteResponseAsync(context, documentWriter, result); } private Task WriteBadRequestResponseAsync(HttpContext context, IDocumentWriter writer, string errorMessage) { var result = new ExecutionResult() { Errors = new ExecutionErrors() { new ExecutionError(errorMessage) } }; context.Response.ContentType = "application/json"; context.Response.StatusCode = 400; // Bad Request return writer.WriteAsync(context.Response.Body, result); } private Task WriteResponseAsync(HttpContext context, IDocumentWriter writer, ExecutionResult result) { context.Response.ContentType = "application/json"; context.Response.StatusCode = 200; // OK return writer.WriteAsync(context.Response.Body, result); } private static T Deserialize<T>(Stream s) { using (var reader = new StreamReader(s)) using (var jsonReader = new JsonTextReader(reader)) { return new JsonSerializer().Deserialize<T>(jsonReader); } } private static async Task<string> ReadAsStringAsync(Stream s) { using (var reader = new StreamReader(s)) { return await reader.ReadToEndAsync(); } } private static void ExtractGraphQLRequestFromQueryString(IQueryCollection qs, GraphQLRequest gqlRequest) { gqlRequest.Query = qs.TryGetValue(GraphQLRequest.QueryKey, out var queryValues) ? queryValues[0] : null; gqlRequest.Variables = qs.TryGetValue(GraphQLRequest.VariablesKey, out var variablesValues) ? JObject.Parse(variablesValues[0]) : null; gqlRequest.OperationName = qs.TryGetValue(GraphQLRequest.OperationNameKey, out var operationNameValues) ? operationNameValues[0] : null; } private static void ExtractGraphQLRequestFromPostBody(IFormCollection fc, GraphQLRequest gqlRequest) { gqlRequest.Query = fc.TryGetValue(GraphQLRequest.QueryKey, out var queryValues) ? queryValues[0] : null; gqlRequest.Variables = fc.TryGetValue(GraphQLRequest.VariablesKey, out var variablesValue) ? JObject.Parse(variablesValue[0]) : null; gqlRequest.OperationName = fc.TryGetValue(GraphQLRequest.OperationNameKey, out var operationNameValues) ? operationNameValues[0] : null; } } public static class GraphQLMiddlewareExtensions { public static IApplicationBuilder UseGraphQL<TSchema>(this IApplicationBuilder builder) where TSchema : CqrsSchema { return builder.UseMiddleware<GraphQLMiddleware<TSchema>>(); } } }
43.567251
285
0.632215
[ "MIT" ]
maca88/CoreSharp
CoreSharp.GraphQL.AspNetCore/GraphQLMiddleware.cs
7,450
C#
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Web; namespace lessonweb.Data { public class Utils { public static T CloneObject<T>(T srcObject) where T : class, new() { // Get the object type Type objectType = typeof(T); // Get the public properties of the object PropertyInfo[] propInfo = srcObject.GetType() .GetProperties( System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public ); // Create a new object T newObject = new T(); // Loop through all the properties and copy the information // from the source object to the new instance foreach (PropertyInfo p in propInfo) { Type t = p.PropertyType; if ((t.IsValueType || t == typeof(string)) && (p.CanRead) && (p.CanWrite)) { p.SetValue(newObject, p.GetValue(srcObject, null), null); } } // Return the cloned object. return newObject; } public static string GetLogoURL(string logoName) { return "/Assets/img/custom/96/" + logoName + "_96px.png"; } } }
29.826087
90
0.533528
[ "Apache-2.0" ]
flyvfr/lessontrack
lessonweb/lessonweb/Data/Utils.cs
1,374
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("DataStructures")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("DataStructures")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("3c26bb9f-f1bd-4a99-ba3e-f9962cfec5fe")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.864865
84
0.745896
[ "Apache-2.0" ]
qulia/CrackingTheCodingInterview
DataStructures/Properties/AssemblyInfo.cs
1,404
C#
using ALE.ETLBox.ConnectionManager; using ALE.ETLBox.ControlFlow; using ALE.ETLBox.Helper; using System; using System.Collections.Generic; using System.Text; using Xunit; namespace ALE.ETLBoxTests.Fixtures { [CollectionDefinition("DataFlow")] public class DatalFlowCollectionClass : ICollectionFixture<DataFlowDatabaseFixture> { } public class DataFlowDatabaseFixture { public DataFlowDatabaseFixture() { DatabaseHelper.RecreateSqlDatabase("DataFlow"); DatabaseHelper.RecreateMySqlDatabase("DataFlow"); DatabaseHelper.RecreatePostgresDatabase("DataFlow"); } } }
24.884615
91
0.724884
[ "MIT" ]
HaSaM-cz/etlbox
TestsETLBox/src/Fixtures/DataFlowDatabaseFixture.cs
649
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.33440 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace SlightNetRepairer.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } } }
39.703704
151
0.583955
[ "MIT" ]
Silvenga/Small-Projects
SchoolCode/Code/VS Workspace/SlightNetRepairer/SlightNetRepairer/Properties/Settings.Designer.cs
1,074
C#
using System.Collections.Immutable; namespace com.tinylabproductions.TLPLib.Extensions { public static class ImmutableHashSetExts { public static ImmutableHashSet<A> toggle<A>(this ImmutableHashSet<A> hs, A a) => hs.Contains(a) ? hs.Remove(a) : hs.Add(a); } }
34.375
84
0.730909
[ "MIT" ]
JurgisRainys/tlplib
parts/0000-TLPLib/Assets/Plugins/Vendor/TLPLib/Extensions/IImmutableSetExts.cs
277
C#
using System.Security.Principal; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; namespace FubarDev.WebDavServer.Sample.AspNetCore.Middlewares { public class ImpersonationMiddleware { private readonly RequestDelegate _next; public ImpersonationMiddleware(RequestDelegate next) { _next = next; } // ReSharper disable once UnusedMember.Local public async Task Invoke(HttpContext context) { if (!(context.User.Identity is WindowsIdentity identity) || !identity.IsAuthenticated) { await _next(context); } else { await WindowsIdentity.RunImpersonated( identity.AccessToken, async () => { await _next(context); }); } } } }
26.333333
98
0.581128
[ "MIT" ]
FubarDevelopment/WebDavServer
sample/FubarDev.WebDavServer.Sample.AspNetCore/Middlewares/ImpersonationMiddleware.cs
871
C#
// Project: Daggerfall Tools For Unity // Copyright: Copyright (C) 2009-2018 Daggerfall Workshop // Web Site: http://www.dfworkshop.net // License: MIT License (http://www.opensource.org/licenses/mit-license.php) // Source Code: https://github.com/Interkarma/daggerfall-unity // Original Author: Gavin Clayton (interkarma@dfworkshop.net) // Contributors: InconsolableCellist // // Notes: // using System; using System.IO; using System.Collections.Generic; using UnityEngine; using DaggerfallWorkshop.Game.Entity; using DaggerfallConnect.FallExe; using DaggerfallConnect.Arena2; using DaggerfallWorkshop.Utility; namespace DaggerfallWorkshop.Game.Items { /// <summary> /// Generates new items for various game systems. /// This helper still under development. /// </summary> public static class ItemBuilder { #region Data const int firstFemaleArchive = 245; const int firstMaleArchive = 249; // This array is used to pick random material values. // The array is traversed, subtracting each value from a sum until the sum is less than the next value. // Steel through Daedric, or Iron if sum is less than the first value. static readonly byte[] materialsByModifier = { 64, 128, 10, 21, 13, 8, 5, 3, 2, 5 }; // Weight multipliers by material type. Iron through Daedric. Weight is baseWeight * value / 4. static readonly short[] weightMultipliersByMaterial = { 4, 5, 4, 4, 3, 4, 4, 2, 4, 5 }; // Value multipliers by material type. Iron through Daedric. Value is baseValue * ( 3 * value). static readonly short[] valueMultipliersByMaterial = { 1, 2, 4, 8, 16, 32, 64, 128, 256, 512 }; // Condition multipliers by material type. Iron through Daedric. MaxCondition is baseMaxCondition * value / 4. static readonly short[] conditionMultipliersByMaterial = { 4, 4, 6, 8, 12, 16, 20, 24, 28, 32 }; // Enchantment point multipliers by material type. Iron through Daedric. Enchantment points is baseEnchanmentPoints * value / 4. static readonly short[] enchantmentPointMultipliersByMaterial = { 3, 4, 7, 5, 6, 5, 7, 8, 10, 12 }; // Value of potions indexed by recipe static readonly ushort[] potionValues = { 25, 50, 50, 50, 75, 75, 75, 75, 100, 100, 100, 100, 125, 125, 125, 200, 200, 200, 250, 500 }; // Enchantment point/gold value data for item powers static readonly int[] extraSpellPtsEnchantPts = { 0x1F4, 0x1F4, 0x1F4, 0x1F4, 0xC8, 0xC8, 0xC8, 0x2BC, 0x320, 0x384, 0x3E8 }; static readonly int[] potentVsEnchantPts = { 0x320, 0x384, 0x3E8, 0x4B0 }; static readonly int[] regensHealthEnchantPts = { 0x0FA0, 0x0BB8, 0x0BB8 }; static readonly int[] vampiricEffectEnchantPts = { 0x7D0, 0x3E8 }; static readonly int[] increasedWeightAllowanceEnchantPts = { 0x190, 0x258 }; static readonly int[] improvesTalentsEnchantPts = { 0x1F4, 0x258, 0x258 }; static readonly int[] goodRepWithEnchantPts = { 0x3E8, 0x3E8, 0x3E8, 0x3E8, 0x3E8, 0x1388 }; static readonly int[][] enchantmentPtsForItemPowerArrays = { null, null, null, extraSpellPtsEnchantPts, potentVsEnchantPts, regensHealthEnchantPts, vampiricEffectEnchantPts, increasedWeightAllowanceEnchantPts, null, null, null, null, null, improvesTalentsEnchantPts, goodRepWithEnchantPts}; static readonly ushort[] enchantmentPointCostsForNonParamTypes = { 0, 0x0F448, 0x0F63C, 0x0FF9C, 0x0FD44, 0, 0, 0, 0x384, 0x5DC, 0x384, 0x64, 0x2BC }; private enum BodyMorphology { Argonian = 0, Elf = 1, Human = 2, Khajiit = 3, } static DyeColors[] clothingDyes = new DyeColors[] { DyeColors.Blue, DyeColors.Grey, DyeColors.Red, DyeColors.DarkBrown, DyeColors.Purple, DyeColors.LightBrown, DyeColors.White, DyeColors.Aquamarine, DyeColors.Yellow, DyeColors.Green, }; #endregion #region Public Methods public static DyeColors RandomClothingDye() { return clothingDyes[UnityEngine.Random.Range(0, clothingDyes.Length)]; } /// <summary> /// Gets a random material based on player level. /// </summary> /// <param name="playerLevel">Player level.</param> /// <returns>WeaponMaterialTypes.</returns> public static WeaponMaterialTypes RandomMaterial(int playerLevel) { int levelModifier = (playerLevel - 10); if (levelModifier >= 0) levelModifier *= 2; else levelModifier *= 4; int randomModifier = UnityEngine.Random.Range(0, 256); int combinedModifiers = levelModifier + randomModifier; combinedModifiers = Mathf.Clamp(combinedModifiers, 0, 256); int material = 0; // initialize to iron // The higher combinedModifiers is, the higher the material while (materialsByModifier[material] < combinedModifiers) { combinedModifiers -= materialsByModifier[material++]; } return (WeaponMaterialTypes)(material); } /// <summary> /// Gets a random armor material based on player level. /// </summary> /// <param name="playerLevel">Player level.</param> /// <returns>ArmorMaterialTypes.</returns> public static ArmorMaterialTypes RandomArmorMaterial(int playerLevel) { // Random armor material int random = UnityEngine.Random.Range(1, 101); if (random >= 70) { if (random >= 90) { WeaponMaterialTypes plateMaterial = RandomMaterial(playerLevel); return (ArmorMaterialTypes)(0x0200 + plateMaterial); } else return ArmorMaterialTypes.Chain; } else return ArmorMaterialTypes.Leather; } /// <summary> /// Creates a generic item from group and template index. /// </summary> /// <param name="itemGroup">Item group.</param> /// <param name="itemIndex">Template index.</param> /// <returns>DaggerfallUnityItem.</returns> public static DaggerfallUnityItem CreateItem(ItemGroups itemGroup, int templateIndex) { // Create item int groupIndex = DaggerfallUnity.Instance.ItemHelper.GetGroupIndex(itemGroup, templateIndex); DaggerfallUnityItem newItem = new DaggerfallUnityItem(itemGroup, groupIndex); return newItem; } /// <summary> /// Generates men's clothing. /// </summary> /// <param name="item">Item type to generate.</param> /// <param name="race">Race of player.</param> /// <param name="variant">Variant to use. If not set, a random variant will be selected.</param> /// <param name="dye">Dye to use</param> /// <returns>DaggerfallUnityItem.</returns> public static DaggerfallUnityItem CreateMensClothing(MensClothing item, Races race, int variant = -1, DyeColors dye = DyeColors.Blue) { // Create item int groupIndex = DaggerfallUnity.Instance.ItemHelper.GetGroupIndex(ItemGroups.MensClothing, (int)item); DaggerfallUnityItem newItem = new DaggerfallUnityItem(ItemGroups.MensClothing, groupIndex); // Random variant if (variant < 0) variant = UnityEngine.Random.Range(0, newItem.ItemTemplate.variants); // Set race, variant, dye SetRace(newItem, race); SetVariant(newItem, variant); newItem.dyeColor = dye; return newItem; } /// <summary> /// Generates women's clothing. /// </summary> /// <param name="item">Item type to generate.</param> /// <param name="race">Race of player.</param> /// <param name="variant">Variant to use. If not set, a random variant will be selected.</param> /// <param name="dye">Dye to use</param> /// <returns>DaggerfallUnityItem.</returns> public static DaggerfallUnityItem CreateWomensClothing(WomensClothing item, Races race, int variant = -1, DyeColors dye = DyeColors.Blue) { // Create item int groupIndex = DaggerfallUnity.Instance.ItemHelper.GetGroupIndex(ItemGroups.WomensClothing, (int)item); DaggerfallUnityItem newItem = new DaggerfallUnityItem(ItemGroups.WomensClothing, groupIndex); // Random variant if (variant < 0) variant = UnityEngine.Random.Range(0, newItem.ItemTemplate.variants); // Set race, variant, dye SetRace(newItem, race); SetVariant(newItem, variant); newItem.dyeColor = dye; return newItem; } /// <summary> /// Creates a new item of random clothing. /// </summary> /// <param name="gender">Gender of player</param> /// <returns>DaggerfallUnityItem.</returns> public static DaggerfallUnityItem CreateRandomClothing(Genders gender, Races race) { // Create random clothing by gender DaggerfallUnityItem newItem; if (gender == Genders.Male) { Array enumArray = DaggerfallUnity.Instance.ItemHelper.GetEnumArray(ItemGroups.MensClothing); int groupIndex = UnityEngine.Random.Range(0, enumArray.Length); newItem = new DaggerfallUnityItem(ItemGroups.MensClothing, groupIndex); } else { Array enumArray = DaggerfallUnity.Instance.ItemHelper.GetEnumArray(ItemGroups.WomensClothing); int groupIndex = UnityEngine.Random.Range(0, enumArray.Length); newItem = new DaggerfallUnityItem(ItemGroups.WomensClothing, groupIndex); } SetRace(newItem, race); // Random dye colour newItem.dyeColor = RandomClothingDye(); // Random variant SetVariant(newItem, UnityEngine.Random.Range(0, newItem.TotalVariants)); return newItem; } /// <summary> /// Creates a new random book /// </summary> /// <returns>DaggerfallUnityItem.</returns> public static DaggerfallUnityItem CreateRandomBook() { Array enumArray = DaggerfallUnity.Instance.ItemHelper.GetEnumArray(ItemGroups.Books); DaggerfallUnityItem book = new DaggerfallUnityItem(ItemGroups.Books, Array.IndexOf(enumArray, Books.Book0)); // TODO: FIXME: I don't know what the higher order bits are for the message field. I just know that message & 0xFF encodes // the ID of the book. Thus the books that are randomly generated are missing information that the actual game provides. // -IC112016 book.message = DaggerfallUnity.Instance.ItemHelper.getRandomBookID(); return book; } /// <summary> /// Creates a new random religious item. /// </summary> /// <returns>DaggerfallUnityItem.</returns> public static DaggerfallUnityItem CreateRandomReligiousItem() { Array enumArray = DaggerfallUnity.Instance.ItemHelper.GetEnumArray(ItemGroups.ReligiousItems); int groupIndex = UnityEngine.Random.Range(0, enumArray.Length); DaggerfallUnityItem newItem = new DaggerfallUnityItem(ItemGroups.ReligiousItems, groupIndex); return newItem; } /// <summary> /// Creates a new random gem. /// </summary> /// <returns>DaggerfallUnityItem.</returns> public static DaggerfallUnityItem CreateRandomGem() { Array enumArray = DaggerfallUnity.Instance.ItemHelper.GetEnumArray(ItemGroups.Gems); int groupIndex = UnityEngine.Random.Range(0, enumArray.Length); DaggerfallUnityItem newItem = new DaggerfallUnityItem(ItemGroups.Gems, groupIndex); return newItem; } /// <summary> /// Creates a new random jewellery. /// </summary> /// <returns>DaggerfallUnityItem.</returns> public static DaggerfallUnityItem CreateRandomJewellery() { Array enumArray = DaggerfallUnity.Instance.ItemHelper.GetEnumArray(ItemGroups.Jewellery); int groupIndex = UnityEngine.Random.Range(0, enumArray.Length); DaggerfallUnityItem newItem = new DaggerfallUnityItem(ItemGroups.Jewellery, groupIndex); return newItem; } /// <summary> /// Generates a weapon. /// </summary> /// <param name="weapon"></param> /// <param name="material"></param> /// <returns></returns> public static DaggerfallUnityItem CreateWeapon(Weapons weapon, WeaponMaterialTypes material) { // Create item int groupIndex = DaggerfallUnity.Instance.ItemHelper.GetGroupIndex(ItemGroups.Weapons, (int)weapon); DaggerfallUnityItem newItem = new DaggerfallUnityItem(ItemGroups.Weapons, groupIndex); // Adjust material newItem.nativeMaterialValue = (int)material; newItem = SetItemPropertiesByMaterial(newItem, material); newItem.dyeColor = DaggerfallUnity.Instance.ItemHelper.GetWeaponDyeColor(material); // Handle arrows if (groupIndex == 18) { newItem.stackCount = UnityEngine.Random.Range(1, 21); newItem.currentCondition = 0; // not sure if this is necessary, but classic does it } return newItem; } /// <summary> /// Creates random weapon. /// </summary> /// <param name="playerLevel">Player level for material type.</param> /// <returns>DaggerfallUnityItem</returns> public static DaggerfallUnityItem CreateRandomWeapon(int playerLevel) { // Create random weapon type Array enumArray = DaggerfallUnity.Instance.ItemHelper.GetEnumArray(ItemGroups.Weapons); int groupIndex = UnityEngine.Random.Range(0, enumArray.Length); DaggerfallUnityItem newItem = new DaggerfallUnityItem(ItemGroups.Weapons, groupIndex); // Random weapon material WeaponMaterialTypes material = RandomMaterial(playerLevel); newItem.nativeMaterialValue = (int)material; newItem = SetItemPropertiesByMaterial(newItem, material); newItem.dyeColor = DaggerfallUnity.Instance.ItemHelper.GetWeaponDyeColor(material); // Handle arrows if (groupIndex == 18) { newItem.stackCount = UnityEngine.Random.Range(1, 21); newItem.currentCondition = 0; // not sure if this is necessary, but classic does it } return newItem; } /// <summary> /// Generates armour. /// </summary> /// <param name="gender">Gender armor is created for.</param> /// <param name="race">Race armor is created for.</param> /// <param name="armor">Type of armor item to create.</param> /// <param name="material">Material of armor.</param> /// <param name="variant">Visual variant of armor. If -1, a random variant is chosen.</param> /// <returns>DaggerfallUnityItem</returns> public static DaggerfallUnityItem CreateArmor(Genders gender, Races race, Armor armor, ArmorMaterialTypes material, int variant = -1) { // Create item int groupIndex = DaggerfallUnity.Instance.ItemHelper.GetGroupIndex(ItemGroups.Armor, (int)armor); DaggerfallUnityItem newItem = new DaggerfallUnityItem(ItemGroups.Armor, groupIndex); // Adjust for gender if (gender == Genders.Female) newItem.PlayerTextureArchive = firstFemaleArchive; else newItem.PlayerTextureArchive = firstMaleArchive; // Adjust for body morphology SetRace(newItem, race); // Adjust material newItem.nativeMaterialValue = (int)material; if (newItem.nativeMaterialValue == (int)ArmorMaterialTypes.Leather) newItem.weightInKg /= 2; else if (newItem.nativeMaterialValue == (int)ArmorMaterialTypes.Chain) newItem.value *= 2; else if (newItem.nativeMaterialValue >= (int)ArmorMaterialTypes.Iron) { int plateMaterial = newItem.nativeMaterialValue - 0x0200; newItem = SetItemPropertiesByMaterial(newItem, (WeaponMaterialTypes)plateMaterial); } newItem.dyeColor = DaggerfallUnity.Instance.ItemHelper.GetArmorDyeColor((ArmorMaterialTypes)newItem.nativeMaterialValue); FixLeatherHelm(newItem); // Adjust for variant if (variant >= 0) SetVariant(newItem, variant); else RandomizeArmorVariant(newItem); return newItem; } /// <summary> /// Creates random armor. /// </summary> /// <param name="playerLevel">Player level for material type.</param> /// <param name="gender">Gender armor is created for.</param> /// <param name="race">Race armor is created for.</param> /// <returns>DaggerfallUnityItem</returns> public static DaggerfallUnityItem CreateRandomArmor(int playerLevel, Genders gender, Races race) { // Create random armor type Array enumArray = DaggerfallUnity.Instance.ItemHelper.GetEnumArray(ItemGroups.Armor); int groupIndex = UnityEngine.Random.Range(0, enumArray.Length); DaggerfallUnityItem newItem = new DaggerfallUnityItem(ItemGroups.Armor, groupIndex); // Adjust for gender if (gender == Genders.Female) newItem.PlayerTextureArchive = firstFemaleArchive; else newItem.PlayerTextureArchive = firstMaleArchive; // Adjust for body morphology SetRace(newItem, race); // Random armor material ArmorMaterialTypes material = RandomArmorMaterial(playerLevel); newItem.nativeMaterialValue = (int)material; if (newItem.nativeMaterialValue == (int)ArmorMaterialTypes.Leather) newItem.weightInKg /= 2; else if (newItem.nativeMaterialValue == (int)ArmorMaterialTypes.Chain) newItem.value *= 2; else if (newItem.nativeMaterialValue >= (int)ArmorMaterialTypes.Iron) { int plateMaterial = newItem.nativeMaterialValue - 0x0200; newItem = SetItemPropertiesByMaterial(newItem, (WeaponMaterialTypes)plateMaterial); } newItem.dyeColor = DaggerfallUnity.Instance.ItemHelper.GetArmorDyeColor(material); FixLeatherHelm(newItem); RandomizeArmorVariant(newItem); return newItem; } /// <summary> /// Creates random magic item in same manner as classic. /// </summary> /// <returns>DaggerfallUnityItem</returns> public static DaggerfallUnityItem CreateRandomMagicItem(int playerLevel, Genders gender, Races race) { byte[] itemGroups0 = { 2, 3, 6, 10, 12, 14, 25 }; byte[] itemGroups1 = { 2, 3, 6, 12, 25 }; DaggerfallUnityItem newItem = null; // Get the list of magic item templates read from MAGIC.DEF MagicItemsFile magicItemsFile = new MagicItemsFile(Path.Combine(DaggerfallUnity.Instance.Arena2Path, "MAGIC.DEF")); List<MagicItemTemplate> magicItems = magicItemsFile.MagicItemsList; // Get the number of non-artifact magic item templates in MAGIC.DEF int numberOfRegularMagicItems = 0; foreach (MagicItemTemplate magicItem in magicItems) { if (magicItem.type == MagicItemTypes.RegularMagicItem) numberOfRegularMagicItems++; } // Choose a random one of the non-artifact magic item templates int chosenItem = UnityEngine.Random.Range(0, numberOfRegularMagicItems); // Get the chosen template foreach (MagicItemTemplate magicItem in magicItems) { if (magicItem.type == MagicItemTypes.RegularMagicItem) { // Proceed when the template is found if (chosenItem == 0) { // Get the item group. The possible groups are determined by the 33rd byte (magicItem.group) of the MAGIC.DEF template being used. ItemGroups group = 0; if (magicItem.group == 0) group = (ItemGroups)itemGroups0[UnityEngine.Random.Range(0, 7)]; else if (magicItem.group == 1) group = (ItemGroups)itemGroups1[UnityEngine.Random.Range(0, 5)]; else if (magicItem.group == 2) group = ItemGroups.Weapons; // Create the base item if (group == ItemGroups.Weapons) { newItem = CreateRandomWeapon(playerLevel); // No arrows as enchanted items while (newItem.GroupIndex == 18) newItem = CreateRandomWeapon(playerLevel); } else if (group == ItemGroups.Armor) newItem = CreateRandomArmor(playerLevel, gender, race); else if (group == ItemGroups.MensClothing || group == ItemGroups.WomensClothing) newItem = CreateRandomClothing(gender, race); else if (group == ItemGroups.ReligiousItems) newItem = CreateRandomReligiousItem(); else if (group == ItemGroups.Gems) newItem = CreateRandomGem(); else // Only other possibility is jewellery newItem = CreateRandomJewellery(); // Replace the regular item name with the magic item name newItem.shortName = magicItem.name; // Add the enchantments newItem.legacyMagic = new DaggerfallEnchantment[magicItem.enchantments.Length]; for (int i = 0; i < magicItem.enchantments.Length; ++i ) newItem.legacyMagic[i] = magicItem.enchantments[i]; // Set the condition/magic uses newItem.maxCondition = magicItem.uses; newItem.currentCondition = magicItem.uses; // Set the value of the item. This is determined by the enchantment point cost/spell-casting cost // of the enchantments on the item. int value = 0; for (int i = 0; i < magicItem.enchantments.Length; ++i) { if (magicItem.enchantments[i].type != EnchantmentTypes.None && magicItem.enchantments[i].type < EnchantmentTypes.ItemDeteriorates) { switch (magicItem.enchantments[i].type) { // Enchantments that cast a spell. The parameter is the spell index in SPELLS.STD. case EnchantmentTypes.CastWhenUsed: case EnchantmentTypes.CastWhenHeld: case EnchantmentTypes.CastWhenStrikes: value += Formulas.FormulaHelper.GetSpellEnchantPtCost(magicItem.enchantments[i].param); break; // Enchantments that provide an effect that has no parameters case EnchantmentTypes.RepairsObjects: case EnchantmentTypes.AbsorbsSpells: case EnchantmentTypes.EnhancesSkill: case EnchantmentTypes.FeatherWeight: case EnchantmentTypes.StrengthensArmor: value += enchantmentPointCostsForNonParamTypes[(int)magicItem.enchantments[i].type]; break; // Bound soul case EnchantmentTypes.SoulBound: MobileEnemy mobileEnemy = GameObjectHelper.EnemyDict[magicItem.enchantments[i].param]; value += mobileEnemy.SoulPts; // TODO: Not sure about this. Should be negative? Needs to be tested. break; default: // Enchantments that provide a non-spell effect with a parameter (when effect applies, what enemies are affected, etc.) value += enchantmentPtsForItemPowerArrays[(int)magicItem.enchantments[i].type][magicItem.enchantments[i].param]; break; } } } newItem.value = value; break; } chosenItem--; } } if (newItem == null) throw new Exception("CreateRandomMagicItem() failed to create an item."); return newItem; } /// <summary> /// Sets properties for a weapon or piece of armor based on its material. /// </summary> /// <param name="item">Item to have its properties modified.</param> /// <param name="material">Material to use to apply properties.</param> /// <returns>DaggerfallUnityItem</returns> public static DaggerfallUnityItem SetItemPropertiesByMaterial(DaggerfallUnityItem item, WeaponMaterialTypes material) { item.value *= 3 * valueMultipliersByMaterial[(int)material]; item.weightInKg = CalculateWeightForMaterial(item, material); item.maxCondition *= conditionMultipliersByMaterial[(int)material] / 4; item.currentCondition = item.maxCondition; item.enchantmentPoints *= enchantmentPointMultipliersByMaterial[(int)material] / 4; return item; } static float CalculateWeightForMaterial(DaggerfallUnityItem item, WeaponMaterialTypes material) { int quarterKgs = (int)(item.weightInKg * 4); float matQuarterKgs = (float)(quarterKgs * weightMultipliersByMaterial[(int)material]) / 4; return Mathf.Round(matQuarterKgs) / 4; } /// <summary> /// Creates a random ingredient from any of the ingredient groups. /// Passing a non-ingredient group will return null. /// </summary> /// <param name="group">Ingedient group.</param> /// <returns>DaggerfallUnityItem</returns> public static DaggerfallUnityItem CreateRandomIngredient(ItemGroups ingredientGroup) { int groupIndex; Array enumArray; switch (ingredientGroup) { case ItemGroups.CreatureIngredients1: case ItemGroups.CreatureIngredients2: case ItemGroups.CreatureIngredients3: case ItemGroups.MetalIngredients: case ItemGroups.MiscellaneousIngredients1: case ItemGroups.MiscellaneousIngredients2: case ItemGroups.PlantIngredients1: case ItemGroups.PlantIngredients2: enumArray = DaggerfallUnity.Instance.ItemHelper.GetEnumArray(ingredientGroup); groupIndex = UnityEngine.Random.Range(0, enumArray.Length); break; default: return null; } // Create item DaggerfallUnityItem newItem = new DaggerfallUnityItem(ingredientGroup, groupIndex); return newItem; } /// <summary> /// Creates a random ingredient from a random ingredient group. /// </summary> /// <returns>DaggerfallUnityItem</returns> public static DaggerfallUnityItem CreateRandomIngredient() { // Randomise ingredient group ItemGroups itemGroup = ItemGroups.None; int group = UnityEngine.Random.Range(0, 7); Array enumArray; switch (group) { case 0: itemGroup = ItemGroups.CreatureIngredients1; break; case 1: itemGroup = ItemGroups.CreatureIngredients2; break; case 2: itemGroup = ItemGroups.CreatureIngredients3; break; case 3: itemGroup = ItemGroups.MetalIngredients; break; case 4: itemGroup = ItemGroups.MiscellaneousIngredients1; break; case 5: itemGroup = ItemGroups.MiscellaneousIngredients2; break; case 6: itemGroup = ItemGroups.PlantIngredients1; break; case 7: itemGroup = ItemGroups.PlantIngredients2; break; default: return null; } // Randomise ingredient within group enumArray = DaggerfallUnity.Instance.ItemHelper.GetEnumArray(itemGroup); int groupIndex = UnityEngine.Random.Range(0, enumArray.Length); // Create item DaggerfallUnityItem newItem = new DaggerfallUnityItem(itemGroup, groupIndex); return newItem; } /// <summary> /// Creates a potion /// </summary> /// <param name="recipe">Recipe index for the potion</param> /// <returns>DaggerfallUnityItem</returns> public static DaggerfallUnityItem CreatePotion(byte recipe) { return new DaggerfallUnityItem(ItemGroups.UselessItems1, 1) { typeDependentData = recipe, value = potionValues[recipe], }; } /// <summary> /// Creates a random potion /// </summary> /// <returns>DaggerfallUnityItem</returns> public static DaggerfallUnityItem CreateRandomPotion() { byte recipe = (byte) UnityEngine.Random.Range(0, 20); return CreatePotion(recipe); } /// <summary> /// Generates gold pieces. /// </summary> /// <param name="amount">Total number of gold pieces in stack.</param> /// <returns></returns> public static DaggerfallUnityItem CreateGoldPieces(int amount) { DaggerfallUnityItem newItem = CreateItem(ItemGroups.Currency, (int)Currency.Gold_pieces); newItem.stackCount = amount; return newItem; } /// <summary> /// Sets a random variant of clothing item. /// </summary> /// <param name="item">Item to randomize variant.</param> public static void RandomizeClothingVariant(DaggerfallUnityItem item) { int totalVariants = item.ItemTemplate.variants; SetVariant(item, UnityEngine.Random.Range(0, totalVariants)); } /// <summary> /// Sets a random variant of armor item. /// </summary> /// <param name="item">Item to randomize variant.</param> public static void RandomizeArmorVariant(DaggerfallUnityItem item) { int variant = 0; // We only need to pick randomly where there is more than one possible variant. Otherwise we can just pass in 0 to SetVariant and // the correct variant will still be chosen. if (item.IsOfTemplate(ItemGroups.Armor, (int)Armor.Cuirass) && (item.nativeMaterialValue >= (int)ArmorMaterialTypes.Iron)) { variant = UnityEngine.Random.Range(1, 4); } else if (item.IsOfTemplate(ItemGroups.Armor, (int)Armor.Greaves)) { if (item.nativeMaterialValue == (int)ArmorMaterialTypes.Leather) variant = UnityEngine.Random.Range(0, 2); else if (item.nativeMaterialValue >= (int)ArmorMaterialTypes.Iron) variant = UnityEngine.Random.Range(2, 6); } else if (item.IsOfTemplate(ItemGroups.Armor, (int)Armor.Left_Pauldron) || item.IsOfTemplate(ItemGroups.Armor, (int)Armor.Right_Pauldron)) { if (item.nativeMaterialValue >= (int)ArmorMaterialTypes.Iron) variant = UnityEngine.Random.Range(1, 4); } else if (item.IsOfTemplate(ItemGroups.Armor, (int)Armor.Helm)) variant = UnityEngine.Random.Range(0, item.ItemTemplate.variants); SetVariant(item, variant); } /// <summary> /// Set leather helms to use chain dye. /// Daggerfall seems to do this also as "leather" helms have the chain tint in-game. /// Might need to revisit this later. /// </summary> public static void FixLeatherHelm(DaggerfallUnityItem item) { if (item.TemplateIndex == (int)Armor.Helm && (ArmorMaterialTypes)item.nativeMaterialValue == ArmorMaterialTypes.Leather) item.dyeColor = DyeColors.Chain; } #endregion #region Private Methods static void SetRace(DaggerfallUnityItem item, Races race) { int offset = (int)GetBodyMorphology(race); item.PlayerTextureArchive += offset; } static void SetVariant(DaggerfallUnityItem item, int variant) { // Range check int totalVariants = item.ItemTemplate.variants; if (variant < 0 || variant >= totalVariants) return; // Clamp to appropriate variant based on material family if (item.IsOfTemplate(ItemGroups.Armor, (int)Armor.Cuirass)) { if (item.nativeMaterialValue == (int)ArmorMaterialTypes.Leather) variant = 0; else if (item.nativeMaterialValue == (int)ArmorMaterialTypes.Chain || item.nativeMaterialValue == (int)ArmorMaterialTypes.Chain2) variant = 4; else variant = Mathf.Clamp(variant, 1, 3); } else if (item.IsOfTemplate(ItemGroups.Armor, (int)Armor.Greaves)) { if (item.nativeMaterialValue == (int)ArmorMaterialTypes.Leather) variant = Mathf.Clamp(variant, 0, 1); else if (item.nativeMaterialValue == (int)ArmorMaterialTypes.Chain || item.nativeMaterialValue == (int)ArmorMaterialTypes.Chain2) variant = 6; else variant = Mathf.Clamp(variant, 2, 5); } else if (item.IsOfTemplate(ItemGroups.Armor, (int)Armor.Left_Pauldron) || item.IsOfTemplate(ItemGroups.Armor, (int)Armor.Right_Pauldron)) { if (item.nativeMaterialValue == (int)ArmorMaterialTypes.Leather) variant = 0; else if (item.nativeMaterialValue == (int)ArmorMaterialTypes.Chain || item.nativeMaterialValue == (int)ArmorMaterialTypes.Chain2) variant = 4; else variant = Mathf.Clamp(variant, 1, 3); } else if (item.IsOfTemplate(ItemGroups.Armor, (int)Armor.Gauntlets)) { if (item.nativeMaterialValue == (int)ArmorMaterialTypes.Leather) variant = 0; else variant = 1; } else if (item.IsOfTemplate(ItemGroups.Armor, (int)Armor.Boots)) { if (item.nativeMaterialValue == (int)ArmorMaterialTypes.Leather) variant = 0; else variant = 1; } // Store variant item.CurrentVariant = variant; } static BodyMorphology GetBodyMorphology(Races race) { switch (race) { case Races.Argonian: return BodyMorphology.Argonian; case Races.DarkElf: case Races.HighElf: case Races.WoodElf: return BodyMorphology.Elf; case Races.Breton: case Races.Nord: case Races.Redguard: return BodyMorphology.Human; case Races.Khajiit: return BodyMorphology.Khajiit; default: throw new Exception("GetBodyMorphology() encountered unsupported race value."); } } #endregion } }
43.789474
159
0.573709
[ "MIT" ]
TheExceptionist/daggerfall-unity
Assets/Scripts/Game/Items/ItemBuilder.cs
38,272
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Linq; using Xunit; namespace System.IO.FileSystem.DriveInfoTests { public partial class DriveInfoUnixTests { [Fact] [PlatformSpecific(PlatformID.AnyUnix)] public void TestConstructor() { Assert.All( new[] { "", "\0", "\0/" }, driveName => Assert.Throws<ArgumentException>("driveName", () => { new DriveInfo(driveName); })); Assert.Throws<ArgumentNullException>("driveName", () => { new DriveInfo(null); }); Assert.Equal("/", new DriveInfo("/").Name); } [Fact] [PlatformSpecific(PlatformID.AnyUnix)] public void TestGetDrives() { var drives = DriveInfo.GetDrives(); Assert.NotNull(drives); Assert.True(drives.Length > 0, "Expected at least one drive"); Assert.All(drives, d => Assert.NotNull(d)); Assert.Contains(drives, d => d.Name == "/"); } [Fact] [PlatformSpecific(PlatformID.AnyUnix)] public void TestInvalidDriveName() { var invalidDrive = new DriveInfo("NonExistentDriveName"); Assert.Throws<DriveNotFoundException>(() => { var df = invalidDrive.DriveFormat; }); Assert.Throws<DriveNotFoundException>(() => { var size = invalidDrive.DriveType; }); Assert.Throws<DriveNotFoundException>(() => { var size = invalidDrive.TotalFreeSpace; }); Assert.Throws<DriveNotFoundException>(() => { var size = invalidDrive.TotalSize; }); } [Fact] [PlatformSpecific(PlatformID.AnyUnix)] public void TestProperties() { var root = new DriveInfo("/"); Assert.Equal("/", root.Name); Assert.Equal("/", root.RootDirectory.FullName); Assert.Equal(DriveType.Ram, root.DriveType); Assert.True(root.IsReady); Assert.True(root.AvailableFreeSpace > 0); Assert.True(root.TotalFreeSpace > 0); Assert.True(root.TotalSize > 0); } } }
37.25
113
0.582103
[ "MIT" ]
sharwell/corefx
src/System.IO.FileSystem.DriveInfo/tests/DriveInfo.Unix.Tests.cs
2,237
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; namespace System.Runtime.InteropServices { public sealed class HandleCollector { private const int DeltaPercent = 10; // this is used for increasing the threshold. private int _initialThreshold; private int _threshold; private int _handleCount; private int[] _gc_counts = new int[3]; private int _gc_gen = 0; public HandleCollector(string name, int initialThreshold) : this(name, initialThreshold, int.MaxValue) { } public HandleCollector(string name, int initialThreshold, int maximumThreshold) { if (initialThreshold < 0) { throw new ArgumentOutOfRangeException(nameof(initialThreshold), SR.Arg_NeedNonNegNumRequired); } if (maximumThreshold < 0) { throw new ArgumentOutOfRangeException(nameof(maximumThreshold), SR.Arg_NeedNonNegNumRequired); } if (initialThreshold > maximumThreshold) { throw new ArgumentException(SR.Arg_InvalidThreshold); } Name = name ?? string.Empty; _initialThreshold = initialThreshold; MaximumThreshold = maximumThreshold; _threshold = initialThreshold; _handleCount = 0; } public int Count => _handleCount; public int InitialThreshold => _initialThreshold; public int MaximumThreshold { get; } public string Name { get; } public void Add() { int gen_collect = -1; Interlocked.Increment(ref _handleCount); if (_handleCount < 0) { throw new InvalidOperationException(SR.InvalidOperation_HCCountOverflow); } if (_handleCount > _threshold) { lock (this) { _threshold = _handleCount + (_handleCount / DeltaPercent); gen_collect = _gc_gen; if (_gc_gen < 2) { _gc_gen++; } } } if ((gen_collect >= 0) && ((gen_collect == 0) || (_gc_counts[gen_collect] == GC.CollectionCount(gen_collect)))) { GC.Collect(gen_collect); Internal.Runtime.Augments.RuntimeThread.Sleep(10 * gen_collect); } //don't bother with gen0. for (int i = 1; i < 3; i++) { _gc_counts[i] = GC.CollectionCount(i); } } public void Remove() { Interlocked.Decrement(ref _handleCount); if (_handleCount < 0) { throw new InvalidOperationException(SR.InvalidOperation_HCCountOverflow); } int newThreshold = _handleCount + _handleCount / DeltaPercent; if (newThreshold < (_threshold - _threshold / DeltaPercent)) { lock (this) { if (newThreshold > _initialThreshold) { _threshold = newThreshold; } else { _threshold = _initialThreshold; } _gc_gen = 0; } } for (int i = 1; i < 3; i++) { _gc_counts[i] = GC.CollectionCount(i); } } } }
30.656
110
0.50548
[ "MIT" ]
2E0PGS/corefx
src/System.Runtime.InteropServices/src/System/Runtime/InteropServices/HandleCollector.cs
3,832
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. using Steeltoe.Management.Endpoint.Test; using System; using Xunit; namespace Steeltoe.Management.Endpoint.Loggers.Test; public class LoggersChangeRequestTest : BaseTest { [Fact] public void Constructor_ThrowsOnNull_Name() { Assert.Throws<ArgumentException>(() => new LoggersChangeRequest(null, "foobar")); } [Fact] public void Constructor_SetsProperties() { var cr = new LoggersChangeRequest("foo", "bar"); Assert.Equal("foo", cr.Name); Assert.Equal("bar", cr.Level); } [Fact] public void Constructor_AllowsReset() { var cr = new LoggersChangeRequest("foo", null); Assert.Equal("foo", cr.Name); Assert.Null(cr.Level); } }
26.914286
89
0.674098
[ "Apache-2.0" ]
SteeltoeOSS/steeltoe
src/Management/test/EndpointBase.Test/Loggers/LoggersChangeRequestTest.cs
942
C#
using System; using System.Linq; using Blockcore.Consensus; using Blockcore.Consensus.BlockInfo; using Blockcore.Consensus.Chain; using Blockcore.Consensus.ScriptInfo; using Blockcore.Consensus.TransactionInfo; using Blockcore.Features.Consensus.CoinViews; using Blockcore.Features.Consensus.Rules.ProvenHeaderRules; using Blockcore.Tests.Common; using Blockcore.Utilities; using FluentAssertions; using Moq; using NBitcoin; using NBitcoin.Crypto; using Xunit; using uint256 = NBitcoin.uint256; namespace Blockcore.Features.Consensus.Tests.Rules.ProvenHeaderRules { public class ProvenBlockHeaderCoinstakeRuleTest : TestPosConsensusRulesUnitTestBase { private readonly PosConsensusOptions options; private int provenHeadersActivationHeight; public ProvenBlockHeaderCoinstakeRuleTest() { this.options = (PosConsensusOptions)this.network.Consensus.Options; this.provenHeadersActivationHeight = this.network.Checkpoints.Keys.Last(); } [Fact] public void RunRule_ProvenHeadersNotActive_RuleIsSkipped() { // Setup proven header. PosBlock posBlock = new PosBlockBuilder(this.network).Build(); ProvenBlockHeader provenBlockHeader = new ProvenBlockHeaderBuilder(posBlock, this.network).Build(); // Setup chained header and move it to the height below proven header activation height. this.ruleContext.ValidationContext.ChainedHeaderToValidate = new ChainedHeader(provenBlockHeader.PosBlockHeader, provenBlockHeader.GetHash(), null); this.checkpoints.Setup(c => c.GetLastCheckpointHeight()).Returns(100); // When we run the validation rule, we should not hit any exceptions as rule will be skipped. Action ruleValidation = () => this.consensusRules.RegisterRule<ProvenHeaderCoinstakeRule>().Run(this.ruleContext); ruleValidation.Should().NotThrow(); } [Fact] public void RunRule_ContextChainedHeaderIsNull_ArgumentNullExceptionIsThrown() { // Setup null chained header. this.ruleContext.ValidationContext.ChainedHeaderToValidate = null; // When we run the validation rule, we should hit null argument exception for chained header. Action ruleValidation = () => this.consensusRules.RegisterRule<ProvenHeaderCoinstakeRule>().Run(this.ruleContext); ruleValidation.Should().Throw<ArgumentNullException>(); } [Fact] public void RunRule_ProvenHeadersActive_And_CoinstakeIsNull_EmptyCoinstakeErrorIsThrown() { // Setup proven header. PosBlock posBlock = new PosBlockBuilder(this.network).Build(); ProvenBlockHeader provenBlockHeader = new ProvenBlockHeaderBuilder(posBlock, this.network).Build(); // Setup chained header and move it to the height higher than proven header activation height. this.ruleContext.ValidationContext.ChainedHeaderToValidate = new ChainedHeader(provenBlockHeader, provenBlockHeader.GetHash(), null); this.ruleContext.ValidationContext.ChainedHeaderToValidate.SetPrivatePropertyValue("Height", this.provenHeadersActivationHeight + 10); (this.ruleContext.ValidationContext.ChainedHeaderToValidate.Header as PosBlockHeader).ProvenBlockHeader.SetPrivateVariableValue<Transaction>("coinstake", null); // When we run the validation rule, we should hit coinstake empty exception. Action ruleValidation = () => this.consensusRules.RegisterRule<ProvenHeaderCoinstakeRule>().Run(this.ruleContext); ruleValidation.Should().Throw<ConsensusErrorException>() .And.ConsensusError .Should().Be(ConsensusErrors.EmptyCoinstake); } [Fact] public void RunRule_ProvenHeadersActive_And_CoinstakeUtxoIsEmpty_ReadTxPrevFailedErrorIsThrown() { // Setup proven header. PosBlock posBlock = new PosBlockBuilder(this.network).Build(); ProvenBlockHeader provenBlockHeader = new ProvenBlockHeaderBuilder(posBlock, this.network).Build(); if (provenBlockHeader.Coinstake is IPosTransactionWithTime posTrx) posTrx.Time = provenBlockHeader.Time; // Setup chained header and move it to the height higher than proven header activation height. this.ruleContext.ValidationContext.ChainedHeaderToValidate = new ChainedHeader(provenBlockHeader, provenBlockHeader.GetHash(), null); this.ruleContext.ValidationContext.ChainedHeaderToValidate.SetPrivatePropertyValue("Height", this.provenHeadersActivationHeight + 10); // By default no utxo are setup in coinview so fetch we return nothing. var res = new FetchCoinsResponse(); res.UnspentOutputs.Add(new OutPoint(posBlock.Transactions[1].Inputs[0].PrevOut), null); this.coinView .Setup(m => m.FetchCoins(It.IsAny<OutPoint[]>())) .Returns(res); // When we run the validation rule, we should hit coinstake read transaction error. Action ruleValidation = () => this.consensusRules.RegisterRule<ProvenHeaderCoinstakeRule>().Run(this.ruleContext); ruleValidation.Should().Throw<ConsensusErrorException>() .And.ConsensusError .Should().Be(ConsensusErrors.ReadTxPrevFailedInsufficient); } [Fact] public void RunRule_ProvenHeadersActive_And_CoinstakeUnspentOutputsIsNull_ReadTxPrevFailedErrorIsThrown() { // Setup proven header. PosBlock posBlock = new PosBlockBuilder(this.network).Build(); ProvenBlockHeader provenBlockHeader = new ProvenBlockHeaderBuilder(posBlock, this.network).Build(); if (provenBlockHeader.Coinstake is IPosTransactionWithTime posTrx) posTrx.Time = provenBlockHeader.Time; // Setup chained header and move it to the height higher than proven header activation height. this.ruleContext.ValidationContext.ChainedHeaderToValidate = new ChainedHeader(provenBlockHeader, provenBlockHeader.GetHash(), null); this.ruleContext.ValidationContext.ChainedHeaderToValidate.SetPrivatePropertyValue("Height", this.provenHeadersActivationHeight + 10); // Add more null unspent output to coinstake. var res = new FetchCoinsResponse(); res.UnspentOutputs.Add(posBlock.Transactions[1].Inputs[0].PrevOut, null); this.coinView .Setup(m => m.FetchCoins(It.IsAny<OutPoint[]>())) .Returns(res); // When we run the validation rule, we should hit coinstake read transaction error. Action ruleValidation = () => this.consensusRules.RegisterRule<ProvenHeaderCoinstakeRule>().Run(this.ruleContext); ruleValidation.Should().Throw<ConsensusErrorException>() .And.ConsensusError .Should().Be(ConsensusErrors.ReadTxPrevFailedInsufficient); } [Fact] public void RunRule_ProvenHeadersActive_And_CoinstakeIsIncorrectlySetup_NonCoinstakeErrorIsThrown() { // Setup proven header. PosBlock posBlock = new PosBlockBuilder(this.network).Build(); ProvenBlockHeader provenBlockHeader = new ProvenBlockHeaderBuilder(posBlock, this.network).Build(); // Setup chained header and move it to the height higher than proven header activation height. this.ruleContext.ValidationContext.ChainedHeaderToValidate = new ChainedHeader(provenBlockHeader, provenBlockHeader.GetHash(), null); this.ruleContext.ValidationContext.ChainedHeaderToValidate.SetPrivatePropertyValue("Height", this.provenHeadersActivationHeight + 10 + this.network.Consensus.LastPOWBlock); // Setup coinstake transaction. var res = new FetchCoinsResponse(); res.UnspentOutputs.Add(new OutPoint(this.network.CreateTransaction(), 0), null); this.coinView .Setup(m => m.FetchCoins(It.IsAny<OutPoint[]>())) .Returns(res); // Change coinstake outputs to make it invalid. ((PosBlockHeader)this.ruleContext.ValidationContext.ChainedHeaderToValidate.Header).ProvenBlockHeader.Coinstake.Outputs.RemoveAt(0); Action ruleValidation = () => this.consensusRules.RegisterRule<ProvenHeaderCoinstakeRule>().Run(this.ruleContext); ruleValidation.Should().Throw<ConsensusErrorException>() .And.ConsensusError .Should().Be(ConsensusErrors.ProofOfWorkTooHigh); } [Fact] public void RunRule_ProvenHeadersActive_And_InvalidStakeTime_StakeTimeViolationErrorIsThrown() { // Setup proven header with valid coinstake. PosBlock posBlock = new PosBlockBuilder(this.network).Build(); ProvenBlockHeader provenBlockHeader = new ProvenBlockHeaderBuilder(posBlock, this.network).Build(); // Setup chained header and move it to the height higher than proven header activation height. this.ruleContext.ValidationContext.ChainedHeaderToValidate = new ChainedHeader(provenBlockHeader, provenBlockHeader.GetHash(), null); this.ruleContext.ValidationContext.ChainedHeaderToValidate.SetPrivatePropertyValue("Height", this.provenHeadersActivationHeight + 10); // Setup coinstake transaction. var res = new FetchCoinsResponse(); res.UnspentOutputs.Add(new OutPoint(this.network.CreateTransaction(), 0), null); this.coinView .Setup(m => m.FetchCoins(It.IsAny<OutPoint[]>())) .Returns(res); // Change coinstake time to differ from header time but divisible by 16. ((PosBlockHeader)this.ruleContext.ValidationContext.ChainedHeaderToValidate.Header).Time = 16; // When we run the validation rule, we should hit coinstake stake time violation error. Action ruleValidation = () => this.consensusRules.RegisterRule<ProvenHeaderCoinstakeRule>().Run(this.ruleContext); ruleValidation.Should().Throw<ConsensusErrorException>() .And.ConsensusError .Should().Be(ConsensusErrors.StakeTimeViolation); // Change coinstake time to be the same as header time but not divisible by 16. this.ruleContext.ValidationContext.ChainedHeaderToValidate.Header.Time = 50; ((PosBlockHeader)this.ruleContext.ValidationContext.ChainedHeaderToValidate.Header).Time = 50; // When we run the validation rule, we should hit coinstake stake time violation error. ruleValidation.Should().Throw<ConsensusErrorException>() .And.ConsensusError .Should().Be(ConsensusErrors.StakeTimeViolation); } [Fact] public void RunRule_ProvenHeadersActive_And_InvalidStakeDepth_StakeDepthErrorIsThrown() { // Setup previous chained header. PosBlock prevPosBlock = new PosBlockBuilder(this.network).Build(); ProvenBlockHeader prevProvenBlockHeader = new ProvenBlockHeaderBuilder(prevPosBlock, this.network).Build(); var previousChainedHeader = new ChainedHeader(prevProvenBlockHeader, prevProvenBlockHeader.GetHash(), null); previousChainedHeader.SetPrivatePropertyValue("Height", this.provenHeadersActivationHeight + 1); // Setup proven header with valid coinstake. PosBlock posBlock = new PosBlockBuilder(this.network).Build(); ProvenBlockHeader provenBlockHeader = new ProvenBlockHeaderBuilder(posBlock, this.network).Build(); provenBlockHeader.PosBlockHeader.HashPrevBlock = prevProvenBlockHeader.GetHash(); if (provenBlockHeader.Coinstake is IPosTransactionWithTime posTrx) posTrx.Time = provenBlockHeader.Time; // Setup chained header and move it to the height higher than proven header activation height. this.ruleContext.ValidationContext.ChainedHeaderToValidate = new ChainedHeader(provenBlockHeader, provenBlockHeader.GetHash(), previousChainedHeader); this.ruleContext.ValidationContext.ChainedHeaderToValidate.SetPrivatePropertyValue("Height", this.provenHeadersActivationHeight + 2); // Ensure that coinview returns a UTXO with valid outputs. var utxoOne = new UnspentOutput(prevPosBlock.Transactions[1].Inputs[0].PrevOut, new Coins((uint)previousChainedHeader.Height, new TxOut(), false, true)); // Setup coinstake transaction with an invalid stake age. var res = new FetchCoinsResponse(); res.UnspentOutputs.Add(utxoOne.OutPoint, utxoOne); this.coinView .Setup(m => m.FetchCoins(It.IsAny<OutPoint[]>())) .Returns(res); // Setup stake validator to fail stake age check. this.stakeValidator .Setup(m => m.IsConfirmedInNPrevBlocks(It.IsAny<UnspentOutput>(), It.IsAny<ChainedHeader>(), It.IsAny<long>())) .Returns(true); // When we run the validation rule, we should hit coinstake depth error. Action ruleValidation = () => this.consensusRules.RegisterRule<ProvenHeaderCoinstakeRule>().Run(this.ruleContext); ruleValidation.Should().Throw<ConsensusErrorException>() .And.ConsensusError .Should().Be(ConsensusErrors.InvalidStakeDepth); } [Fact] public void RunRule_ProvenHeadersActive_And_InvalidCoinstakeSignature_CoinstakeVerifySignatureErrorIsThrown() { // Setup previous chained header. PosBlock prevPosBlock = new PosBlockBuilder(this.network).Build(); ProvenBlockHeader prevProvenBlockHeader = new ProvenBlockHeaderBuilder(prevPosBlock, this.network).Build(); var previousChainedHeader = new ChainedHeader(prevProvenBlockHeader, prevProvenBlockHeader.GetHash(), null); previousChainedHeader.SetPrivatePropertyValue("Height", this.provenHeadersActivationHeight + 1); // Setup proven header with valid coinstake. PosBlock posBlock = new PosBlockBuilder(this.network).Build(); ProvenBlockHeader provenBlockHeader = new ProvenBlockHeaderBuilder(posBlock, this.network).Build(); provenBlockHeader.PosBlockHeader.HashPrevBlock = prevProvenBlockHeader.GetHash(); if (provenBlockHeader.Coinstake is IPosTransactionWithTime posTrx) posTrx.Time = provenBlockHeader.Time; // Setup chained header and move it to the height higher than proven header activation height. this.ruleContext.ValidationContext.ChainedHeaderToValidate = new ChainedHeader(provenBlockHeader, provenBlockHeader.GetHash(), previousChainedHeader); this.ruleContext.ValidationContext.ChainedHeaderToValidate.SetPrivatePropertyValue("Height", this.provenHeadersActivationHeight + 2); // Ensure that coinview returns UTXO with valid outputs. var utxoOneTransaction = this.network.CreateTransaction(); utxoOneTransaction.AddOutput(new TxOut()); var utxoOne = new UnspentOutput(new OutPoint(utxoOneTransaction, 0), new Coins((uint)this.provenHeadersActivationHeight + 10, utxoOneTransaction.Outputs.First(), false)); // Setup coinstake transaction with a valid stake age. var res = new FetchCoinsResponse(); res.UnspentOutputs.Add(utxoOne.OutPoint, utxoOne); this.coinView .Setup(m => m.FetchCoins(It.IsAny<OutPoint[]>())) .Returns(res); // Setup stake validator to fail signature validation. this.stakeValidator .Setup(m => m.VerifySignature(It.IsAny<UnspentOutput>(), It.IsAny<Transaction>(), It.IsAny<int>(), It.IsAny<ScriptVerify>())) .Returns(false); // Setup stake validator to pass stake age check. this.stakeValidator .Setup(m => m.IsConfirmedInNPrevBlocks(It.IsAny<UnspentOutput>(), It.IsAny<ChainedHeader>(), It.IsAny<long>())) .Returns(false); // When we run the validation rule, we should hit coinstake signature verification error. Action ruleValidation = () => this.consensusRules.RegisterRule<ProvenHeaderCoinstakeRule>().Run(this.ruleContext); ruleValidation.Should().Throw<ConsensusErrorException>().And.ConsensusError.Should().Be(ConsensusErrors.CoinstakeVerifySignatureFailed); } [Fact] public void RunRule_ProvenHeadersActive_And_NullPreviousStake_InvalidPreviousProvenHeaderStakeModifierErrorIsThrown() { // Setup previous chained header. PosBlock prevPosBlock = new PosBlockBuilder(this.network).Build(); ProvenBlockHeader prevProvenBlockHeader = new ProvenBlockHeaderBuilder(prevPosBlock, this.network).Build(); prevProvenBlockHeader.StakeModifierV2 = null; // Forcing previous stake modifier to null. var previousChainedHeader = new ChainedHeader(prevProvenBlockHeader, prevProvenBlockHeader.GetHash(), null); previousChainedHeader.SetPrivatePropertyValue("Height", this.provenHeadersActivationHeight + 1); // Setup proven header with valid coinstake. PosBlock posBlock = new PosBlockBuilder(this.network).Build(); ProvenBlockHeader provenBlockHeader = new ProvenBlockHeaderBuilder(posBlock, this.network).Build(); provenBlockHeader.PosBlockHeader.HashPrevBlock = prevProvenBlockHeader.GetHash(); if (provenBlockHeader.Coinstake is IPosTransactionWithTime posTrx) posTrx.Time = provenBlockHeader.Time; // Setup chained header and move it to the height higher than proven header activation height. this.ruleContext.ValidationContext.ChainedHeaderToValidate = new ChainedHeader(provenBlockHeader, provenBlockHeader.GetHash(), previousChainedHeader); this.ruleContext.ValidationContext.ChainedHeaderToValidate.SetPrivatePropertyValue("Height", this.provenHeadersActivationHeight + 2); // Ensure that coinview returns a UTXO with valid outputs. var utxoOneTransaction = this.network.CreateTransaction(); utxoOneTransaction.AddOutput(new TxOut()); var utxoOne = new UnspentOutput(new OutPoint(utxoOneTransaction, 0), new Coins((uint)this.provenHeadersActivationHeight + 10, utxoOneTransaction.Outputs.First(), false)); // Setup coinstake transaction with a valid stake age. var res = new FetchCoinsResponse(); res.UnspentOutputs.Add(utxoOne.OutPoint, utxoOne); this.coinView .Setup(m => m.FetchCoins(It.IsAny<OutPoint[]>())) .Returns(res); // Setup stake validator to pass stake age check. this.stakeValidator .Setup(m => m.IsConfirmedInNPrevBlocks(It.IsAny<UnspentOutput>(), It.IsAny<ChainedHeader>(), It.IsAny<long>())) .Returns(false); // Setup stake validator to pass signature validation. this.stakeValidator .Setup(m => m.VerifySignature(It.IsAny<UnspentOutput>(), It.IsAny<Transaction>(), It.IsAny<int>(), It.IsAny<ScriptVerify>())) .Returns(true); // When we run the validation rule, we should hit previous stake null error. Action ruleValidation = () => this.consensusRules.RegisterRule<ProvenHeaderCoinstakeRule>().Run(this.ruleContext); ruleValidation.Should().Throw<ConsensusErrorException>() .And.ConsensusError .Should().Be(ConsensusErrors.InvalidPreviousProvenHeaderStakeModifier); } [Fact] public void RunRule_ProvenHeadersActive_And_InvalidStakeKernelHash_CoinstakeVerifySignatureErrorIsThrown() { // Setup previous chained header. PosBlock prevPosBlock = new PosBlockBuilder(this.network).Build(); ProvenBlockHeader prevProvenBlockHeader = new ProvenBlockHeaderBuilder(prevPosBlock, this.network).Build(); var previousChainedHeader = new ChainedHeader(prevProvenBlockHeader, prevProvenBlockHeader.GetHash(), null); previousChainedHeader.SetPrivatePropertyValue("Height", this.provenHeadersActivationHeight + 1); // Setup proven header with valid coinstake. PosBlock posBlock = new PosBlockBuilder(this.network).Build(); ProvenBlockHeader provenBlockHeader = new ProvenBlockHeaderBuilder(posBlock, this.network).Build(prevProvenBlockHeader); provenBlockHeader.PosBlockHeader.HashPrevBlock = prevProvenBlockHeader.GetHash(); if (provenBlockHeader.Coinstake is IPosTransactionWithTime posTrx) posTrx.Time = provenBlockHeader.Time; // Setup chained header and move it to the height higher than proven header activation height. this.ruleContext.ValidationContext.ChainedHeaderToValidate = new ChainedHeader(provenBlockHeader, provenBlockHeader.GetHash(), previousChainedHeader); this.ruleContext.ValidationContext.ChainedHeaderToValidate.SetPrivatePropertyValue("Height", this.provenHeadersActivationHeight + 2); // Ensure that coinview returns a UTXO with valid outputs. var utxoOneTransaction = this.network.CreateTransaction(); utxoOneTransaction.AddOutput(new TxOut()); var utxoOne = new UnspentOutput(new OutPoint(utxoOneTransaction, 0), new Coins((uint)this.provenHeadersActivationHeight + 10, utxoOneTransaction.Outputs.First(), false)); // Setup coinstake transaction with a valid stake age. var res = new FetchCoinsResponse(); res.UnspentOutputs.Add(utxoOne.OutPoint, utxoOne); this.coinView .Setup(m => m.FetchCoins(It.IsAny<OutPoint[]>())) .Returns(res); // Setup stake validator to pass stake age check. this.stakeValidator .Setup(m => m.IsConfirmedInNPrevBlocks(It.IsAny<UnspentOutput>(), It.IsAny<ChainedHeader>(), It.IsAny<long>())) .Returns(false); // Setup stake validator to pass signature validation. this.stakeValidator .Setup(m => m.VerifySignature(It.IsAny<UnspentOutput>(), It.IsAny<Transaction>(), It.IsAny<int>(), It.IsAny<ScriptVerify>())) .Returns(true); // Setup stake validator to fail stake kernel hash validation. this.stakeChain.Setup(m => m.Get(It.IsAny<uint256>())).Returns(new BlockStake()); this.stakeValidator .Setup(m => m.CheckStakeKernelHash(It.IsAny<PosRuleContext>(), It.IsAny<uint>(), It.IsAny<uint256>(), It.IsAny<UnspentOutput>(), It.IsAny<OutPoint>(), It.IsAny<uint>())) .Throws(new ConsensusErrorException(ConsensusErrors.StakeHashInvalidTarget)); // When we run the validation rule, we should hit stake hash invalid target error. Action ruleValidation = () => this.consensusRules.RegisterRule<ProvenHeaderCoinstakeRule>().Run(this.ruleContext); ruleValidation.Should().Throw<ConsensusErrorException>() .And.ConsensusError .Should().Be(ConsensusErrors.StakeHashInvalidTarget); } [Fact] [Trait("Unstable", "True")] public void RunRule_ProvenHeadersActive_And_InvalidMerkleProof_BadMerkleProofErrorIsThrown() { // Setup previous chained header. PosBlock prevPosBlock = new PosBlockBuilder(this.network).Build(); ProvenBlockHeader prevProvenBlockHeader = new ProvenBlockHeaderBuilder(prevPosBlock, this.network).Build(); var previousChainedHeader = new ChainedHeader(prevProvenBlockHeader, prevProvenBlockHeader.GetHash(), null); previousChainedHeader.SetPrivatePropertyValue("Height", this.provenHeadersActivationHeight + 1); // Setup proven header with valid coinstake. PosBlock posBlock = new PosBlockBuilder(this.network).Build(); ProvenBlockHeader provenBlockHeader = new ProvenBlockHeaderBuilder(posBlock, this.network).Build(prevProvenBlockHeader); provenBlockHeader.PosBlockHeader.HashPrevBlock = prevProvenBlockHeader.GetHash(); if (provenBlockHeader.Coinstake is IPosTransactionWithTime posTrx) posTrx.Time = provenBlockHeader.Time; // Corrupt merkle proof. provenBlockHeader.SetPrivateVariableValue("merkleProof", new PartialMerkleTree(new[] { new uint256(1234) }, new[] { false })); // Setup chained header and move it to the height higher than proven header activation height. this.ruleContext.ValidationContext.ChainedHeaderToValidate = new ChainedHeader(provenBlockHeader, provenBlockHeader.GetHash(), previousChainedHeader); this.ruleContext.ValidationContext.ChainedHeaderToValidate.SetPrivatePropertyValue("Height", this.provenHeadersActivationHeight + 2); // Ensure that coinview returns a UTXO with valid outputs. var utxoOne = new UnspentOutput(prevPosBlock.Transactions[1].Inputs[0].PrevOut, new Coins((uint)previousChainedHeader.Height, new TxOut(), false, true)); // Setup coinstake transaction with a valid stake age. var res = new FetchCoinsResponse(); res.UnspentOutputs.Add(utxoOne.OutPoint, utxoOne); this.coinView .Setup(m => m.FetchCoins(It.IsAny<OutPoint[]>())) .Returns(res); // Setup stake validator to pass stake age check. this.stakeValidator .Setup(m => m.IsConfirmedInNPrevBlocks(It.IsAny<UnspentOutput>(), It.IsAny<ChainedHeader>(), It.IsAny<long>())) .Returns(false); // Setup stake validator to pass signature validation. this.stakeValidator .Setup(m => m.VerifySignature(It.IsAny<UnspentOutput>(), It.IsAny<Transaction>(), It.IsAny<int>(), It.IsAny<ScriptVerify>())) .Returns(true); // Setup stake validator to pass stake kernel hash validation. this.stakeChain.Setup(m => m.Get(It.IsAny<uint256>())).Returns(new BlockStake()); this.stakeValidator .Setup(m => m.CheckStakeKernelHash(It.IsAny<PosRuleContext>(), It.IsAny<uint>(), It.IsAny<uint256>(), It.IsAny<UnspentOutput>(), It.IsAny<OutPoint>(), It.IsAny<uint>())).Returns(true); // When we run the validation rule, we should hit bad merkle proof error. Action ruleValidation = () => this.consensusRules.RegisterRule<ProvenHeaderCoinstakeRule>().Run(this.ruleContext); ruleValidation.Should().Throw<ConsensusErrorException>() .And.ConsensusError .Should().Be(ConsensusErrors.BadMerkleRoot); } [Fact] public void RunRule_ProvenHeadersActive_And_InvalidCoinstakeKernelSignature_BadBlockSignatureErrorIsThrown() { // Setup private key. var mnemonic = new Mnemonic(Wordlist.English, WordCount.Twelve); Key privateKey = mnemonic.DeriveExtKey().PrivateKey; // Setup previous chained header. PosBlock prevPosBlock = new PosBlockBuilder(this.network, privateKey).Build(); ProvenBlockHeader prevProvenBlockHeader = new ProvenBlockHeaderBuilder(prevPosBlock, this.network).Build(); var previousChainedHeader = new ChainedHeader(prevProvenBlockHeader, prevProvenBlockHeader.GetHash(), null); previousChainedHeader.SetPrivatePropertyValue("Height", this.provenHeadersActivationHeight + 1); // Setup proven header with valid coinstake. PosBlock posBlock = new PosBlockBuilder(this.network, privateKey).Build(); posBlock.UpdateMerkleRoot(); ProvenBlockHeader provenBlockHeader = new ProvenBlockHeaderBuilder(posBlock, this.network).Build(prevProvenBlockHeader); provenBlockHeader.PosBlockHeader.HashPrevBlock = prevProvenBlockHeader.GetHash(); if (provenBlockHeader.Coinstake is IPosTransactionWithTime posTrx) posTrx.Time = provenBlockHeader.Time; // Set invalid coinstake script pub key. provenBlockHeader.Coinstake.Outputs[1].ScriptPubKey = new Script("03cdac179a3391d96cf4957fa0255e4aa8055a993e92df7146e740117885b184ea OP_CHECKSIG"); // Setup chained header and move it to the height higher than proven header activation height. this.ruleContext.ValidationContext.ChainedHeaderToValidate = new ChainedHeader(provenBlockHeader, provenBlockHeader.GetHash(), previousChainedHeader); this.ruleContext.ValidationContext.ChainedHeaderToValidate.SetPrivatePropertyValue("Height", this.provenHeadersActivationHeight + 2); // Setup coinstake transaction with a valid stake age. uint unspentOutputsHeight = (uint)this.provenHeadersActivationHeight + 10; var res = new FetchCoinsResponse(); var unspentOutputs = new UnspentOutput(prevPosBlock.Transactions[1].Inputs[0].PrevOut, new Coins(unspentOutputsHeight, new TxOut(new Money(100), privateKey.PubKey), false)); res.UnspentOutputs.Add(unspentOutputs.OutPoint, unspentOutputs); this.coinView .Setup(m => m.FetchCoins(It.IsAny<OutPoint[]>())) .Returns(res); // Setup stake validator to pass signature validation. this.stakeValidator .Setup(m => m.VerifySignature(It.IsAny<UnspentOutput>(), It.IsAny<Transaction>(), It.IsAny<int>(), It.IsAny<ScriptVerify>())) .Returns(true); // Setup stake validator to pass stake kernel hash validation. this.stakeChain.Setup(m => m.Get(It.IsAny<uint256>())).Returns(new BlockStake()); this.stakeValidator .Setup(m => m.CheckStakeKernelHash(It.IsAny<PosRuleContext>(), It.IsAny<uint>(), It.IsAny<uint256>(), It.IsAny<UnspentOutput>(), It.IsAny<OutPoint>(), It.IsAny<uint>())).Returns(true); // Setup stake validator to pass stake age check. this.stakeValidator .Setup(m => m.IsConfirmedInNPrevBlocks(It.IsAny<UnspentOutput>(), It.IsAny<ChainedHeader>(), It.IsAny<long>())) .Returns(false); // When we run the validation rule, we should hit bad merkle proof error. Action ruleValidation = () => this.consensusRules.RegisterRule<ProvenHeaderCoinstakeRule>().Run(this.ruleContext); ruleValidation.Should().Throw<ConsensusErrorException>() .And.ConsensusError .Should().Be(ConsensusErrors.BadBlockSignature); } [Fact] public void RunRule_ProvenHeadersActive_And_ValidProvenHeader_NoErrorsAreThrown() { // Setup private key. var mnemonic = new Mnemonic(Wordlist.English, WordCount.Twelve); Key privateKey = mnemonic.DeriveExtKey().PrivateKey; // Setup previous chained header. PosBlock prevPosBlock = new PosBlockBuilder(this.network, privateKey).Build(); ProvenBlockHeader prevProvenBlockHeader = new ProvenBlockHeaderBuilder(prevPosBlock, this.network).Build(); var previousChainedHeader = new ChainedHeader(prevProvenBlockHeader, prevProvenBlockHeader.GetHash(), null); previousChainedHeader.SetPrivatePropertyValue("Height", this.provenHeadersActivationHeight + 1); // Setup proven header with valid coinstake. PosBlock posBlock = new PosBlockBuilder(this.network, privateKey).Build(); posBlock.UpdateMerkleRoot(); posBlock.Header.HashPrevBlock = prevProvenBlockHeader.GetHash(); posBlock.Header.Bits = 16777216; // Update signature. ECDSASignature signature = privateKey.Sign(posBlock.Header.GetHash()); posBlock.BlockSignature = new BlockSignature { Signature = signature.ToDER() }; ProvenBlockHeader provenBlockHeader = new ProvenBlockHeaderBuilder(posBlock, this.network).Build(prevProvenBlockHeader); provenBlockHeader.PosBlockHeader.HashPrevBlock = prevProvenBlockHeader.GetHash(); if (provenBlockHeader.Coinstake is IPosTransactionWithTime posTrx) posTrx.Time = provenBlockHeader.Time; // Set invalid coinstake script pub key provenBlockHeader.Coinstake.Outputs[1].ScriptPubKey = privateKey.PubKey.ScriptPubKey; // Setup chained header and move it to the height higher than proven header activation height. this.ruleContext.ValidationContext.ChainedHeaderToValidate = new ChainedHeader(provenBlockHeader, provenBlockHeader.GetHash(), previousChainedHeader); this.ruleContext.ValidationContext.ChainedHeaderToValidate.SetPrivatePropertyValue("Height", this.provenHeadersActivationHeight + 2); // Setup coinstake transaction with a valid stake age. uint unspentOutputsHeight = (uint)this.provenHeadersActivationHeight + 10; var res = new FetchCoinsResponse(); var unspentOutputs = new UnspentOutput(prevPosBlock.Transactions[1].Inputs[0].PrevOut, new Coins(unspentOutputsHeight, new TxOut(new Money(100), privateKey.PubKey), false)); res.UnspentOutputs.Add(unspentOutputs.OutPoint, unspentOutputs); this.coinView .Setup(m => m.FetchCoins(It.IsAny<OutPoint[]>())) .Returns(res); // Setup stake validator to pass stake age check. this.stakeValidator .Setup(m => m.IsConfirmedInNPrevBlocks(It.IsAny<UnspentOutput>(), It.IsAny<ChainedHeader>(), It.IsAny<long>())) .Returns(false); // Setup stake validator to pass signature validation. this.stakeValidator .Setup(m => m.VerifySignature(It.IsAny<UnspentOutput>(), It.IsAny<Transaction>(), It.IsAny<int>(), It.IsAny<ScriptVerify>())) .Returns(true); // Setup stake validator to pass stake kernel hash validation. this.stakeChain.Setup(m => m.Get(It.IsAny<uint256>())).Returns(new BlockStake()); this.stakeValidator .Setup(m => m.CheckStakeKernelHash(It.IsAny<PosRuleContext>(), It.IsAny<uint>(), It.IsAny<uint256>(), It.IsAny<UnspentOutput>(), It.IsAny<OutPoint>(), It.IsAny<uint>())).Returns(true); // When we run the validation rule, we should not hit any errors. Action ruleValidation = () => this.consensusRules.RegisterRule<ProvenHeaderCoinstakeRule>().Run(this.ruleContext); ruleValidation.Should().NotThrow(); } } }
60.194872
200
0.684671
[ "MIT" ]
Botcoin-Abacus/blockcore
src/Tests/Blockcore.Features.Consensus.Tests/Rules/ProvenHeaderRules/ProvenBlockHeaderCoinstakeRuleTest.cs
35,216
C#
// Copyright (c) .NET Foundation and Contributors (https://dotnetfoundation.org) // Copyright (c) 2018-2021 Stride and its contributors (https://stride3d.net) // Copyright (c) 2011-2018 Silicon Studio Corp. (https://www.siliconstudio.co.jp) // See the LICENSE.md file in the project root for full license information. #if DEBUG using System; using System.ComponentModel; using Stride.Core.Annotations; using System.Collections.Generic; using Stride.Core.Assets; using Stride.Core; using Stride.Core.IO; using Stride.Core.Mathematics; using Stride.Rendering; namespace Stride.Assets.Presentation.Test { public enum TestEnum { FirstValue, SecondValue, ThirdValue, FourthValue } [Flags] public enum TestFlagEnum { ZeroFlag = 0, FirstFlag = 1, SecondFlag = 2, ThirdFlag = 4, FourthFlag = 8, SecondAndThirdFlags = SecondFlag | ThirdFlag, } [DataContract("TestStruct")] public struct TestStruct { public int Integer { get; set; } public float Float { get; set; } public string String { get; set; } } [DataContract("TestClass")] public class TestClass { public float Float { get; set; } public string String { get; set; } } [DataContract("TestEnabledClass")] public class TestEnabledClass { public bool Enabled { get; set; } public float Float { get; set; } public string String { get; set; } } [DataContract("TestAbstractClass")] public abstract class TestAbstractClass { public int DefaultInt { get; set; } } [DataContract("TestImplemClass1")] public class TestImplemClass1 : TestAbstractClass { public string String1 { get; set; } } [DataContract("TestImplemClass2")] public class TestImplemClass2 : TestAbstractClass { public string String2 { get; set; } } [DataContract("TestImplemClassEnabled")] public class TestImplemClassEnabled : TestAbstractClass { public bool Enabled { get; set; } } [DataContract("TestInlinedAbstractClass")] [InlineProperty] public abstract class TestInlinedAbstractClass { public int DefaultInt { get; set; } } [DataContract("TestInlinedImplemClass1")] public class TestInlinedImplemClass1 : TestInlinedAbstractClass { [InlineProperty] public Vector2 Vector { get; set; } } [DataContract("TestInlinedImplemClass2")] public class TestInlinedImplemClass2 : TestInlinedAbstractClass { [InlineProperty] public Vector3 Vector { get; set; } } [DataContract("TestMissingInlinedProperty")] public class TestMissingInlinedProperty : TestInlinedAbstractClass { public Vector3 Vector { get; set; } } [DataContract("TestAsset")] [AssetDescription(FileExtension)] [Display("Test Asset")] [CategoryOrder(1, "Primitive types")] [CategoryOrder(2, "Vector types")] [CategoryOrder(3, "Class & Struct types")] [CategoryOrder(4, "Instanciable types")] [CategoryOrder(5, "Collections")] [CategoryOrder(6, "Categories")] public sealed class TestAsset : Asset { public const string FileExtension = ".sdtest"; [DataMember(10)] [Display("String", "Primitive types")] public string String { get; set; } [DataMember(20)] [Display("Float", "Primitive types")] public float Size { get; set; } [DataMember(22)] [DataMemberRange(200, 2000, 10, 100, 2)] [Display("Constrained Float", "Primitive types")] public float ConstrainedFloat { get; set; } [DataMember(23)] [Display("Byte", "Primitive types")] public byte Byte { get; set; } [DataMember(25)] [Display("Boolean", "Primitive types")] public bool Boolean { get; set; } [DataMember(27)] [Display("Unsigned Short", "Primitive types")] public ushort UnsignedShort { get; set; } [DataMember(28)] [Display("TimeSpan", "Primitive types")] public TimeSpan TimeSpan { get; set; } [DataMember(30)] [Display("Enum", "Primitive types")] public TestEnum Enum { get; set; } [DataMember(31)] [Display("FlagEnum", "Primitive types")] public TestFlagEnum FlagEnum { get; set; } [DataMember(40)] [Display("Character", "Primitive types")] public char Character { get; set; } [DataMember(41)] [Display("FilePath", "Primitive types")] public UFile FilePath { get; set; } = new UFile(""); [DataMember(41)] [Display("DirectoryPath", "Primitive types")] public UDirectory DirectoryPath { get; set; } = new UDirectory(""); [DataMember(42)] [Display("Color", "Vector types")] public Color Color { get; set; } = new Color(0, 255, 255, 255); [DataMember(43)] [Display("Color3", "Vector types")] public Color3 Color3 { get; set; } = new Color3(1.0f, 1.0f, 0.0f); [DataMember(44)] [Display("Color4", "Vector types")] public Color4 Color4 { get; set; } = new Color4(1.0f, 0.0f, 1.0f, 1.0f); [DataMember(45)] [Display("Vector2", "Vector types")] public Vector2 Vector2 { get; set; } [DataMember(46)] [Display("Vector3", "Vector types")] public Vector3 Vector3 { get; set; } [DataMember(47)] [Display("Vector4", "Vector types")] public Vector4 Vector4 { get; set; } [DataMember(48)] [Display("Int2", "Int types")] public Int2 Int2 { get; set; } [DataMember(49)] [Display("Int3", "Int types")] public Int3 Int3 { get; set; } [DataMember(50)] [Display("Int4", "Int types")] public Int4 Int4 { get; set; } [DataMember(51)] [Display("RectangleF", "Vector types")] public RectangleF RectangleF { get; set; } [DataMember(52)] [Display("Rectangle", "Vector types")] public Rectangle Rectangle { get; set; } [DataMember(53)] [Display("Angle", "Vector types")] public AngleSingle Angle { get; set; } [DataMember(54)] [Display("Rotation", "Vector types")] public Quaternion Rotation { get; set; } [DataMember(55)] [Display("Matrix", "Vector types")] public Matrix Matrix { get; set; } // TODO: Add ImageEnum and ImageFlagEnum [DataMember(56)] [Display("Nullable Enum", "Class & Struct types")] public TestEnum? NullableEnum { get; set; } [DataMember(57)] [Display("Nullable Rectangle", "Class & Struct types")] public Rectangle? NullableRectangle { get; set; } [DataMember(60)] [Display("Structure", "Class & Struct types")] public TestStruct Structure { get; set; } [DataMember(70)] [Display("Class", "Class & Struct types")] public TestClass Class { get; set; } = new TestClass(); [DataMember(80)] [Display("Enabled Class", "Class & Struct types")] public TestEnabledClass EnabledClass { get; set; } = new TestEnabledClass(); [DataMember(100)] [Display("Abstract Class", "Instanciable types")] public TestAbstractClass AbstractClass { get; set; } [DataMember(110)] [Display("Inlined Abstract Class", "Instanciable types")] public TestInlinedAbstractClass InlinedAbstractClass { get; set; } [DataMember(120)] [Display("ReadOnly Abstract Class", "Instanciable types")] public TestAbstractClass ReadOnlyAbstractClass { get; } = new TestImplemClass1 { DefaultInt = 5, String1 = "TestImplem1" }; [DataMember(130)] [Display("ReadOnly Abstract Class (Null)", "Instanciable types")] public TestAbstractClass ReadOnlyAbstractClassNull { get; } = null; [DataMember(140)] [Display("Inlined ReadOnly Abstract Class", "Instanciable types")] public TestInlinedAbstractClass ReadOnlyInlinedAbstractClass { get; } = new TestInlinedImplemClass1 { DefaultInt = 5, Vector = Vector2.One }; [DataMember(150)] [Display("Inlined ReadOnly Abstract Class (Null)", "Instanciable types")] public TestInlinedAbstractClass ReadOnlyInlinedAbstractClassNull { get; } = null; [DataMember(200)] [Display("Integer List", "Collections")] public List<int> IntegerList { get; } = new List<int>(); [DataMember(210)] [Display("Structure List", "Collections")] public List<TestStruct> StructureList { get; set; } = new List<TestStruct>(); [DataMember(220)] [Display("Vector List", "Collections")] public List<Vector3> VectorList { get; set; } = new List<Vector3>(); [DataMember(230)] [Display("Class List", "Collections")] public List<TestClass> ClassList { get; set; } = new List<TestClass>(); [DataMember(240)] [Display("Abstract List", "Collections")] public List<TestAbstractClass> AbstractList { get; set; } = new List<TestAbstractClass>(); //[DataMember(250)] //[Display("List of Integer Lists", "Collections")] //public List<List<int>> ListOfListsInt { get; set; } = new List<List<int>>(); //[DataMember(260)] //[Display("List of Struct Lists", "Collections")] //public List<List<TestStruct>> ListOfListsStruct { get; set; } = new List<List<TestStruct>>(); //[DataMember(270)] //[Display("List of Class Lists", "Collections")] //public List<List<TestClass>> ListOfListsClass { get; set; } = new List<List<TestClass>>(); [DataMember(275)] [MemberCollection(ReadOnly = true)] [Display("ReadOnly Abstract List", "Collections")] public List<TestAbstractClass> ReadOnlyAbstractList { get; private set; } = new List<TestAbstractClass> { new TestImplemClass1 { String1 = "Item1", DefaultInt = 1 }, new TestImplemClass2 { String2 = "Item2", DefaultInt = 2 }, new TestImplemClassEnabled { DefaultInt = 3, Enabled = true } }; [DataMember(280)] [Display("Integer Dictionary", "Collections")] public Dictionary<string, int> IntegerDictionary { get; set; } = new Dictionary<string, int>(); [DataMember(290)] [Display("Class Dictionary", "Collections")] public Dictionary<string, TestClass> ClassDictionary { get; set; } = new Dictionary<string, TestClass>(); [DataMember(300)] [Display("Abstract Dictionary", "Collections")] public Dictionary<string, TestAbstractClass> AbstractDictionary { get; set; } = new Dictionary<string, TestAbstractClass>(); [Display("Category", "Categories")] [Category] public TestClass CategoryClass { get; set; } = new TestClass(); [Display("Enabled Category", "Categories")] [Category] public TestEnabledClass EnabledCategory { get; set; } = new TestEnabledClass(); //[DataMember(800)] //public PropertyKey PropertyKey { get; set; } [DataMember(850)] public ParameterKey ParameterKey { get; set; } public static TestAsset CreateNew() { var testAsset = new TestAsset { String = "The name", Enum = TestEnum.ThirdValue, Character = 'f', Size = 16.5f, IntegerList = { 4, 6, 8 }, Structure = new TestStruct { Float = 1.0f, Integer = 2, String = "Inner string" }, StructureList = { new TestStruct { Float = 2.0f, Integer = 1, String = "Inner string1" }, new TestStruct { Float = 4.0f, Integer = 3, String = "Inner string2" }, new TestStruct { Float = 8.0f, Integer = 6, String = "Inner string3" }, }, Class = new TestClass { Float = 8.0f, String = "Inner class string" }, ClassList = { new TestClass { Float = 18.0f, String = "Inner class string1" }, new TestClass { Float = 28.0f, String = "Inner class string2" }, new TestClass { Float = 38.0f, String = "Inner class string3" }, }, ClassDictionary = { { "First", new TestClass { Float = 21.0f, String = "Inner class string1" } }, { "Second", new TestClass { Float = 31.0f, String = "Inner class string2" } }, { "Third", new TestClass { Float = 41.0f, String = "Inner class string3" } }, }, //ListOfListsInt = //{ // new List<int> { 2, 4 }, // new List<int> { 6, 8 } //}, //ListOfListsStruct = //{ // new List<TestStruct> { new TestStruct() }, // new List<TestStruct> { new TestStruct() } //}, //ListOfListsClass = //{ // new List<TestClass> { new TestClass() }, // new List<TestClass> { new TestClass() } //} }; return testAsset; } } } #endif
34.022613
149
0.579056
[ "MIT" ]
Ethereal77/stride
sources/editor/Stride.Assets.Presentation/Test/TestAsset.cs
13,541
C#
using System; namespace OpenSatelliteProject.GRB.Product { public class ImageSize { public int Width { get; set; } public int Height { get; set; } public ImageSize (int width, int height) { Width = width; Height = height; } public static ImageSize New(int width, int height) { return new ImageSize(width, height); } } }
21.947368
60
0.563549
[ "MIT" ]
opensatelliteproject/grbdump
GRB/Product/ImageSize.cs
419
C#
using System.Web; using System.Web.Optimization; namespace TestandoF { public class BundleConfig { // Para obter mais informações sobre o agrupamento, visite https://go.microsoft.com/fwlink/?LinkId=301862 public static void RegisterBundles(BundleCollection bundles) { bundles.Add(new ScriptBundle("~/bundles/jquery").Include( "~/Scripts/jquery-{version}.js")); bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include( "~/Scripts/jquery.validate*")); // Use a versão em desenvolvimento do Modernizr para desenvolver e aprender. Em seguida, quando estiver // pronto para a produção, utilize a ferramenta de build em https://modernizr.com para escolher somente os testes que precisa. bundles.Add(new ScriptBundle("~/bundles/modernizr").Include( "~/Scripts/modernizr-*")); bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include( "~/Scripts/bootstrap.js")); bundles.Add(new StyleBundle("~/Content/css").Include( "~/Content/bootstrap.css", "~/Content/site.css")); } } }
40.16129
138
0.596787
[ "MIT" ]
LuisFelipeagarcia/testeFork
TestandoF/TestandoF/App_Start/BundleConfig.cs
1,252
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text.Json; using System.Text.Json.Serialization; using BAMCIS.GeoJSON; using Inforit.GeoJson.Converters.Extensions; namespace Inforit.GeoJson.Converters { /// <summary> /// Used to serialize and deserialize LineString objects /// </summary> public class LineStringConverter : JsonConverter<LineString> { /// <inheritdoc /> public override bool CanConvert(Type typeToConvert) { return typeToConvert == typeof(LineString); } /// <inheritdoc /> public override LineString Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { var polygonPositions = new List<Position>(); // Read the JSON document using var jsonDocument = JsonDocument.ParseValue(ref reader); var jsonElement = jsonDocument.RootElement; // JsonElement TryGetProperty or GetProperty methods are case sensitive var coordinatesProperty = jsonElement .EnumerateObject() .First(p => string.Equals(p.Name, "coordinates", StringComparison.OrdinalIgnoreCase)); var coordinates = coordinatesProperty.Value.EnumerateArray(); while (coordinates.MoveNext()) { var coordinate = coordinates.Current.EnumerateArray(); polygonPositions.Add(new Position(coordinate.First().GetDouble(), coordinate.Last().GetDouble())); } // Take this array of arrays of arrays and create linear rings // and use those to create create polygons return new LineString(polygonPositions); } /// <inheritdoc /> public override void Write(Utf8JsonWriter writer, LineString value, JsonSerializerOptions options) { var lineString = value; writer.WriteStartObject(); writer.WritePropertyName(nameof(lineString.Type)); writer.WriteStringValue(lineString.Type.ToString()); writer.WriteStartArray(nameof(lineString.Coordinates)); foreach (var position in lineString.Coordinates) { writer.WritePosition(position); } writer.WriteEndArray(); writer.WriteEndObject(); } } }
34.930556
125
0.602386
[ "MIT" ]
Inforitnl/GeoJson.Converters
Inforit.GeoJson.Converters/Converters/LineStringConverter.cs
2,515
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the personalize-runtime-2018-05-22.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Xml.Serialization; using Amazon.PersonalizeRuntime.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.PersonalizeRuntime.Model.Internal.MarshallTransformations { /// <summary> /// GetRecommendations Request Marshaller /// </summary> public class GetRecommendationsRequestMarshaller : IMarshaller<IRequest, GetRecommendationsRequest> , IMarshaller<IRequest,AmazonWebServiceRequest> { /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="input"></param> /// <returns></returns> public IRequest Marshall(AmazonWebServiceRequest input) { return this.Marshall((GetRecommendationsRequest)input); } /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(GetRecommendationsRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.PersonalizeRuntime"); request.Headers["Content-Type"] = "application/json"; request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2018-05-22"; request.HttpMethod = "POST"; request.ResourcePath = "/recommendations"; request.MarshallerVersion = 2; using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture)) { JsonWriter writer = new JsonWriter(stringWriter); writer.WriteObjectStart(); var context = new JsonMarshallerContext(request, writer); if(publicRequest.IsSetCampaignArn()) { context.Writer.WritePropertyName("campaignArn"); context.Writer.Write(publicRequest.CampaignArn); } if(publicRequest.IsSetContext()) { context.Writer.WritePropertyName("context"); context.Writer.WriteObjectStart(); foreach (var publicRequestContextKvp in publicRequest.Context) { context.Writer.WritePropertyName(publicRequestContextKvp.Key); var publicRequestContextValue = publicRequestContextKvp.Value; context.Writer.Write(publicRequestContextValue); } context.Writer.WriteObjectEnd(); } if(publicRequest.IsSetFilterArn()) { context.Writer.WritePropertyName("filterArn"); context.Writer.Write(publicRequest.FilterArn); } if(publicRequest.IsSetItemId()) { context.Writer.WritePropertyName("itemId"); context.Writer.Write(publicRequest.ItemId); } if(publicRequest.IsSetNumResults()) { context.Writer.WritePropertyName("numResults"); context.Writer.Write(publicRequest.NumResults); } if(publicRequest.IsSetUserId()) { context.Writer.WritePropertyName("userId"); context.Writer.Write(publicRequest.UserId); } writer.WriteObjectEnd(); string snippet = stringWriter.ToString(); request.Content = System.Text.Encoding.UTF8.GetBytes(snippet); } return request; } private static GetRecommendationsRequestMarshaller _instance = new GetRecommendationsRequestMarshaller(); internal static GetRecommendationsRequestMarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static GetRecommendationsRequestMarshaller Instance { get { return _instance; } } } }
36.553191
151
0.596236
[ "Apache-2.0" ]
Singh400/aws-sdk-net
sdk/src/Services/PersonalizeRuntime/Generated/Model/Internal/MarshallTransformations/GetRecommendationsRequestMarshaller.cs
5,154
C#
using Microsoft.AspNetCore.Mvc; using NJsonSchema.Annotations; namespace Tzkt.Api { [ModelBinder(BinderType = typeof(BakingRightTypeBinder))] [JsonSchemaExtensionData("x-tzkt-extension", "query-parameter")] [JsonSchemaExtensionData("x-tzkt-query-parameter", "baking,endorsing")] public class BakingRightTypeParameter { /// <summary> /// **Equal** filter mode (optional, i.e. `param.eq=123` is the same as `param=123`). \ /// Specify baking right type to get items where the specified field is equal to the specified value. /// /// Example: `?type=baking`. /// </summary> [JsonSchemaType(typeof(string))] public int? Eq { get; set; } /// <summary> /// **Not equal** filter mode. \ /// Specify baking right type to get items where the specified field is not equal to the specified value. /// /// Example: `?type.ne=endorsing`. /// </summary> [JsonSchemaType(typeof(string))] public int? Ne { get; set; } } }
35.433333
113
0.610536
[ "MIT" ]
baking-bad/tezzycat
Tzkt.Api/Parameters/BakingRightTypeParameter.cs
1,065
C#
using LinqAF.Impl; namespace LinqAF { public partial struct SkipLastEnumerable<TItem, TInnerEnumerable, TInnerEnumerator> { public SkipLastEnumerable<TItem, TInnerEnumerable, TInnerEnumerator> SkipLast(int count) { if (IsDefaultValue()) throw CommonImplementation.Uninitialized("source"); if(count < 0) { count = 0; } var newCount = this.InnerCount + count; return new SkipLastEnumerable<TItem, TInnerEnumerable, TInnerEnumerator>(ref Inner, newCount); } } }
26.727273
106
0.620748
[ "Apache-2.0" ]
kevin-montrose/LinqAF
LinqAF/Overrides/SkipLast.cs
590
C#
using System.Collections.Immutable; using System.Globalization; using System.Text.RegularExpressions; using Microsoft.Recognizers.Definitions; using Microsoft.Recognizers.Definitions.Hindi; namespace Microsoft.Recognizers.Text.NumberWithUnit.Hindi { public class TemperatureExtractorConfiguration : HindiNumberWithUnitExtractorConfiguration { public static readonly ImmutableDictionary<string, string> TemperatureSuffixList = NumbersWithUnitDefinitions.TemperatureSuffixList.ToImmutableDictionary(); private const RegexOptions RegexFlags = RegexOptions.Compiled | RegexOptions.Singleline | RegexOptions.ExplicitCapture; private static readonly ImmutableList<string> AmbiguousValues = NumbersWithUnitDefinitions.AmbiguousTemperatureUnitList.ToImmutableList(); private static readonly Regex AmbiguousUnitMultiplierRegex = RegexCache.Get(BaseUnits.AmbiguousUnitNumberMultiplierRegex, RegexFlags); public TemperatureExtractorConfiguration() : this(new CultureInfo(Culture.Hindi)) { } public TemperatureExtractorConfiguration(CultureInfo ci) : base(ci) { } public override ImmutableDictionary<string, string> SuffixList => TemperatureSuffixList; public override ImmutableDictionary<string, string> PrefixList => null; public override ImmutableList<string> AmbiguousUnitList => AmbiguousValues; public override string ExtractType => Constants.SYS_UNIT_TEMPERATURE; public override Regex AmbiguousUnitNumberMultiplierRegex => AmbiguousUnitMultiplierRegex; } }
38.674419
127
0.755863
[ "MIT" ]
theolivenbaum/Recognizers-Text
.NET/Microsoft.Recognizers.Text.NumberWithUnit/Hindi/Extractors/TemperatureExtractorConfiguration.cs
1,665
C#
using System.Runtime.Serialization; using SharpRemote.Test.Types.Enums; namespace SharpRemote.Test.Types.Structs { [DataContract] public struct FieldSbyteEnum { [DataMember] public SbyteEnum Value; } }
19
40
0.789474
[ "MIT" ]
JTOne123/SharpRemote
SharpRemote.Test/Types/Structs/FieldSbyteEnum.cs
211
C#
/* * Copyright (c) 2018 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ namespace TencentCloud.Vod.V20180717.Models { using Newtonsoft.Json; using System.Collections.Generic; using TencentCloud.Common; public class AiRecognitionTaskOcrWordsSegmentItem : AbstractModel { /// <summary> /// Start time offset of recognized segment in seconds. /// </summary> [JsonProperty("StartTimeOffset")] public float? StartTimeOffset{ get; set; } /// <summary> /// End time offset of recognition segment in seconds. /// </summary> [JsonProperty("EndTimeOffset")] public float? EndTimeOffset{ get; set; } /// <summary> /// Confidence of recognized segment. Value range: 0-100. /// </summary> [JsonProperty("Confidence")] public float? Confidence{ get; set; } /// <summary> /// Zone coordinates of recognition result. The array contains four elements: [x1,y1,x2,y2], i.e., the horizontal and vertical coordinates of the top-left and bottom-right corners. /// </summary> [JsonProperty("AreaCoordSet")] public long?[] AreaCoordSet{ get; set; } /// <summary> /// For internal usage only. DO NOT USE IT. /// </summary> public override void ToMap(Dictionary<string, string> map, string prefix) { this.SetParamSimple(map, prefix + "StartTimeOffset", this.StartTimeOffset); this.SetParamSimple(map, prefix + "EndTimeOffset", this.EndTimeOffset); this.SetParamSimple(map, prefix + "Confidence", this.Confidence); this.SetParamArraySimple(map, prefix + "AreaCoordSet.", this.AreaCoordSet); } } }
36.046154
188
0.647461
[ "Apache-2.0" ]
TencentCloud/tencentcloud-sdk-dotnet-intl-en
TencentCloud/Vod/V20180717/Models/AiRecognitionTaskOcrWordsSegmentItem.cs
2,343
C#
// Copyright 2004-2017 The Poderosa Project. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Text; using System.Windows.Forms; using Poderosa.Plugins; namespace Poderosa.Forms { internal partial class ExtensionPointList : Form { public ExtensionPointList() { InitializeComponent(); InitText(); FillList(); } private void InitText() { StringResource sr = CoreUtil.Strings; this.Text = sr.GetString("Form.ExtensionPointList.Text"); _idHeader.Text = "ID"; _ownerHeader.Text = sr.GetString("Form.ExtensionPointList._ownerHeader"); _countHeader.Text = sr.GetString("Form.ExtensionPointList._countHeader"); _okButton.Text = sr.GetString("Common.OK"); _cancelButton.Text = sr.GetString("Common.Cancel"); } private void FillList() { _list.BeginUpdate(); IPluginInspector pi = (IPluginInspector)WindowManagerPlugin.Instance.PoderosaWorld.PluginManager.GetAdapter(typeof(IPluginInspector)); foreach (IExtensionPoint pt in pi.ExtensionPoints) { ListViewItem li = new ListViewItem(pt.ID); li.SubItems.Add(pt.OwnerPlugin == null ? "" : pi.GetPluginInfo(pt.OwnerPlugin).PluginInfoAttribute.ID); //Rootではオーナなし li.SubItems.Add(pt.GetExtensions().Length.ToString()); _list.Items.Add(li); } _list.EndUpdate(); } } }
39.351852
146
0.663529
[ "Apache-2.0" ]
dnobori/poderosa
Core/ExtensionPointList.cs
2,141
C#
using System; using System.Threading; using System.Threading.Tasks; using ZendeskApi.Client.Models; using ZendeskApi.Client.Responses; namespace ZendeskApi.Client.Resources { public interface IDeletedUsersResource { #region List Deleted Users [Obsolete("Use `GetAllAsync` instead.")] Task<UsersListResponse> ListAsync( PagerParameters pager = null, CancellationToken cancellationToken = default(CancellationToken)); Task<UsersListResponse> GetAllAsync( PagerParameters pager = null, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region Get Deleted Users Task<UserResponse> GetAsync( long userId, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region Permanently Delete Users Task PermanentlyDeleteAsync( long userId, CancellationToken cancellationToken = default(CancellationToken)); #endregion } }
31.264706
78
0.67921
[ "Apache-2.0" ]
Ud0o/ZendeskApiClient
src/ZendeskApi.Client/Resources/Interfaces/User/IDeletedUsersResource.cs
1,063
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ShopManager : MonoBehaviour { public ShopItemDecl[] items; public ShopItem itemPrefab; public Transform itemParent; private void Start() { for (int i = 0; i < items.Length; i++) { var it = items[i]; var pref = Instantiate(itemPrefab, itemParent); pref.title.text = it.title; pref.desc.text = it.description + "\nCost : " + (it.isGoogle ? "" : it.cost.ToString()) + " lines\n<color=#" + ColorUtility.ToHtmlStringRGBA(it.effectCol) + ">" + it.effect + "</color>"; pref.isGoogle = it.isGoogle; if (it.isGoogle) { pref.descr = it.description; pref.descr2 = "\n<color=#" + ColorUtility.ToHtmlStringRGBA(it.effectCol) + ">" + it.effect + "</color>"; } pref.img.sprite = it.image; pref.buy.onClick.AddListener(() => { if (it.cost > FindObjectOfType<GameManager>().Lines || it.isGoogle) { return; } FindObjectOfType<GameManager>().OnClick(true, -it.cost); FindObjectOfType<ClickManager>().AddCps(it.cpsInc); FindObjectOfType<ClickManager>().linesPerClick += it.pcInc; }); } } } [System.Serializable] public struct ShopItemDecl { public string title; public string description; public string effect; public Color effectCol; public Sprite image; public int cost; public int cpsInc; public int pcInc; public bool isGoogle; }
31.055556
198
0.568277
[ "MIT" ]
coderpro1123211/Idle-Coder-BIGNETWORK-JAM
Assets/Scripts/ShopManager.cs
1,679
C#
using System; using System.Linq.Expressions; using System.Threading.Tasks; using EmployeeManagement.Application.CacheRepositories; using EmployeeManagement.Application.Dtos.EmployeeDtos; using EmployeeManagement.Application.Exceptions; using EmployeeManagement.Application.Extensions; using EmployeeManagement.Application.Services; using EmployeeManagement.Domain.Entities; using TanvirArjel.EFCore.GenericRepository; namespace EmployeeManagement.Application.Implementations.Services { internal class EmployeeService : IEmployeeService { private readonly IEmployeeCacheRepository _employeeCacheRepository; private readonly IRepository _repository; public EmployeeService(IEmployeeCacheRepository employeeCacheRepository, IRepository repository) { _employeeCacheRepository = employeeCacheRepository; _repository = repository; } public async Task<PaginatedList<EmployeeDetailsDto>> GetListAsync(int pageNumber, int pageSize) { pageNumber.ThrowIfOutOfRange(1, 50, nameof(pageNumber)); pageNumber.ThrowIfOutOfRange(1, 50, nameof(pageSize)); Expression<Func<Employee, EmployeeDetailsDto>> selectExpression = e => new EmployeeDetailsDto { EmployeeId = e.Id, EmployeeName = e.Name, DepartmentId = e.DepartmentId, DepartmentName = e.Department.Name, DateOfBirth = e.DateOfBirth, Email = e.Email, PhoneNumber = e.PhoneNumber, IsActive = e.IsActive, CreatedAtUtc = e.CreatedAtUtc, LastModifiedAtUtc = e.LastModifiedAtUtc }; PaginationSpecification<Employee> paginationSpecification = new PaginationSpecification<Employee> { PageIndex = pageNumber, PageSize = pageSize }; PaginatedList<EmployeeDetailsDto> employeeDetailsDtos = await _repository.GetPaginatedListAsync(paginationSpecification, selectExpression); return employeeDetailsDtos; } public async Task<EmployeeDetailsDto> GetDetailsByIdAsync(int employeeId) { employeeId.ThrowIfNotPositive(nameof(employeeId)); EmployeeDetailsDto employeeDetailsDto = await _employeeCacheRepository.GetDetailsByIdAsync(employeeId); return employeeDetailsDto; } public async Task CreateAsync(CreateEmployeeDto createEmployeeDto) { createEmployeeDto.ThrowIfNull(nameof(createEmployeeDto)); Employee employeeToBeCreated = new Employee() { Name = createEmployeeDto.EmployeeName, DepartmentId = createEmployeeDto.DepartmentId, DateOfBirth = createEmployeeDto.DateOfBirth, Email = createEmployeeDto.Email, PhoneNumber = createEmployeeDto.PhoneNumber }; await _repository.InsertAsync(employeeToBeCreated); } public async Task UpdateAsync(UpdateEmployeeDto updateEmployeeDto) { try { updateEmployeeDto.ThrowIfNull(nameof(updateEmployeeDto)); Employee employeeeToBeUpdated = await _repository.GetByIdAsync<Employee>(updateEmployeeDto.EmployeeId); if (employeeeToBeUpdated == null) { throw new EntityNotFoundException(typeof(Employee), updateEmployeeDto.EmployeeId); } employeeeToBeUpdated.Name = updateEmployeeDto.EmployeeName; employeeeToBeUpdated.DepartmentId = updateEmployeeDto.DepartmentId; employeeeToBeUpdated.DateOfBirth = updateEmployeeDto.DateOfBirth; employeeeToBeUpdated.Email = updateEmployeeDto.Email; employeeeToBeUpdated.PhoneNumber = updateEmployeeDto.PhoneNumber; await _repository.UpdateAsync(employeeeToBeUpdated); } catch (Exception) { throw; } } public async Task DeleteAsync(int employeeId) { employeeId.ThrowIfNotPositive(nameof(employeeId)); Employee employeeeToBeDeleted = await _repository.GetByIdAsync<Employee>(employeeId); if (employeeeToBeDeleted == null) { throw new EntityNotFoundException(typeof(Employee), employeeId); } await _repository.DeleteAsync(employeeeToBeDeleted); } } }
37.827869
151
0.651571
[ "MIT" ]
nagurshaik-git/CleanArchitecture
src/Server/Core/EmployeeManagement.Application/Implementations/Services/EmployeeService.cs
4,617
C#
using System; using UnityEngine; using Zenject; namespace Zenject.Tests.Bindings.FromPrefabResource { public class Bob : MonoBehaviour { [NonSerialized] [Inject] public Jim Jim; } }
16.571429
52
0.62069
[ "MIT" ]
teareyes83/Fight2048
Assets/Plugins/Zenject/OptionalExtras/IntegrationTests/Bindings/TestFromPrefabResource/Common/Bob.cs
232
C#
namespace GeneXus.Deploy.AzureFunctions.Handlers.Helpers { public class EventSourceType { public const string QueueMessage = "QueueMessage"; public const string ServiceBusMessage = "ServiceBusMessage"; public const string Timer = "Timer"; } }
25.2
62
0.777778
[ "Apache-2.0" ]
genexuslabs/DotNetClasses
dotnet/src/extensions/Azure/Handlers/Helpers/EventSourceType.cs
252
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; using System.Collections; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Security.Principal; namespace System.DirectoryServices.AccountManagement { internal sealed partial class SAMStoreCtx : StoreCtx { private readonly DirectoryEntry _ctxBase; private readonly object _ctxBaseLock = new object(); // when mutating ctxBase private readonly bool _ownCtxBase; // if true, we "own" ctxBase and must Dispose of it when we're done private bool _disposed; internal NetCred Credentials { get { return _credentials; } } private readonly NetCred _credentials; internal AuthenticationTypes AuthTypes { get { return _authTypes; } } private readonly AuthenticationTypes _authTypes; private readonly ContextOptions _contextOptions; #pragma warning disable CA1810 // Initialize reference type static fields inline static SAMStoreCtx() #pragma warning restore CA1810 { // // Load the *PropertyMappingTableByProperty and *PropertyMappingTableByWinNT tables // s_userPropertyMappingTableByProperty = new Hashtable(); s_userPropertyMappingTableByWinNT = new Hashtable(); s_groupPropertyMappingTableByProperty = new Hashtable(); s_groupPropertyMappingTableByWinNT = new Hashtable(); s_computerPropertyMappingTableByProperty = new Hashtable(); s_computerPropertyMappingTableByWinNT = new Hashtable(); s_validPropertyMap = new Dictionary<string, ObjectMask>(); s_maskMap = new Dictionary<Type, ObjectMask>(); s_maskMap.Add(typeof(UserPrincipal), ObjectMask.User); s_maskMap.Add(typeof(ComputerPrincipal), ObjectMask.Computer); s_maskMap.Add(typeof(GroupPrincipal), ObjectMask.Group); s_maskMap.Add(typeof(Principal), ObjectMask.Principal); for (int i = 0; i < s_propertyMappingTableRaw.GetLength(0); i++) { string propertyName = s_propertyMappingTableRaw[i, 0] as string; Type principalType = s_propertyMappingTableRaw[i, 1] as Type; string winNTAttribute = s_propertyMappingTableRaw[i, 2] as string; FromWinNTConverterDelegate fromWinNT = s_propertyMappingTableRaw[i, 3] as FromWinNTConverterDelegate; ToWinNTConverterDelegate toWinNT = s_propertyMappingTableRaw[i, 4] as ToWinNTConverterDelegate; Debug.Assert(propertyName != null); Debug.Assert((winNTAttribute != null && fromWinNT != null) || (fromWinNT == null)); Debug.Assert(principalType == typeof(Principal) || principalType.IsSubclassOf(typeof(Principal))); // Build the table entry. The same entry will be used in both tables. // Once constructed, the table entries are treated as read-only, so there's // no danger in sharing the entries between tables. PropertyMappingTableEntry propertyEntry = new PropertyMappingTableEntry(); propertyEntry.propertyName = propertyName; propertyEntry.suggestedWinNTPropertyName = winNTAttribute; propertyEntry.winNTToPapiConverter = fromWinNT; propertyEntry.papiToWinNTConverter = toWinNT; // Add it to the appropriate tables List<Hashtable> byPropertyTables = new List<Hashtable>(); List<Hashtable> byWinNTTables = new List<Hashtable>(); ObjectMask BitMask = 0; if (principalType == typeof(UserPrincipal)) { byPropertyTables.Add(s_userPropertyMappingTableByProperty); byWinNTTables.Add(s_userPropertyMappingTableByWinNT); BitMask = ObjectMask.User; } else if (principalType == typeof(ComputerPrincipal)) { byPropertyTables.Add(s_computerPropertyMappingTableByProperty); byWinNTTables.Add(s_computerPropertyMappingTableByWinNT); BitMask = ObjectMask.Computer; } else if (principalType == typeof(GroupPrincipal)) { byPropertyTables.Add(s_groupPropertyMappingTableByProperty); byWinNTTables.Add(s_groupPropertyMappingTableByWinNT); BitMask = ObjectMask.Group; } else { Debug.Assert(principalType == typeof(Principal)); byPropertyTables.Add(s_userPropertyMappingTableByProperty); byPropertyTables.Add(s_computerPropertyMappingTableByProperty); byPropertyTables.Add(s_groupPropertyMappingTableByProperty); byWinNTTables.Add(s_userPropertyMappingTableByWinNT); byWinNTTables.Add(s_computerPropertyMappingTableByWinNT); byWinNTTables.Add(s_groupPropertyMappingTableByWinNT); BitMask = ObjectMask.Principal; } if ((winNTAttribute == null) || (winNTAttribute == "*******")) { BitMask = ObjectMask.None; } ObjectMask currentMask; if (s_validPropertyMap.TryGetValue(propertyName, out currentMask)) { s_validPropertyMap[propertyName] = currentMask | BitMask; } else { s_validPropertyMap.Add(propertyName, BitMask); } // *PropertyMappingTableByProperty // If toWinNT is null, there's no PAPI->WinNT mapping for this property // (it's probably read-only, e.g., "LastLogon"). // if (toWinNT != null) // { foreach (Hashtable propertyMappingTableByProperty in byPropertyTables) { if (propertyMappingTableByProperty[propertyName] == null) propertyMappingTableByProperty[propertyName] = new ArrayList(); ((ArrayList)propertyMappingTableByProperty[propertyName]).Add(propertyEntry); } // } // *PropertyMappingTableByWinNT // If fromLdap is null, there's no direct WinNT->PAPI mapping for this property. // It's probably a property that requires custom handling, such as an IdentityClaim. if (fromWinNT != null) { string winNTAttributeLower = winNTAttribute.ToLowerInvariant(); foreach (Hashtable propertyMappingTableByWinNT in byWinNTTables) { if (propertyMappingTableByWinNT[winNTAttributeLower] == null) propertyMappingTableByWinNT[winNTAttributeLower] = new ArrayList(); ((ArrayList)propertyMappingTableByWinNT[winNTAttributeLower]).Add(propertyEntry); } } } } // Throws exception if ctxBase is not a computer object public SAMStoreCtx(DirectoryEntry ctxBase, bool ownCtxBase, string username, string password, ContextOptions options) { Debug.Assert(ctxBase != null); GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "Constructing SAMStoreCtx for {0}", ctxBase.Path); Debug.Assert(SAMUtils.IsOfObjectClass(ctxBase, "Computer")); _ctxBase = ctxBase; _ownCtxBase = ownCtxBase; if (username != null && password != null) _credentials = new NetCred(username, password); _contextOptions = options; _authTypes = SDSUtils.MapOptionsToAuthTypes(options); } public override void Dispose() { try { if (!_disposed) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "Dispose: disposing, ownCtxBase={0}", _ownCtxBase); if (_ownCtxBase) _ctxBase.Dispose(); _disposed = true; } } finally { base.Dispose(); } } // // StoreCtx information // // Retrieves the Path (ADsPath) of the object used as the base of the StoreCtx internal override string BasePath { get { Debug.Assert(_ctxBase != null); return _ctxBase.Path; } } // // CRUD // // Used to perform the specified operation on the Principal. They also make any needed security subsystem // calls to obtain digitial signatures. // // Insert() and Update() must check to make sure no properties not supported by this StoreCtx // have been set, prior to persisting the Principal. internal override void Insert(Principal p) { Debug.Assert(p.unpersisted == true); Debug.Assert(p.fakePrincipal == false); try { // Insert the principal into the store SDSUtils.InsertPrincipal( p, this, new SDSUtils.GroupMembershipUpdater(UpdateGroupMembership), _credentials, _authTypes, false // handled in PushChangesToNative ); // Load in all the initial values from the store ((DirectoryEntry)p.UnderlyingObject).RefreshCache(); // Load in the StoreKey Debug.Assert(p.Key == null); // since it was previously unpersisted Debug.Assert(p.UnderlyingObject != null); // since we just persisted it Debug.Assert(p.UnderlyingObject is DirectoryEntry); DirectoryEntry de = (DirectoryEntry)p.UnderlyingObject; // We just created a principal, so it should have an objectSid Debug.Assert((de.Properties["objectSid"] != null) && (de.Properties["objectSid"].Count == 1)); SAMStoreKey key = new SAMStoreKey( this.MachineFlatName, (byte[])de.Properties["objectSid"].Value ); p.Key = key; // Reset the change tracking p.ResetAllChangeStatus(); GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "Insert: new SID is ", Utils.ByteArrayToString((byte[])de.Properties["objectSid"].Value)); } catch (System.Runtime.InteropServices.COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(e); } } internal override void Update(Principal p) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "Update"); Debug.Assert(p.fakePrincipal == false); Debug.Assert(p.unpersisted == false); Debug.Assert(p.UnderlyingObject != null); Debug.Assert(p.UnderlyingObject is DirectoryEntry); try { // Commit the properties SDSUtils.ApplyChangesToDirectory( p, this, new SDSUtils.GroupMembershipUpdater(UpdateGroupMembership), _credentials, _authTypes ); // Reset the change tracking p.ResetAllChangeStatus(); } catch (System.Runtime.InteropServices.COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(e); } } internal override void Delete(Principal p) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "Delete"); Debug.Assert(p.fakePrincipal == false); // Principal.Delete() shouldn't be calling us on an unpersisted Principal. Debug.Assert(p.unpersisted == false); Debug.Assert(p.UnderlyingObject != null); Debug.Assert(p.UnderlyingObject is DirectoryEntry); try { SDSUtils.DeleteDirectoryEntry((DirectoryEntry)p.UnderlyingObject); } catch (System.Runtime.InteropServices.COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(e); } } internal override bool AccessCheck(Principal p, PrincipalAccessMask targetPermission) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "AccessCheck " + targetPermission.ToString()); switch (targetPermission) { case PrincipalAccessMask.ChangePassword: PropertyValueCollection values = ((DirectoryEntry)p.GetUnderlyingObject()).Properties["UserFlags"]; if (values.Count != 0) { Debug.Assert(values.Count == 1); Debug.Assert(values[0] is int); return (SDSUtils.StatusFromAccountControl((int)values[0], PropertyNames.PwdInfoCannotChangePassword)); } Debug.Fail("SAMStoreCtx.AccessCheck: user entry has an empty UserFlags value"); GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "AccessCheck Unable to read userAccountControl"); break; default: Debug.Fail("SAMStoreCtx.AccessCheck: Fell off end looking for " + targetPermission.ToString()); break; } return false; } internal override void Move(StoreCtx originalStore, Principal p) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "Move"); } // // Special operations: the Principal classes delegate their implementation of many of the // special methods to their underlying StoreCtx // // methods for manipulating accounts /// <summary> /// This method sets the default user account control bits for the new principal /// being created in this account store. /// </summary> /// <param name="p"> Principal to set the user account control bits for </param> internal override void InitializeUserAccountControl(AuthenticablePrincipal p) { Debug.Assert(p != null); Debug.Assert(p.fakePrincipal == false); Debug.Assert(p.unpersisted == true); // should only ever be called for new principals // set the userAccountControl bits on the underlying directory entry DirectoryEntry de = (DirectoryEntry)p.UnderlyingObject; Debug.Assert(de != null); Type principalType = p.GetType(); if ((principalType == typeof(UserPrincipal)) || (principalType.IsSubclassOf(typeof(UserPrincipal)))) { de.Properties["userFlags"].Value = SDSUtils.SAM_DefaultUAC; } } internal override bool IsLockedOut(AuthenticablePrincipal p) { Debug.Assert(p.fakePrincipal == false); Debug.Assert(p.unpersisted == false); DirectoryEntry de = (DirectoryEntry)p.UnderlyingObject; Debug.Assert(de != null); try { de.RefreshCache(); return (bool)de.InvokeGet("IsAccountLocked"); } catch (System.Reflection.TargetInvocationException e) { if (e.InnerException is System.Runtime.InteropServices.COMException) { throw (ExceptionHelper.GetExceptionFromCOMException((System.Runtime.InteropServices.COMException)e.InnerException)); } throw; } } internal override void UnlockAccount(AuthenticablePrincipal p) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "UnlockAccount"); Debug.Assert(p.fakePrincipal == false); Debug.Assert(p.unpersisted == false); // Computer accounts are never locked out, so nothing to do if (p is ComputerPrincipal) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "UnlockAccount: computer acct, skipping"); return; } DirectoryEntry de = (DirectoryEntry)p.UnderlyingObject; Debug.Assert(de != null); // After setting the property, we need to commit the change to the store. // We do it in a copy of de, so that we don't inadvertently commit any other // pending changes in de. DirectoryEntry copyOfDe = null; try { copyOfDe = SDSUtils.BuildDirectoryEntry(de.Path, _credentials, _authTypes); Debug.Assert(copyOfDe != null); copyOfDe.InvokeSet("IsAccountLocked", new object[] { false }); copyOfDe.CommitChanges(); } catch (System.Runtime.InteropServices.COMException e) { // ADSI threw an exception trying to write the change GlobalDebug.WriteLineIf(GlobalDebug.Error, "SAMStoreCtx", "UnlockAccount: caught COMException, message={0}", e.Message); throw ExceptionHelper.GetExceptionFromCOMException(e); } finally { if (copyOfDe != null) copyOfDe.Dispose(); } } // methods for manipulating passwords internal override void SetPassword(AuthenticablePrincipal p, string newPassword) { Debug.Assert(p.fakePrincipal == false); Debug.Assert(p is UserPrincipal || p is ComputerPrincipal); // Shouldn't be being called if this is the case Debug.Assert(p.unpersisted == false); // ********** In SAM, computer accounts don't have a set password method if (p is ComputerPrincipal) { GlobalDebug.WriteLineIf(GlobalDebug.Warn, "SAMStoreCtx", "SetPassword: computer acct, can't reset"); throw new InvalidOperationException(SR.SAMStoreCtxNoComputerPasswordSet); } Debug.Assert(p != null); Debug.Assert(newPassword != null); // but it could be an empty string DirectoryEntry de = (DirectoryEntry)p.UnderlyingObject; Debug.Assert(de != null); SDSUtils.SetPassword(de, newPassword); } internal override void ChangePassword(AuthenticablePrincipal p, string oldPassword, string newPassword) { Debug.Assert(p.fakePrincipal == false); Debug.Assert(p is UserPrincipal || p is ComputerPrincipal); // Shouldn't be being called if this is the case Debug.Assert(p.unpersisted == false); // ********** In SAM, computer accounts don't have a change password method if (p is ComputerPrincipal) { GlobalDebug.WriteLineIf(GlobalDebug.Warn, "SAMStoreCtx", "ChangePassword: computer acct, can't change"); throw new InvalidOperationException(SR.SAMStoreCtxNoComputerPasswordSet); } Debug.Assert(p != null); Debug.Assert(newPassword != null); // but it could be an empty string Debug.Assert(oldPassword != null); // but it could be an empty string DirectoryEntry de = (DirectoryEntry)p.UnderlyingObject; Debug.Assert(de != null); SDSUtils.ChangePassword(de, oldPassword, newPassword); } internal override void ExpirePassword(AuthenticablePrincipal p) { Debug.Assert(p.fakePrincipal == false); // ********** In SAM, computer accounts don't have a password-expired property if (p is ComputerPrincipal) { GlobalDebug.WriteLineIf(GlobalDebug.Warn, "SAMStoreCtx", "ExpirePassword: computer acct, can't expire"); throw new InvalidOperationException(SR.SAMStoreCtxNoComputerPasswordExpire); } WriteAttribute(p, "PasswordExpired", 1); } internal override void UnexpirePassword(AuthenticablePrincipal p) { Debug.Assert(p.fakePrincipal == false); // ********** In SAM, computer accounts don't have a password-expired property if (p is ComputerPrincipal) { GlobalDebug.WriteLineIf(GlobalDebug.Warn, "SAMStoreCtx", "UnexpirePassword: computer acct, can't unexpire"); throw new InvalidOperationException(SR.SAMStoreCtxNoComputerPasswordExpire); } WriteAttribute(p, "PasswordExpired", 0); } private void WriteAttribute(AuthenticablePrincipal p, string attribute, int value) { Debug.Assert(p is UserPrincipal || p is ComputerPrincipal); Debug.Assert(p != null); DirectoryEntry de = (DirectoryEntry)p.UnderlyingObject; SDSUtils.WriteAttribute(de.Path, attribute, value, _credentials, _authTypes); } // // the various FindBy* methods // internal override ResultSet FindByLockoutTime( DateTime dt, MatchType matchType, Type principalType) { throw new NotSupportedException(SR.StoreNotSupportMethod); } internal override ResultSet FindByBadPasswordAttempt( DateTime dt, MatchType matchType, Type principalType) { throw new NotSupportedException(SR.StoreNotSupportMethod); } internal override ResultSet FindByLogonTime( DateTime dt, MatchType matchType, Type principalType) { return FindByDate(FindByDateMatcher.DateProperty.LogonTime, matchType, dt, principalType); } internal override ResultSet FindByPasswordSetTime( DateTime dt, MatchType matchType, Type principalType) { return FindByDate(FindByDateMatcher.DateProperty.PasswordSetTime, matchType, dt, principalType); } internal override ResultSet FindByExpirationTime( DateTime dt, MatchType matchType, Type principalType) { return FindByDate(FindByDateMatcher.DateProperty.AccountExpirationTime, matchType, dt, principalType); } private ResultSet FindByDate( FindByDateMatcher.DateProperty property, MatchType matchType, DateTime value, Type principalType ) { // We use the same SAMQuery set that we use for query-by-example, but with a different // SAMMatcher class to perform the date-range filter. // Get the entries we'll iterate over. Write access to Children is controlled through the // ctxBaseLock, but we don't want to have to hold that lock while we're iterating over all // the child entries. So we have to clone the ctxBase --- not ideal, but it prevents // multithreading issues. DirectoryEntries entries = SDSUtils.BuildDirectoryEntry(_ctxBase.Path, _credentials, _authTypes).Children; Debug.Assert(entries != null); // The SAMQuerySet will use this to restrict the types of DirectoryEntry objects returned. List<string> schemaTypes = GetSchemaFilter(principalType); // Create the ResultSet that will perform the client-side filtering SAMQuerySet resultSet = new SAMQuerySet( schemaTypes, entries, _ctxBase, -1, // no size limit this, new FindByDateMatcher(property, matchType, value)); return resultSet; } // Get groups of which p is a direct member internal override ResultSet GetGroupsMemberOf(Principal p) { // Enforced by the methods that call us Debug.Assert(p.unpersisted == false); if (!p.fakePrincipal) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "GetGroupsMemberOf: is real principal"); // No nested groups or computers as members of groups in SAM if (!(p is UserPrincipal)) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "GetGroupsMemberOf: not a user, returning empty set"); return new EmptySet(); } Debug.Assert(p.UnderlyingObject != null); DirectoryEntry userDE = (DirectoryEntry)p.UnderlyingObject; UnsafeNativeMethods.IADsMembers iadsMembers = (UnsafeNativeMethods.IADsMembers)userDE.Invoke("Groups"); ResultSet resultSet = new SAMGroupsSet(iadsMembers, this, _ctxBase); return resultSet; } else { // ADSI's IADsGroups doesn't work for fake principals like NT AUTHORITY\NETWORK SERVICE // We use the same SAMQuery set that we use for query-by-example, but with a different // SAMMatcher class to match groups which contain the specified principal as a member // Get the entries we'll iterate over. Write access to Children is controlled through the // ctxBaseLock, but we don't want to have to hold that lock while we're iterating over all // the child entries. So we have to clone the ctxBase --- not ideal, but it prevents // multithreading issues. DirectoryEntries entries = SDSUtils.BuildDirectoryEntry(_ctxBase.Path, _credentials, _authTypes).Children; Debug.Assert(entries != null); // The SAMQuerySet will use this to restrict the types of DirectoryEntry objects returned. List<string> schemaTypes = GetSchemaFilter(typeof(GroupPrincipal)); SecurityIdentifier principalSid = p.Sid; byte[] SidB = new byte[principalSid.BinaryLength]; principalSid.GetBinaryForm(SidB, 0); if (principalSid == null) { GlobalDebug.WriteLineIf(GlobalDebug.Warn, "SAMStoreCtx", "GetGroupsMemberOf: bad SID IC"); throw new InvalidOperationException(SR.StoreCtxNeedValueSecurityIdentityClaimToQuery); } // Create the ResultSet that will perform the client-side filtering SAMQuerySet resultSet = new SAMQuerySet( schemaTypes, entries, _ctxBase, -1, // no size limit this, new GroupMemberMatcher(SidB)); return resultSet; } } // Get groups from this ctx which contain a principal corresponding to foreignPrincipal // (which is a principal from foreignContext) internal override ResultSet GetGroupsMemberOf(Principal foreignPrincipal, StoreCtx foreignContext) { // If it's a fake principal, we don't need to do any of the lookup to find a local representation. // We'll skip straight to GetGroupsMemberOf(Principal), which will lookup the groups to which it belongs via its SID. if (foreignPrincipal.fakePrincipal) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "GetGroupsMemberOf(ctx): is fake principal"); return GetGroupsMemberOf(foreignPrincipal); } // Get the Principal's SID, so we can look it up by SID in our store SecurityIdentifier Sid = foreignPrincipal.Sid; if (Sid == null) { GlobalDebug.WriteLineIf(GlobalDebug.Warn, "SAMStoreCtx", "GetGroupsMemberOf(ctx): no SID IC"); throw new InvalidOperationException(SR.StoreCtxNeedValueSecurityIdentityClaimToQuery); } // In SAM, only users can be member of SAM groups (no nested groups) UserPrincipal u = UserPrincipal.FindByIdentity(this.OwningContext, IdentityType.Sid, Sid.ToString()); // If no corresponding principal exists in this store, then by definition the principal isn't // a member of any groups in this store. if (u == null) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "GetGroupsMemberOf(ctx): no corresponding user, returning empty set"); return new EmptySet(); } // Now that we got the principal in our store, enumerating its group membership can be handled the // usual way. return GetGroupsMemberOf(u); } // Get groups of which p is a member, using AuthZ S4U APIs for recursive membership internal override ResultSet GetGroupsMemberOfAZ(Principal p) { // Enforced by the methods that call us Debug.Assert(p.unpersisted == false); Debug.Assert(p is UserPrincipal); // Get the user SID that AuthZ will use. SecurityIdentifier Sid = p.Sid; if (Sid == null) { GlobalDebug.WriteLineIf(GlobalDebug.Warn, "SAMStoreCtx", "GetGroupsMemberOfAZ: no SID IC"); throw new InvalidOperationException(SR.StoreCtxNeedValueSecurityIdentityClaimToQuery); } byte[] Sidb = new byte[Sid.BinaryLength]; Sid.GetBinaryForm(Sidb, 0); if (Sidb == null) { GlobalDebug.WriteLineIf(GlobalDebug.Warn, "SAMStoreCtx", "GetGroupsMemberOfAZ: Bad SID IC"); throw new ArgumentException(SR.StoreCtxSecurityIdentityClaimBadFormat); } try { return new AuthZSet(Sidb, _credentials, _contextOptions, this.MachineFlatName, this, _ctxBase); } catch (System.Runtime.InteropServices.COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(e); } } // Get members of group g internal override BookmarkableResultSet GetGroupMembership(GroupPrincipal g, bool recursive) { // Enforced by the methods that call us Debug.Assert(g.unpersisted == false); // Fake groups are a member of other groups, but they themselves have no members // (they don't even exist in the store) if (g.fakePrincipal) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "GetGroupMembership: is fake principal, returning empty set"); return new EmptySet(); } Debug.Assert(g.UnderlyingObject != null); DirectoryEntry groupDE = (DirectoryEntry)g.UnderlyingObject; UnsafeNativeMethods.IADsGroup iADsGroup = (UnsafeNativeMethods.IADsGroup)groupDE.NativeObject; BookmarkableResultSet resultSet = new SAMMembersSet(groupDE.Path, iADsGroup, recursive, this, _ctxBase); return resultSet; } // Is p a member of g in the store? internal override bool SupportsNativeMembershipTest { get { return false; } } internal override bool IsMemberOfInStore(GroupPrincipal g, Principal p) { Debug.Fail("SAMStoreCtx.IsMemberOfInStore: Shouldn't be here."); return false; } // Can a Clear() operation be performed on the specified group? If not, also returns // a string containing a human-readable explanation of why not, suitable for use in an exception. internal override bool CanGroupBeCleared(GroupPrincipal g, out string explanationForFailure) { // Always true for this type of StoreCtx explanationForFailure = null; return true; } // Can the given member be removed from the specified group? If not, also returns // a string containing a human-readable explanation of why not, suitable for use in an exception. internal override bool CanGroupMemberBeRemoved(GroupPrincipal g, Principal member, out string explanationForFailure) { // Always true for this type of StoreCtx explanationForFailure = null; return true; } // // Cross-store support // // Given a native store object that represents a "foreign" principal (e.g., a FPO object in this store that // represents a pointer to another store), maps that representation to the other store's StoreCtx and returns // a Principal from that other StoreCtx. The implementation of this method is highly dependent on the // details of the particular store, and must have knowledge not only of this StoreCtx, but also of how to // interact with other StoreCtxs to fulfill the request. // // This method is typically used by ResultSet implementations, when they're iterating over a collection // (e.g., of group membership) and encounter an entry that represents a foreign principal. internal override Principal ResolveCrossStoreRefToPrincipal(object o) { Debug.Assert(o is DirectoryEntry); // Get the SID of the foreign principal DirectoryEntry foreignDE = (DirectoryEntry)o; if (foreignDE.Properties["objectSid"].Count == 0) { GlobalDebug.WriteLineIf(GlobalDebug.Warn, "SAMStoreCtx", "ResolveCrossStoreRefToPrincipal: no objectSid found"); throw new PrincipalOperationException(SR.SAMStoreCtxCantRetrieveObjectSidForCrossStore); } Debug.Assert(foreignDE.Properties["objectSid"].Count == 1); byte[] sid = (byte[])foreignDE.Properties["objectSid"].Value; // Ask the OS to resolve the SID to its target. int accountUsage = 0; string name; string domainName; int err = Utils.LookupSid(this.MachineUserSuppliedName, _credentials, sid, out name, out domainName, out accountUsage); if (err != 0) { GlobalDebug.WriteLineIf(GlobalDebug.Warn, "SAMStoreCtx", "ResolveCrossStoreRefToPrincipal: LookupSid failed, err={0}, server={1}", err, this.MachineUserSuppliedName); throw new PrincipalOperationException( SR.Format(SR.SAMStoreCtxCantResolveSidForCrossStore, err)); } GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "ResolveCrossStoreRefToPrincipal: LookupSid found {0} in {1}", name, domainName); // Since this is SAM, the remote principal must be an AD principal. // Build a PrincipalContext for the store which owns the principal // Use the ad default options so we turn sign and seal back on. PrincipalContext remoteCtx = SDSCache.Domain.GetContext(domainName, _credentials, DefaultContextOptions.ADDefaultContextOption); SecurityIdentifier sidObj = new SecurityIdentifier(sid, 0); Principal p = remoteCtx.QueryCtx.FindPrincipalByIdentRef( typeof(Principal), UrnScheme.SidScheme, sidObj.ToString(), DateTime.UtcNow); if (p != null) return p; else { GlobalDebug.WriteLineIf(GlobalDebug.Warn, "SAMStoreCtx", "ResolveCrossStoreRefToPrincipal: no matching principal"); throw new PrincipalOperationException(SR.SAMStoreCtxFailedFindCrossStoreTarget); } } // // Data Validation // // Returns true if AccountInfo is supported for the specified principal, false otherwise. // Used when an application tries to access the AccountInfo property of a newly-inserted // (not yet persisted) AuthenticablePrincipal, to determine whether it should be allowed. internal override bool SupportsAccounts(AuthenticablePrincipal p) { // Fake principals do not have store objects, so they certainly don't have stored account info. if (p.fakePrincipal) return false; // Both Computer and User support accounts. return true; } // Returns the set of credential types supported by this store for the specified principal. // Used when an application tries to access the PasswordInfo property of a newly-inserted // (not yet persisted) AuthenticablePrincipal, to determine whether it should be allowed. // Also used to implement AuthenticablePrincipal.SupportedCredentialTypes. internal override CredentialTypes SupportedCredTypes(AuthenticablePrincipal p) { // Fake principals do not have store objects, so they certainly don't have stored creds. if (p.fakePrincipal) return (CredentialTypes)0; CredentialTypes supportedTypes = CredentialTypes.Password; // Longhorn SAM supports certificate-based authentication if (this.IsLSAM) supportedTypes |= CredentialTypes.Certificate; return supportedTypes; } // // Construct a fake Principal to represent a well-known SID like // "\Everyone" or "NT AUTHORITY\NETWORK SERVICE" // internal override Principal ConstructFakePrincipalFromSID(byte[] sid) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "ConstructFakePrincipalFromSID: sid={0}, machine={1}", Utils.ByteArrayToString(sid), this.MachineFlatName); Principal p = Utils.ConstructFakePrincipalFromSID( sid, this.OwningContext, this.MachineUserSuppliedName, _credentials, this.MachineUserSuppliedName); // Assign it a StoreKey SAMStoreKey key = new SAMStoreKey(this.MachineFlatName, sid); p.Key = key; return p; } // // Private data // private bool IsLSAM // IsLonghornSAM (also called MSAM or LH-SAM) { get { if (!_isLSAM.HasValue) { lock (_computerInfoLock) { if (!_isLSAM.HasValue) LoadComputerInfo(); } } Debug.Assert(_isLSAM.HasValue); return _isLSAM.Value; } } internal string MachineUserSuppliedName { get { if (_machineUserSuppliedName == null) { lock (_computerInfoLock) { if (_machineUserSuppliedName == null) LoadComputerInfo(); } } Debug.Assert(_machineUserSuppliedName != null); return _machineUserSuppliedName; } } internal string MachineFlatName { get { if (_machineFlatName == null) { lock (_computerInfoLock) { if (_machineFlatName == null) LoadComputerInfo(); } } Debug.Assert(_machineFlatName != null); return _machineFlatName; } } private readonly object _computerInfoLock = new object(); private Nullable<bool> _isLSAM; private string _machineUserSuppliedName; private string _machineFlatName; // computerInfoLock must be held coming in here private void LoadComputerInfo() { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "LoadComputerInfo"); Debug.Assert(_ctxBase != null); Debug.Assert(SAMUtils.IsOfObjectClass(_ctxBase, "Computer")); // // Target OS version // int versionMajor; int versionMinor; if (!SAMUtils.GetOSVersion(_ctxBase, out versionMajor, out versionMinor)) { throw new PrincipalOperationException(SR.SAMStoreCtxUnableToRetrieveVersion); } Debug.Assert(versionMajor > 0); Debug.Assert(versionMinor >= 0); if (versionMajor >= 6) // 6.0 == Longhorn _isLSAM = true; else _isLSAM = false; GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "LoadComputerInfo: ver={0}.{1}", versionMajor, versionMinor); // // Machine user-supplied name // // This ADSI property stores the machine name as supplied by the user in the ADsPath. // It could be a flat name or a DNS name. if (_ctxBase.Properties["Name"].Count > 0) { Debug.Assert(_ctxBase.Properties["Name"].Count == 1); _machineUserSuppliedName = (string)_ctxBase.Properties["Name"].Value; GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "LoadComputerInfo: machineUserSuppliedName={0}", _machineUserSuppliedName); } else { throw new PrincipalOperationException(SR.SAMStoreCtxUnableToRetrieveMachineName); } // // Machine flat name // IntPtr buffer = IntPtr.Zero; try { // This function takes in a flat or DNS name, and returns the flat name of the computer int err = Interop.Wkscli.NetWkstaGetInfo(_machineUserSuppliedName, 100, ref buffer); if (err == 0) { UnsafeNativeMethods.WKSTA_INFO_100 wkstaInfo = (UnsafeNativeMethods.WKSTA_INFO_100)Marshal.PtrToStructure(buffer, typeof(UnsafeNativeMethods.WKSTA_INFO_100)); _machineFlatName = wkstaInfo.wki100_computername; GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "LoadComputerInfo: machineFlatName={0}", _machineFlatName); } else { throw new PrincipalOperationException( SR.Format( SR.SAMStoreCtxUnableToRetrieveFlatMachineName, err)); } } finally { if (buffer != IntPtr.Zero) Interop.Netutils.NetApiBufferFree(buffer); } } internal override bool IsValidProperty(Principal p, string propertyName) { ObjectMask value = ObjectMask.None; if (s_validPropertyMap.TryGetValue(propertyName, out value)) { return ((s_maskMap[p.GetType()] & value) > 0 ? true : false); } else { Debug.Fail("Property not found"); return false; } } } }
41.891324
163
0.56515
[ "MIT" ]
333fred/runtime
src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/SAM/SAMStoreCtx.cs
45,871
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.IO; using System.Linq; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; namespace NuGet.Build.Tasks { /// <summary> /// Convert .metaproj paths to project paths. /// </summary> public class GetRestoreSolutionProjectsTask : Microsoft.Build.Utilities.Task { private const string MetaProjExtension = ".metaproj"; /// <summary> /// Solution project references. /// </summary> [Required] public ITaskItem[] ProjectReferences { get; set; } /// <summary> /// Root path used for resolving the absolute project paths. /// </summary> [Required] public string SolutionFilePath { get; set; } /// <summary> /// Output items /// </summary> [Output] public ITaskItem[] OutputProjectReferences { get; set; } public override bool Execute() { // Log inputs var log = new MSBuildLogger(Log); log.LogDebug($"(in) ProjectReferences '{string.Join(";", ProjectReferences.Select(p => p.ItemSpec))}'"); log.LogDebug($"(in) SolutionFilePath '{SolutionFilePath}'"); var entries = new List<ITaskItem>(); var parentDirectory = Path.GetDirectoryName(SolutionFilePath); foreach (var project in ProjectReferences) { if (string.IsNullOrEmpty(project.ItemSpec)) { continue; } var projectPath = Path.GetFullPath(Path.Combine(parentDirectory, project.ItemSpec)); // Check for the metaproj extension, this is auto generated by solutions instead of // the actual project path when build order is set. For the purpose of restore // the order is not important so we remove the extension to get the real project path. if (projectPath.EndsWith(MetaProjExtension, StringComparison.OrdinalIgnoreCase)) { // Remove .metaproj from the path. projectPath = projectPath.Substring(0, projectPath.Length - MetaProjExtension.Length); } // Clone items using the modified path var newEntry = new TaskItem(projectPath, project.CloneCustomMetadata()); entries.Add(newEntry); } OutputProjectReferences = entries.ToArray(); return true; } } }
35.337662
116
0.596104
[ "Apache-2.0" ]
AntonC9018/NuGet.Client
src/NuGet.Core/NuGet.Build.Tasks/GetRestoreSolutionProjectsTask.cs
2,721
C#