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
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BorsukSoftware.ObjectGraph.ObjectBuilders { /// <summary> /// Standard implementation of <see cref="IDependency{T}"/> /// </summary> /// <typeparam name="TAddress">The type of the address</typeparam> public sealed class Dependency<TAddress> : IDependency<TAddress> { #region IDependency Members public string Name { get; private set; } public IObjectContext<TAddress> ObjectContext { get; private set; } public TAddress Address { get; private set; } #endregion #region Construction Logic /// <summary> /// Creates a new instance of <see cref="Dependency{TAddress}"/> /// </summary> /// <param name="name">The name of the dependency</param> /// <param name="address">The address of the dependency</param> /// <param name="objectContext">The object context that the item must be sourced from (optional)</param> /// <exception cref="ArgumentNullException">If no address is specified</exception> public Dependency( string name, TAddress address, IObjectContext<TAddress> objectContext ) { if( address == null ) throw new ArgumentNullException( nameof( address ) ); this.Name = name; this.Address = address; this.ObjectContext = objectContext; } #endregion } }
28.702128
106
0.716086
[ "MIT" ]
borsuksoftware/ObjectGraph
ObjectGraph.Core/ObjectBuilders/Dependency.cs
1,351
C#
namespace Qooba.Framework.Abstractions { public interface IModuleProvider { IModule GetModule(string name); } }
16.625
39
0.684211
[ "MIT" ]
qooba/Qooba.Framework
src/Qooba.Framework.Abstractions/IModuleProvider.cs
135
C#
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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.Collections.Generic; using Aliyun.Acs.Core; namespace Aliyun.Acs.OutboundBot.Model.V20191226 { public class ListTagsResponse : AcsResponse { private string requestId; private bool? success; private string code; private string message; private int? httpStatusCode; private List<ListTags_Tag> tags; private List<ListTags_TagGroup> tagGroups; public string RequestId { get { return requestId; } set { requestId = value; } } public bool? Success { get { return success; } set { success = value; } } public string Code { get { return code; } set { code = value; } } public string Message { get { return message; } set { message = value; } } public int? HttpStatusCode { get { return httpStatusCode; } set { httpStatusCode = value; } } public List<ListTags_Tag> Tags { get { return tags; } set { tags = value; } } public List<ListTags_TagGroup> TagGroups { get { return tagGroups; } set { tagGroups = value; } } public class ListTags_Tag { private string tagId; private string tagName; private int? tagIndex; private string scriptId; private string tagGroup; public string TagId { get { return tagId; } set { tagId = value; } } public string TagName { get { return tagName; } set { tagName = value; } } public int? TagIndex { get { return tagIndex; } set { tagIndex = value; } } public string ScriptId { get { return scriptId; } set { scriptId = value; } } public string TagGroup { get { return tagGroup; } set { tagGroup = value; } } } public class ListTags_TagGroup { private string tagGroupId; private int? tagGroupIndex; private string scriptId; private string tagGroup; public string TagGroupId { get { return tagGroupId; } set { tagGroupId = value; } } public int? TagGroupIndex { get { return tagGroupIndex; } set { tagGroupIndex = value; } } public string ScriptId { get { return scriptId; } set { scriptId = value; } } public string TagGroup { get { return tagGroup; } set { tagGroup = value; } } } } }
14.10728
63
0.543726
[ "Apache-2.0" ]
bbs168/aliyun-openapi-net-sdk
aliyun-net-sdk-outboundbot/OutboundBot/Model/V20191226/ListTagsResponse.cs
3,682
C#
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** 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.Aws.Schemas { /// <summary> /// Provides an EventBridge Custom Schema Registry resource. /// /// &gt; **Note:** EventBridge was formerly known as CloudWatch Events. The functionality is identical. /// /// ## Example Usage /// /// ```csharp /// using Pulumi; /// using Aws = Pulumi.Aws; /// /// class MyStack : Stack /// { /// public MyStack() /// { /// var test = new Aws.Schemas.Registry("test", new Aws.Schemas.RegistryArgs /// { /// Description = "A custom schema registry", /// }); /// } /// /// } /// ``` /// /// ## Import /// /// EventBridge schema registries can be imported using the `name`, e.g., console /// /// ```sh /// $ pulumi import aws:schemas/registry:Registry test my_own_registry /// ``` /// </summary> [AwsResourceType("aws:schemas/registry:Registry")] public partial class Registry : Pulumi.CustomResource { /// <summary> /// The Amazon Resource Name (ARN) of the discoverer. /// </summary> [Output("arn")] public Output<string> Arn { get; private set; } = null!; /// <summary> /// The description of the discoverer. Maximum of 256 characters. /// </summary> [Output("description")] public Output<string?> Description { get; private set; } = null!; /// <summary> /// The name of the custom event schema registry. Maximum of 64 characters consisting of lower case letters, upper case letters, 0-9, ., -, _. /// </summary> [Output("name")] public Output<string> Name { get; private set; } = null!; [Output("tags")] public Output<ImmutableDictionary<string, string>?> Tags { get; private set; } = null!; /// <summary> /// A map of tags assigned to the resource, including those inherited from the provider `default_tags` configuration block. /// </summary> [Output("tagsAll")] public Output<ImmutableDictionary<string, string>> TagsAll { get; private set; } = null!; /// <summary> /// Create a Registry 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 Registry(string name, RegistryArgs? args = null, CustomResourceOptions? options = null) : base("aws:schemas/registry:Registry", name, args ?? new RegistryArgs(), MakeResourceOptions(options, "")) { } private Registry(string name, Input<string> id, RegistryState? state = null, CustomResourceOptions? options = null) : base("aws:schemas/registry:Registry", name, state, MakeResourceOptions(options, id)) { } private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id) { var defaultOptions = new CustomResourceOptions { Version = Utilities.Version, }; 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 Registry 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="state">Any extra arguments used during the lookup.</param> /// <param name="options">A bag of options that control this resource's behavior</param> public static Registry Get(string name, Input<string> id, RegistryState? state = null, CustomResourceOptions? options = null) { return new Registry(name, id, state, options); } } public sealed class RegistryArgs : Pulumi.ResourceArgs { /// <summary> /// The description of the discoverer. Maximum of 256 characters. /// </summary> [Input("description")] public Input<string>? Description { get; set; } /// <summary> /// The name of the custom event schema registry. Maximum of 64 characters consisting of lower case letters, upper case letters, 0-9, ., -, _. /// </summary> [Input("name")] public Input<string>? Name { get; set; } [Input("tags")] private InputMap<string>? _tags; public InputMap<string> Tags { get => _tags ?? (_tags = new InputMap<string>()); set => _tags = value; } public RegistryArgs() { } } public sealed class RegistryState : Pulumi.ResourceArgs { /// <summary> /// The Amazon Resource Name (ARN) of the discoverer. /// </summary> [Input("arn")] public Input<string>? Arn { get; set; } /// <summary> /// The description of the discoverer. Maximum of 256 characters. /// </summary> [Input("description")] public Input<string>? Description { get; set; } /// <summary> /// The name of the custom event schema registry. Maximum of 64 characters consisting of lower case letters, upper case letters, 0-9, ., -, _. /// </summary> [Input("name")] public Input<string>? Name { get; set; } [Input("tags")] private InputMap<string>? _tags; public InputMap<string> Tags { get => _tags ?? (_tags = new InputMap<string>()); set => _tags = value; } [Input("tagsAll")] private InputMap<string>? _tagsAll; /// <summary> /// A map of tags assigned to the resource, including those inherited from the provider `default_tags` configuration block. /// </summary> public InputMap<string> TagsAll { get => _tagsAll ?? (_tagsAll = new InputMap<string>()); set => _tagsAll = value; } public RegistryState() { } } }
36.4
150
0.57808
[ "ECL-2.0", "Apache-2.0" ]
wgarcia79/pulumi-aws
sdk/dotnet/Schemas/Registry.cs
6,916
C#
using System; using System.Collections; using System.Collections.Generic; using System.Linq; namespace ServiceStack.OrmLite.Dapper { public static partial class SqlMapper { private sealed class DapperRow : System.Dynamic.IDynamicMetaObjectProvider , IDictionary<string, object> , IReadOnlyDictionary<string, object> { private readonly DapperTable table; private object[] values; public DapperRow(DapperTable table, object[] values) { this.table = table ?? throw new ArgumentNullException(nameof(table)); this.values = values ?? throw new ArgumentNullException(nameof(values)); } private sealed class DeadValue { public static readonly DeadValue Default = new DeadValue(); private DeadValue() { /* hiding constructor */ } } int ICollection<KeyValuePair<string, object>>.Count { get { int count = 0; for (int i = 0; i < values.Length; i++) { if (!(values[i] is DeadValue)) count++; } return count; } } public bool TryGetValue(string key, out object value) { var index = table.IndexOfName(key); if (index < 0) { // doesn't exist value = null; return false; } // exists, **even if** we don't have a value; consider table rows heterogeneous value = index < values.Length ? values[index] : null; if (value is DeadValue) { // pretend it isn't here value = null; return false; } return true; } public override string ToString() { var sb = GetStringBuilder().Append("{DapperRow"); foreach (var kv in this) { var value = kv.Value; sb.Append(", ").Append(kv.Key); if (value != null) { sb.Append(" = '").Append(kv.Value).Append('\''); } else { sb.Append(" = NULL"); } } return sb.Append('}').__ToStringRecycle(); } System.Dynamic.DynamicMetaObject System.Dynamic.IDynamicMetaObjectProvider.GetMetaObject( System.Linq.Expressions.Expression parameter) { return new DapperRowMetaObject(parameter, System.Dynamic.BindingRestrictions.Empty, this); } public IEnumerator<KeyValuePair<string, object>> GetEnumerator() { var names = table.FieldNames; for (var i = 0; i < names.Length; i++) { object value = i < values.Length ? values[i] : null; if (!(value is DeadValue)) { yield return new KeyValuePair<string, object>(names[i], value); } } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } #region Implementation of ICollection<KeyValuePair<string,object>> void ICollection<KeyValuePair<string, object>>.Add(KeyValuePair<string, object> item) { IDictionary<string, object> dic = this; dic.Add(item.Key, item.Value); } void ICollection<KeyValuePair<string, object>>.Clear() { // removes values for **this row**, but doesn't change the fundamental table for (int i = 0; i < values.Length; i++) values[i] = DeadValue.Default; } bool ICollection<KeyValuePair<string, object>>.Contains(KeyValuePair<string, object> item) { return TryGetValue(item.Key, out object value) && Equals(value, item.Value); } void ICollection<KeyValuePair<string, object>>.CopyTo(KeyValuePair<string, object>[] array, int arrayIndex) { foreach (var kv in this) { array[arrayIndex++] = kv; // if they didn't leave enough space; not our fault } } bool ICollection<KeyValuePair<string, object>>.Remove(KeyValuePair<string, object> item) { IDictionary<string, object> dic = this; return dic.Remove(item.Key); } bool ICollection<KeyValuePair<string, object>>.IsReadOnly => false; #endregion #region Implementation of IDictionary<string,object> bool IDictionary<string, object>.ContainsKey(string key) { int index = table.IndexOfName(key); if (index < 0 || index >= values.Length || values[index] is DeadValue) return false; return true; } void IDictionary<string, object>.Add(string key, object value) { SetValue(key, value, true); } bool IDictionary<string, object>.Remove(string key) { int index = table.IndexOfName(key); if (index < 0 || index >= values.Length || values[index] is DeadValue) return false; values[index] = DeadValue.Default; return true; } object IDictionary<string, object>.this[string key] { get { TryGetValue(key, out object val); return val; } set { SetValue(key, value, false); } } public object SetValue(string key, object value) { return SetValue(key, value, false); } private object SetValue(string key, object value, bool isAdd) { if (key == null) throw new ArgumentNullException(nameof(key)); int index = table.IndexOfName(key); if (index < 0) { index = table.AddField(key); } else if (isAdd && index < values.Length && !(values[index] is DeadValue)) { // then semantically, this value already exists throw new ArgumentException("An item with the same key has already been added", nameof(key)); } int oldLength = values.Length; if (oldLength <= index) { // we'll assume they're doing lots of things, and // grow it to the full width of the table Array.Resize(ref values, table.FieldCount); for (int i = oldLength; i < values.Length; i++) { values[i] = DeadValue.Default; } } return values[index] = value; } ICollection<string> IDictionary<string, object>.Keys { get { return this.Select(kv => kv.Key).ToArray(); } } ICollection<object> IDictionary<string, object>.Values { get { return this.Select(kv => kv.Value).ToArray(); } } #endregion #region Implementation of IReadOnlyDictionary<string,object> int IReadOnlyCollection<KeyValuePair<string, object>>.Count { get { return values.Count(t => !(t is DeadValue)); } } bool IReadOnlyDictionary<string, object>.ContainsKey(string key) { int index = table.IndexOfName(key); return index >= 0 && index < values.Length && !(values[index] is DeadValue); } object IReadOnlyDictionary<string, object>.this[string key] { get { TryGetValue(key, out object val); return val; } } IEnumerable<string> IReadOnlyDictionary<string, object>.Keys { get { return this.Select(kv => kv.Key); } } IEnumerable<object> IReadOnlyDictionary<string, object>.Values { get { return this.Select(kv => kv.Value); } } #endregion } } }
35.34
119
0.479457
[ "MIT" ]
DimChumHaul/TingRUI.PCV3
Src/Lib/Orm/ServiceStack.OrmLite-V5.5/Dapper/SqlMapper.DapperRow.cs
8,837
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace LoRaWan.Tests.E2E { using System; using System.Globalization; using System.Threading.Tasks; using LoRaWan.Tests.Common; using Xunit; using XunitRetryHelper; // Tests ABP requests [Collection(Constants.TestCollectionName)] // run in serial [Trait("Category", "SkipWhenLiveUnitTesting")] public sealed class ABPTest : IntegrationTestBaseCi { public ABPTest(IntegrationTestFixtureCi testFixture) : base(testFixture) { } [RetryFact] public Task Test_ABP_Confirmed_And_Unconfirmed_Message_With_ADR_Single() { return Test_ABP_Confirmed_And_Unconfirmed_Message_With_ADR(nameof(TestFixtureCi.Device5_ABP)); } [RetryFact] public Task Test_ABP_Confirmed_And_Unconfirmed_Message_With_ADR_MultiGw() { return Test_ABP_Confirmed_And_Unconfirmed_Message_With_ADR(nameof(TestFixtureCi.Device5_ABP_MultiGw)); } // Verifies that ABP confirmed and unconfirmed messages are working // Uses Device5_ABP private async Task Test_ABP_Confirmed_And_Unconfirmed_Message_With_ADR(string devicePropertyName) { var device = TestFixtureCi.GetDeviceByPropertyName(devicePropertyName); if (device.IsMultiGw) { Assert.True(await LoRaAPIHelper.ResetADRCache(device.DeviceID)); } await ArduinoDevice.setDeviceDefaultAsync(); const int MESSAGES_COUNT = 10; LogTestStart(device); await ArduinoDevice.setDeviceModeAsync(LoRaArduinoSerial._device_mode_t.LWABP); await ArduinoDevice.setIdAsync(device.DevAddr, device.DeviceID, null); await ArduinoDevice.setKeyAsync(device.NwkSKey, device.AppSKey, null); await ArduinoDevice.SetupLora(TestFixtureCi.Configuration.LoraRegion, LoRaArduinoSerial._data_rate_t.DR3, 4, true); // for a reason I need to set DR twice otherwise it reverts to DR 0 // await ArduinoDevice.setDataRateAsync(LoRaArduinoSerial._data_rate_t.DR3, LoRaArduinoSerial._physical_type_t.EU868); // Sends 5x unconfirmed messages for (var i = 0; i < MESSAGES_COUNT / 2; ++i) { var msg = GeneratePayloadMessage(); Log($"{device.DeviceID}: Sending unconfirmed '{msg}' {i + 1}/{MESSAGES_COUNT}"); await ArduinoDevice.transferPacketAsync(msg, 10); await Task.Delay(Constants.DELAY_BETWEEN_MESSAGES); // After transferPacket: Expectation from serial // +MSG: Done await AssertUtils.ContainsWithRetriesAsync("+MSG: Done", ArduinoDevice.SerialLogs); // 0000000000000005: valid frame counter, msg: 1 server: 0 await TestFixtureCi.AssertNetworkServerModuleLogStartsWithAsync($"{device.DeviceID}: valid frame counter, msg:"); // 0000000000000005: decoding with: DecoderValueSensor port: 8 await TestFixtureCi.AssertNetworkServerModuleLogStartsWithAsync($"{device.DeviceID}: decoding with: {device.SensorDecoder} port:"); // 0000000000000005: message '{"value": 51}' sent to hub await TestFixtureCi.AssertNetworkServerModuleLogStartsWithAsync($"{device.DeviceID}: message '{{\"value\":{msg}}}' sent to hub"); TestFixtureCi.ClearLogs(); } // Sends 5x confirmed messages for (var i = 0; i < MESSAGES_COUNT / 2; ++i) { var msg = GeneratePayloadMessage(); Log($"{device.DeviceID}: Sending confirmed '{msg}' {i + 1}/{MESSAGES_COUNT / 2}"); await ArduinoDevice.transferPacketWithConfirmedAsync(msg, 10); await Task.Delay(2 * Constants.DELAY_BETWEEN_MESSAGES); // After transferPacketWithConfirmed: Expectation from serial // +CMSG: ACK Received await AssertUtils.ContainsWithRetriesAsync("+CMSG: ACK Received", ArduinoDevice.SerialLogs); // 0000000000000005: valid frame counter, msg: 1 server: 0 await TestFixtureCi.AssertNetworkServerModuleLogStartsWithAsync($"{device.DeviceID}: valid frame counter, msg:"); // 0000000000000005: decoding with: DecoderValueSensor port: 8 await TestFixtureCi.AssertNetworkServerModuleLogStartsWithAsync($"{device.DeviceID}: decoding with: {device.SensorDecoder} port:"); // 0000000000000005: message '{"value": 51}' sent to hub await TestFixtureCi.AssertNetworkServerModuleLogStartsWithAsync($"{device.DeviceID}: message '{{\"value\":{msg}}}' sent to hub"); if (device.IsMultiGw) { var searchTokenSending = $"{device.DeviceID}: sending a downstream message"; var sending = await TestFixtureCi.SearchNetworkServerModuleAsync((log) => log.StartsWith(searchTokenSending, StringComparison.OrdinalIgnoreCase)); Assert.NotNull(sending.MatchedEvent); var searchTokenAlreadySent = $"{device.DeviceID}: another gateway has already sent ack or downlink msg"; var ignored = await TestFixtureCi.SearchNetworkServerModuleAsync((log) => log.StartsWith(searchTokenAlreadySent, StringComparison.OrdinalIgnoreCase)); Assert.NotNull(ignored.MatchedEvent); Assert.NotEqual(sending.MatchedEvent.SourceId, ignored.MatchedEvent.SourceId); } TestFixtureCi.ClearLogs(); } // Sends 10x unconfirmed messages for (var i = 0; i < MESSAGES_COUNT; ++i) { var msg = GeneratePayloadMessage(); Log($"{device.DeviceID}: Sending unconfirmed '{msg}' {i + 1}/{MESSAGES_COUNT / 2}"); await ArduinoDevice.transferPacketAsync(msg, 10); await Task.Delay(Constants.DELAY_BETWEEN_MESSAGES); // After transferPacket: Expectation from serial // +MSG: Done await AssertUtils.ContainsWithRetriesAsync("+MSG: Done", ArduinoDevice.SerialLogs); // 0000000000000005: valid frame counter, msg: 1 server: 0 await TestFixtureCi.AssertNetworkServerModuleLogStartsWithAsync($"{device.DeviceID}: valid frame counter, msg:"); // 0000000000000005: decoding with: DecoderValueSensor port: 8 await TestFixtureCi.AssertNetworkServerModuleLogStartsWithAsync($"{device.DeviceID}: decoding with: {device.SensorDecoder} port:"); // 0000000000000005: message '{"value": 51}' sent to hub await TestFixtureCi.AssertNetworkServerModuleLogStartsWithAsync($"{device.DeviceID}: message '{{\"value\":{msg}}}' sent to hub"); TestFixtureCi.ClearLogs(); } // Starting ADR test protocol Log($"{device.DeviceID}: Starting ADR protocol"); for (var i = 0; i < 56; ++i) { var message = GeneratePayloadMessage(); await ArduinoDevice.transferPacketAsync(message, 10); await Task.Delay(Constants.DELAY_BETWEEN_MESSAGES); await AssertUtils.ContainsWithRetriesAsync("+MSG: Done", ArduinoDevice.SerialLogs); } await Task.Delay(Constants.DELAY_BETWEEN_MESSAGES); await TestFixtureCi.AssertNetworkServerModuleLogStartsWithAsync($"{device.DeviceID}: ADR ack request received"); var searchTokenADRRateAdaptation = $"{device.DeviceID}: performing a rate adaptation: DR"; var received = await TestFixtureCi.SearchNetworkServerModuleAsync((log) => log.StartsWith(searchTokenADRRateAdaptation, StringComparison.OrdinalIgnoreCase)); Assert.NotNull(received.MatchedEvent); if (device.IsMultiGw) { var searchTokenADRAlreadySent = $"{device.DeviceID}: another gateway has already sent ack or downlink msg"; var ignored = await TestFixtureCi.SearchNetworkServerModuleAsync((log) => log.StartsWith(searchTokenADRAlreadySent, StringComparison.OrdinalIgnoreCase)); Assert.NotNull(ignored.MatchedEvent); Assert.NotEqual(received.MatchedEvent.SourceId, ignored.MatchedEvent.SourceId); } // Check the messages are now sent on DR5 for (var i = 0; i < 2; ++i) { var message = GeneratePayloadMessage(); await ArduinoDevice.transferPacketAsync(message, 10); await Task.Delay(Constants.DELAY_BETWEEN_MESSAGES); await AssertUtils.ContainsWithRetriesAsync("+MSG: Done", ArduinoDevice.SerialLogs); await TestFixtureCi.AssertNetworkServerModuleLogStartsWithAsync($"{device.DevAddr}: LinkADRCmd mac command detected in upstream payload: Type: LinkADRCmd Answer, power: changed, data rate: changed,", $"{device.DevAddr}: LinkADRCmd mac command detected in upstream payload: Type: LinkADRCmd Answer, power: not changed, data rate: changed,"); } } [RetryFact] public Task Test_ABP_Wrong_DevAddr_Is_Ignored_05060708() { return Test_ABP_Wrong_DevAddr_Is_Ignored("05060708"); } [RetryFact] public Task Test_ABP_Wrong_DevAddr_Is_Ignored_02060708() { return Test_ABP_Wrong_DevAddr_Is_Ignored("02060708"); } // Verifies that ABP using wrong devAddr is ignored when sending messages // Uses Device6_ABP private async Task Test_ABP_Wrong_DevAddr_Is_Ignored(string devAddrToUse) { var device = TestFixtureCi.Device6_ABP; LogTestStart(device); Assert.NotEqual(devAddrToUse, device.DevAddr); await ArduinoDevice.setDeviceModeAsync(LoRaArduinoSerial._device_mode_t.LWABP); await ArduinoDevice.setIdAsync(devAddrToUse, device.DeviceID, null); await ArduinoDevice.setKeyAsync(device.NwkSKey, device.AppSKey, null); await ArduinoDevice.SetupLora(TestFixtureCi.Configuration.LoraRegion); await ArduinoDevice.transferPacketAsync(GeneratePayloadMessage(), 10); await Task.Delay(Constants.DELAY_FOR_SERIAL_AFTER_SENDING_PACKET); // After transferPacket: Expectation from serial // +MSG: Done await AssertUtils.ContainsWithRetriesAsync("+MSG: Done", ArduinoDevice.SerialLogs); if (devAddrToUse.StartsWith("02", StringComparison.Ordinal)) { // 02060708: device is not our device, ignore message await TestFixtureCi.AssertNetworkServerModuleLogStartsWithAsync( $"{devAddrToUse}: device is not our device, ignore message", $"{devAddrToUse}: device is not from our network, ignoring message"); } else { // 05060708: device is using another network id, ignoring this message await TestFixtureCi.AssertNetworkServerModuleLogStartsWithAsync( $"{devAddrToUse}: device is using another network id, ignoring this message"); } await Task.Delay(Constants.DELAY_BETWEEN_MESSAGES); TestFixtureCi.ClearLogs(); // Try with confirmed message await ArduinoDevice.transferPacketWithConfirmedAsync(GeneratePayloadMessage(), 10); // wait for serial logs to be ready await Task.Delay(Constants.DELAY_FOR_SERIAL_AFTER_SENDING_PACKET); // After transferPacketWithConfirmed: Expectation from serial // +CMSG: ACK Received -- should not be there! Assert.DoesNotContain("+CMSG: ACK Received", ArduinoDevice.SerialLogs); if (devAddrToUse.StartsWith("02", StringComparison.Ordinal)) { // 02060708: device is not our device, ignore message await TestFixtureCi.AssertNetworkServerModuleLogStartsWithAsync( $"{devAddrToUse}: device is not our device, ignore message", $"{devAddrToUse}: device is not from our network, ignoring message"); } else { // 05060708: device is using another network id, ignoring this message await TestFixtureCi.AssertNetworkServerModuleLogStartsWithAsync( $"{devAddrToUse}: device is using another network id, ignoring this message"); } } // Tests using a incorrect Network Session key, resulting device not ours // AppSKey="2B7E151628AED2A6ABF7158809CF4F3C", // NwkSKey="3B7E151628AED2A6ABF7158809CF4F3C", // DevAddr="0028B1B2" // Uses Device7_ABP [RetryFact] public async Task Test_ABP_Mismatch_NwkSKey_And_AppSKey_Fails_Mic_Validation() { var device = TestFixtureCi.Device7_ABP; LogTestStart(device); var appSKeyToUse = "000102030405060708090A0B0C0D0E0F"; var nwkSKeyToUse = "01020304050607080910111213141516"; Assert.NotEqual(appSKeyToUse, device.AppSKey); Assert.NotEqual(nwkSKeyToUse, device.NwkSKey); await ArduinoDevice.setDeviceModeAsync(LoRaArduinoSerial._device_mode_t.LWABP); await ArduinoDevice.setIdAsync(device.DevAddr, device.DeviceID, null); await ArduinoDevice.setKeyAsync(nwkSKeyToUse, appSKeyToUse, null); await ArduinoDevice.SetupLora(TestFixtureCi.Configuration.LoraRegion); await ArduinoDevice.transferPacketAsync(GeneratePayloadMessage(), 10); // wait for serial logs to be ready await Task.Delay(Constants.DELAY_FOR_SERIAL_AFTER_SENDING_PACKET); // After transferPacket: Expectation from serial // +MSG: Done // await AssertUtils.ContainsWithRetriesAsync("+MSG: Done", this.lora.SerialLogs); // 0000000000000005: with devAddr 0028B1B0 check MIC failed. Device will be ignored from now on await TestFixtureCi.AssertNetworkServerModuleLogStartsWithAsync($"{device.DevAddr}: with devAddr {device.DevAddr} check MIC failed"); await Task.Delay(Constants.DELAY_BETWEEN_MESSAGES); TestFixtureCi.ClearLogs(); // Try with confirmed message await ArduinoDevice.transferPacketWithConfirmedAsync(GeneratePayloadMessage(), 10); await Task.Delay(Constants.DELAY_FOR_SERIAL_AFTER_SENDING_PACKET); // 0000000000000005: with devAddr 0028B1B0 check MIC failed await TestFixtureCi.AssertNetworkServerModuleLogStartsWithAsync($"{device.DevAddr}: with devAddr {device.DevAddr} check MIC failed"); // wait until arduino stops trying to send confirmed msg await ArduinoDevice.WaitForIdleAsync(); } // Tests using a invalid Network Session key, resulting in mic failed // Uses Device8_ABP [RetryFact] public async Task Test_ABP_Invalid_NwkSKey_Fails_With_Mic_Error() { var device = TestFixtureCi.Device8_ABP; LogTestStart(device); var nwkSKeyToUse = "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"; Assert.NotEqual(nwkSKeyToUse, device.NwkSKey); await ArduinoDevice.setDeviceModeAsync(LoRaArduinoSerial._device_mode_t.LWABP); await ArduinoDevice.setIdAsync(device.DevAddr, device.DeviceID, null); await ArduinoDevice.setKeyAsync(nwkSKeyToUse, device.AppSKey, null); await ArduinoDevice.SetupLora(TestFixtureCi.Configuration.LoraRegion); await ArduinoDevice.transferPacketAsync(GeneratePayloadMessage(), 10); await Task.Delay(Constants.DELAY_BETWEEN_MESSAGES); // After transferPacket: Expectation from serial // +MSG: Done await AssertUtils.ContainsWithRetriesAsync("+MSG: Done", ArduinoDevice.SerialLogs); // 0000000000000008: with devAddr 0028B1B3 check MIC failed. Device will be ignored from now on await TestFixtureCi.AssertNetworkServerModuleLogStartsWithAsync($"{device.DevAddr}: with devAddr {device.DevAddr} check MIC failed"); TestFixtureCi.ClearLogs(); // Try with confirmed message await ArduinoDevice.transferPacketWithConfirmedAsync(GeneratePayloadMessage(), 10); await Task.Delay(Constants.DELAY_BETWEEN_MESSAGES); // 0000000000000008: with devAddr 0028B1B3 check MIC failed. await TestFixtureCi.AssertNetworkServerModuleLogStartsWithAsync($"{device.DevAddr}: with devAddr {device.DevAddr} check MIC failed"); // Before starting new test, wait until Lora drivers stops sending/receiving data await ArduinoDevice.WaitForIdleAsync(); } // Verifies that ABP confirmed and unconfirmed messages are working // Uses Device16_ABP and Device17_ABP [RetryFact] public async Task Test_ABP_Device_With_Same_DevAddr() { const int MESSAGES_COUNT = 2; LogTestStart(new TestDeviceInfo[] { TestFixtureCi.Device16_ABP, TestFixtureCi.Device17_ABP }); await SendABPMessages(MESSAGES_COUNT, TestFixtureCi.Device16_ABP); await SendABPMessages(MESSAGES_COUNT, TestFixtureCi.Device17_ABP); } private async Task SendABPMessages(int messages_count, TestDeviceInfo device) { await ArduinoDevice.setDeviceModeAsync(LoRaArduinoSerial._device_mode_t.LWABP); await ArduinoDevice.setIdAsync(device.DevAddr, device.DeviceID, null); await ArduinoDevice.setKeyAsync(device.NwkSKey, device.AppSKey, null); await ArduinoDevice.SetupLora(TestFixtureCi.Configuration.LoraRegion); // Sends 10x unconfirmed messages for (var i = 0; i < messages_count; ++i) { var msg = GeneratePayloadMessage(); Log($"{device.DeviceID}: Sending unconfirmed '{msg}' {i + 1}/{messages_count}"); await ArduinoDevice.transferPacketAsync(msg, 10); await Task.Delay(Constants.DELAY_BETWEEN_MESSAGES); // After transferPacket: Expectation from serial // +MSG: Done await AssertUtils.ContainsWithRetriesAsync("+MSG: Done", ArduinoDevice.SerialLogs); // 0000000000000005: valid frame counter, msg: 1 server: 0 await TestFixtureCi.AssertNetworkServerModuleLogStartsWithAsync($"{device.DeviceID}: valid frame counter, msg:"); // 0000000000000005: decoding with: DecoderValueSensor port: 8 await TestFixtureCi.AssertNetworkServerModuleLogStartsWithAsync($"{device.DeviceID}: decoding with: {device.SensorDecoder} port:"); // 0000000000000005: message '{"value": 51}' sent to hub await TestFixtureCi.AssertNetworkServerModuleLogStartsWithAsync($"{device.DeviceID}: message '{{\"value\":{msg}}}' sent to hub"); TestFixtureCi.ClearLogs(); } // Sends 10x confirmed messages for (var i = 0; i < messages_count; ++i) { var msg = GeneratePayloadMessage(); Log($"{device.DeviceID}: Sending confirmed '{msg}' {i + 1}/{messages_count}"); await ArduinoDevice.transferPacketWithConfirmedAsync(msg, 10); await Task.Delay(Constants.DELAY_BETWEEN_MESSAGES); // After transferPacketWithConfirmed: Expectation from serial // +CMSG: ACK Received await AssertUtils.ContainsWithRetriesAsync("+CMSG: ACK Received", ArduinoDevice.SerialLogs); // 0000000000000005: valid frame counter, msg: 1 server: 0 await TestFixtureCi.AssertNetworkServerModuleLogStartsWithAsync($"{device.DeviceID}: valid frame counter, msg:"); // 0000000000000005: decoding with: DecoderValueSensor port: 8 await TestFixtureCi.AssertNetworkServerModuleLogStartsWithAsync($"{device.DeviceID}: decoding with: {device.SensorDecoder} port:"); // 0000000000000005: message '{"value": 51}' sent to hub await TestFixtureCi.AssertNetworkServerModuleLogStartsWithAsync($"{device.DeviceID}: message '{{\"value\":{msg}}}' sent to hub"); TestFixtureCi.ClearLogs(); } } // Verifies that ABP confirmed and unconfirmed messages are working // Uses Device25_ABP and Device26_ABP [RetryFact] public async Task Test_ABP_Device_With_Connection_Timeout() { LogTestStart(new TestDeviceInfo[] { TestFixtureCi.Device25_ABP, TestFixtureCi.Device26_ABP }); // Sends 1 message from device 25 var device25 = TestFixtureCi.Device25_ABP; await ArduinoDevice.setDeviceModeAsync(LoRaArduinoSerial._device_mode_t.LWABP); await ArduinoDevice.setIdAsync(device25.DevAddr, device25.DeviceID, null); await ArduinoDevice.setKeyAsync(device25.NwkSKey, device25.AppSKey, null); await ArduinoDevice.SetupLora(TestFixtureCi.Configuration.LoraRegion); await ArduinoDevice.transferPacketAsync(GeneratePayloadMessage(), 10); await TestFixtureCi.SearchNetworkServerModuleAsync((log) => log.StartsWith($"{device25.DeviceID}: processing time", StringComparison.Ordinal)); // wait 61 seconds await Task.Delay(TimeSpan.FromSeconds(120)); // Send 1 message from device 26 var device26 = TestFixtureCi.Device26_ABP; await ArduinoDevice.setDeviceModeAsync(LoRaArduinoSerial._device_mode_t.LWABP); await ArduinoDevice.setIdAsync(device26.DevAddr, device26.DeviceID, null); await ArduinoDevice.setKeyAsync(device26.NwkSKey, device26.AppSKey, null); await ArduinoDevice.SetupLora(TestFixtureCi.Configuration.LoraRegion); await ArduinoDevice.transferPacketAsync(GeneratePayloadMessage(), 10); await Task.Delay(Constants.DELAY_BETWEEN_MESSAGES); var result = await TestFixtureCi.SearchNetworkServerModuleAsync( msg => msg.StartsWith($"{device25.DeviceID}: device client disconnected", StringComparison.Ordinal), new SearchLogOptions { MaxAttempts = 10, SourceIdFilter = device25.GatewayID }); Assert.NotNull(result.MatchedEvent); TestFixtureCi.ClearLogs(); // Send 1 message from device 25 and check that connection was restablished await ArduinoDevice.setDeviceModeAsync(LoRaArduinoSerial._device_mode_t.LWABP); await ArduinoDevice.setIdAsync(device25.DevAddr, device25.DeviceID, null); await ArduinoDevice.setKeyAsync(device25.NwkSKey, device25.AppSKey, null); await ArduinoDevice.SetupLora(TestFixtureCi.Configuration.LoraRegion); var expectedMessage = GeneratePayloadMessage(); await ArduinoDevice.transferPacketAsync(expectedMessage, 10); // After transferPacket: Expectation from serial // +MSG: Done await AssertUtils.ContainsWithRetriesAsync("+MSG: Done", ArduinoDevice.SerialLogs); // 0000000000000005: message '{"value": 51}' sent to hub await TestFixtureCi.AssertNetworkServerModuleLogStartsWithAsync($"{device25.DeviceID}: message '{{\"value\":{expectedMessage}}}' sent to hub"); // "device client reconnected" await TestFixtureCi.AssertNetworkServerModuleLogStartsWithAsync($"{device25.DeviceID}: device client reconnected"); } private static string GeneratePayloadMessage() => PayloadGenerator.Next().ToString(CultureInfo.InvariantCulture); } }
50.084362
356
0.655561
[ "MIT" ]
Mandur/iotedge-lorawan-starterk
Tests/E2E/ABPTest.cs
24,341
C#
 using Contensive.Models.Db; using Contensive.Processor; using Contensive.Processor.Controllers; using Contensive.Processor.Models.Domain; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Linq; using static Tests.TestConstants; namespace Tests { [TestClass] public class EmailControllerTests { // [TestMethod] public void processConditional_DaysBeforeExpire_Test() { using (CPClass cp = new(testAppName)) { // // arrange, now = 1/1/2020 at 12:00 am cp.core.mockEmail = true; DbBaseModel.deleteRows<SystemEmailModel>(cp, ""); DbBaseModel.deleteRows<ConditionalEmailModel>(cp, ""); DbBaseModel.deleteRows<GroupEmailModel>(cp, ""); Assert.AreEqual(0, cp.core.mockEmailList.Count); cp.core.mockDateTimeNow(new DateTime(2020, 1, 1, 0, 0, 0)); // // -- group GroupModel group = DbBaseModel.addDefault<GroupModel>(cp); group.name = "DaysAfterJoiningGroup"; group.caption = "DaysAfterJoiningGroup"; group.ccguid = "{1234-1243-1234-1234}"; group.save(cp); // // -- person PersonModel person = DbBaseModel.addDefault<PersonModel>(cp); person.name = "user"; person.email = "test@test.com"; person.save(cp); // // -- join 1/1/2020 at 12:00 am, expire from group in 10 days later, 1/10/2020 at 12:00 am cp.Group.AddUser(group.id, person.id, ((DateTime)cp.core.dateTimeNowMockable).AddDays(10)); // // -- setup conditional email, send 5 days before group expiration, so send after 1/5/2020 12:00am and before 1/6/2020 12:00am ConditionalEmailModel email = DbBaseModel.addDefault<ConditionalEmailModel>(cp); email.name = "ConditionalEmailTest"; email.subject = "ConditionalEmailTest-subject"; email.testMemberId = 0; email.conditionExpireDate = null; email.conditionPeriod = 5; email.fromAddress = "ConditionalEmailTest@kma.net"; email.conditionId = 1; email.submitted = true; email.save(cp); // // -- setup email-group, associating this email to the EmailGroupModel rule = DbBaseModel.addDefault<EmailGroupModel>(cp); rule.emailId = email.id; rule.groupId = group.id; rule.save(cp); // // act/asset EmailController.processConditionalEmail(cp.core); Assert.AreEqual(0, cp.core.mockEmailList.Count); // // 1/1/2020 at noon cp.core.mockDateTimeNow(cp.Utils.GetDateTimeMockable().AddDays(0.5)); Assert.AreEqual(0, EmailController.processConditionalEmail(cp.core)); // // 1/2/2020 at noon cp.core.mockDateTimeNow(cp.Utils.GetDateTimeMockable().AddDays(1)); Assert.AreEqual(0, EmailController.processConditionalEmail(cp.core)); // // 1/3/2020 at noon cp.core.mockDateTimeNow(cp.Utils.GetDateTimeMockable().AddDays(1)); Assert.AreEqual(0, EmailController.processConditionalEmail(cp.core)); // // 1/4/2020 at noon cp.core.mockDateTimeNow(cp.Utils.GetDateTimeMockable().AddDays(1)); Assert.AreEqual(0, EmailController.processConditionalEmail(cp.core)); // // 1/5/2020 at noon cp.core.mockDateTimeNow(cp.Utils.GetDateTimeMockable().AddDays(1)); Assert.AreEqual(0, EmailController.processConditionalEmail(cp.core)); // // 1/6/2020 at noon, must send one. If others are in the system, it cp.core.mockDateTimeNow(cp.Utils.GetDateTimeMockable().AddDays(1)); Assert.AreEqual(1, EmailController.processConditionalEmail(cp.core)); // // 1/7/2020 at noon cp.core.mockDateTimeNow(cp.Utils.GetDateTimeMockable().AddDays(1)); Assert.AreEqual(0, EmailController.processConditionalEmail(cp.core)); } } // [TestMethod] public void controllers_Email_GetBlockedList_test1() { using (CPClass cp = new(testAppName)) { cp.core.mockEmail = true; DbBaseModel.deleteRows<SystemEmailModel>(cp, ""); DbBaseModel.deleteRows<ConditionalEmailModel>(cp, ""); DbBaseModel.deleteRows<GroupEmailModel>(cp, ""); Assert.AreEqual(0, cp.core.mockEmailList.Count); // arrange string test1 = GenericController.getRandomInteger(cp.core).ToString() + "@kma.net"; string test2 = GenericController.getRandomInteger(cp.core).ToString() + "@kma.net"; // act EmailController.addToBlockList(cp.core, test1); string blockList = Contensive.Processor.Controllers.EmailController.getBlockList(cp.core); // assert Assert.IsTrue(EmailController.isOnBlockedList(cp.core, test1)); Assert.IsFalse(EmailController.isOnBlockedList(cp.core, test2)); } } // [TestMethod] public void controllers_Email_VerifyEmailAddress_test1() { using (CPClass cp = new(testAppName)) { cp.core.mockEmail = true; DbBaseModel.deleteRows<SystemEmailModel>(cp, ""); DbBaseModel.deleteRows<ConditionalEmailModel>(cp, ""); DbBaseModel.deleteRows<GroupEmailModel>(cp, ""); Assert.AreEqual(0, cp.core.mockEmailList.Count); // arrange // act // assert Assert.IsFalse(EmailController.verifyEmailAddress(cp.core, "123")); Assert.IsFalse(EmailController.verifyEmailAddress(cp.core, "123@")); Assert.IsFalse(EmailController.verifyEmailAddress(cp.core, "123@2")); Assert.IsFalse(EmailController.verifyEmailAddress(cp.core, "123@2.")); Assert.IsTrue(EmailController.verifyEmailAddress(cp.core, "123@2.com")); } } // [TestMethod] public void controllers_Email_queueAdHocEmail_test1() { using (CPClass cp = new(testAppName)) { cp.core.mockEmail = true; DbBaseModel.deleteRows<SystemEmailModel>(cp, ""); DbBaseModel.deleteRows<ConditionalEmailModel>(cp, ""); DbBaseModel.deleteRows<GroupEmailModel>(cp, ""); Assert.AreEqual(0, cp.core.mockEmailList.Count); // arrange string body = GenericController.getRandomInteger(cp.core).ToString(); string sendStatus = ""; string ResultLogFilename = ""; // act EmailController.queueAdHocEmail(cp.core, "Unit Test", 0, "to@kma.net", "from@kma.net", "subject", body, "bounce@kma.net", "replyTo@kma.net", ResultLogFilename, true, true, 0, ref sendStatus); Contensive.BaseClasses.AddonBaseClass addon = new Contensive.Processor.Addons.Email.ProcessEmailClass(); addon.Execute(cp); // assert Assert.AreEqual(1, cp.core.mockEmailList.Count); MockEmailClass sentEmail = cp.core.mockEmailList.First(); Assert.IsTrue(string.IsNullOrEmpty(sentEmail.AttachmentFilename)); Assert.AreEqual("to@kma.net", getEmailPart(sentEmail.email.toAddress)); Assert.AreEqual("from@kma.net", getEmailPart(sentEmail.email.fromAddress)); Assert.AreEqual("bounce@kma.net", getEmailPart(sentEmail.email.bounceAddress)); Assert.AreEqual("replyTo@kma.net", getEmailPart(sentEmail.email.replyToAddress)); Assert.AreEqual("subject", sentEmail.email.subject); Assert.AreEqual(body, sentEmail.email.textBody); } } // [TestMethod] public void controllers_Email_queuePersonEmail_test1() { using (CPClass cp = new(testAppName)) { cp.core.mockEmail = true; DbBaseModel.deleteRows<SystemEmailModel>(cp, ""); DbBaseModel.deleteRows<ConditionalEmailModel>(cp, ""); DbBaseModel.deleteRows<GroupEmailModel>(cp, ""); Assert.AreEqual(0, cp.core.mockEmailList.Count); // arrange string body = GenericController.getRandomInteger(cp.core).ToString(); var toPerson = DbBaseModel.addDefault<PersonModel>(cp, ContentMetadataModel.getDefaultValueDict(cp.core, PersonModel.tableMetadata.contentName)); Assert.IsNotNull(toPerson); toPerson.email = GenericController.getRandomInteger(cp.core).ToString() + "@kma.net"; toPerson.firstName = GenericController.getRandomInteger(cp.core).ToString(); toPerson.lastName = GenericController.getRandomInteger(cp.core).ToString(); toPerson.save(cp); string sendStatus = ""; // act Assert.IsTrue(EmailController.tryQueuePersonEmail(cp.core, "Function Test", toPerson, "from@kma.net", "subject", body, "bounce@kma.net", "replyTo@kma.net", true, true, 0, "", true, ref sendStatus)); Contensive.BaseClasses.AddonBaseClass addon = new Contensive.Processor.Addons.Email.ProcessEmailClass(); addon.Execute(cp); // assert Assert.AreEqual(1, cp.core.mockEmailList.Count); MockEmailClass sentEmail = cp.core.mockEmailList.First(); Assert.IsTrue(string.IsNullOrEmpty(sentEmail.AttachmentFilename)); Assert.AreEqual(toPerson.email, getEmailPart(sentEmail.email.toAddress)); Assert.AreEqual("from@kma.net", getEmailPart(sentEmail.email.fromAddress)); Assert.AreEqual("bounce@kma.net", getEmailPart(sentEmail.email.bounceAddress)); Assert.AreEqual("replyTo@kma.net", getEmailPart(sentEmail.email.replyToAddress)); Assert.AreEqual("subject", sentEmail.email.subject); Assert.AreEqual(body, sentEmail.email.textBody); } } // private string getEmailPart(string FriendlyEmailAddress) { if (string.IsNullOrEmpty(FriendlyEmailAddress)) return FriendlyEmailAddress; if (!FriendlyEmailAddress.Contains('<') || !FriendlyEmailAddress.Contains('>')) return FriendlyEmailAddress; int posStart = FriendlyEmailAddress.IndexOf('<'); int posEnd = FriendlyEmailAddress.IndexOf('>'); if (posStart > posEnd) return FriendlyEmailAddress; return FriendlyEmailAddress.Substring(posStart + 1, posEnd - posStart-1); } // [TestMethod] public void controllers_Email_queueSystemEmail_test1() { using (CPClass cp = new(testAppName)) { cp.core.mockEmail = true; // arrange string htmlBody = "a<b>1</b><br>2<p>3</p><div>4</div>"; // var confirmPerson = DbBaseModel.addDefault<PersonModel>(cp); Assert.IsNotNull(confirmPerson); confirmPerson.email = GenericController.getRandomInteger(cp.core).ToString() + "@kma.net"; confirmPerson.firstName = GenericController.getRandomInteger(cp.core).ToString(); confirmPerson.lastName = GenericController.getRandomInteger(cp.core).ToString(); confirmPerson.save(cp); // SystemEmailModel systemEmail = DbBaseModel.addDefault<SystemEmailModel>(cp); systemEmail.name = "system email test " + cp.Utils.GetRandomInteger(); systemEmail.addLinkEId = false; systemEmail.allowSpamFooter = false; systemEmail.emailTemplateId = 0; systemEmail.fromAddress = GenericController.getRandomInteger(cp.core).ToString() + "@kma.net"; systemEmail.subject = htmlBody; systemEmail.copyFilename.content = systemEmail.subject; systemEmail.testMemberId = confirmPerson.id; systemEmail.save(cp); // var toPerson = DbBaseModel.addDefault<PersonModel>(cp); Assert.IsNotNull(toPerson); toPerson.email = GenericController.getRandomInteger(cp.core).ToString() + "@kma.net"; toPerson.firstName = GenericController.getRandomInteger(cp.core).ToString(); toPerson.lastName = GenericController.getRandomInteger(cp.core).ToString(); toPerson.save(cp); // var group = DbBaseModel.addDefault<GroupModel>(cp); group.name = "test group " + cp.Utils.GetRandomInteger(); group.save(cp); // cp.Group.AddUser(group.id, toPerson.id); // var emailGroup = DbBaseModel.addDefault<Contensive.Models.Db.EmailGroupModel>(cp); emailGroup.groupId = group.id; emailGroup.emailId = systemEmail.id; emailGroup.save(cp); // act string userErrorMessage = ""; int additionalMemberId = 0; string appendedCopy = ""; Assert.IsTrue(EmailController.tryQueueSystemEmail(cp.core, systemEmail.name, appendedCopy, additionalMemberId, ref userErrorMessage)); Contensive.BaseClasses.AddonBaseClass addon = new Contensive.Processor.Addons.Email.ProcessEmailClass(); addon.Execute(cp); // // assert 2 emails, first the confirmation, then to-address Assert.AreEqual(2, cp.core.mockEmailList.Count); { // // -- the confirmationl MockEmailClass sentEmail = cp.core.mockEmailList[0]; Assert.AreEqual(confirmPerson.email, getEmailPart(sentEmail.email.toAddress)); Assert.AreEqual(systemEmail.fromAddress, getEmailPart(sentEmail.email.fromAddress)); Assert.AreNotEqual(-1, sentEmail.email.htmlBody.IndexOf(htmlBody)); Assert.IsTrue(string.IsNullOrEmpty(sentEmail.AttachmentFilename)); Assert.AreEqual("", getEmailPart(sentEmail.email.bounceAddress)); Assert.AreEqual("", getEmailPart(sentEmail.email.replyToAddress)); } { // // -- the to-email MockEmailClass sentEmail = cp.core.mockEmailList[1]; Assert.IsTrue(string.IsNullOrEmpty(sentEmail.AttachmentFilename)); Assert.AreEqual(toPerson.email, getEmailPart(sentEmail.email.toAddress)); Assert.AreEqual(systemEmail.fromAddress, getEmailPart(sentEmail.email.fromAddress)); Assert.AreEqual(systemEmail.subject, sentEmail.email.subject); Assert.AreNotEqual(-1, sentEmail.email.htmlBody.IndexOf(htmlBody)); Assert.AreEqual("", getEmailPart(sentEmail.email.bounceAddress)); Assert.AreEqual("", getEmailPart(sentEmail.email.replyToAddress)); } } } } }
55.86014
214
0.581685
[ "Apache-2.0" ]
contensive/Contensive5
source/ProcessorTests/Email/emailControllerTests.cs
15,978
C#
using RayTracingTutorial05.Structs; using System; using System.Threading; using Vortice.Direct3D12; using Vortice.Direct3D12.Debug; using Vortice.DXGI; using Vortice.Mathematics; namespace RayTracingTutorial05.RTX { public class D3D12GraphicsContext { public int kDefaultSwapChainBuffers = 2; public D3D12GraphicsContext(int winWidth, int winHeight) { if (!D3D12.IsSupported(Vortice.Direct3D.FeatureLevel.Level_12_0)) { throw new InvalidOperationException("Direct3D12 is not supported on current OS"); } } public IDXGISwapChain3 CreateDXGISwapChain(IDXGIFactory4 pFactory, IntPtr hwnd, int width, int height, Vortice.DXGI.Format format, ID3D12CommandQueue pCommandQueue) { SwapChainDescription1 swapChainDesc = new SwapChainDescription1(); swapChainDesc.BufferCount = kDefaultSwapChainBuffers; swapChainDesc.Width = width; swapChainDesc.Height = height; swapChainDesc.Format = format; swapChainDesc.Usage = Usage.RenderTargetOutput; swapChainDesc.SwapEffect = SwapEffect.FlipDiscard; swapChainDesc.SampleDescription = new SampleDescription(1, 0); // CreateSwapChainForHwnd() doesn't accept IDXGISwapChain3 (Why MS? Why?) IDXGISwapChain1 pSwapChain = pFactory.CreateSwapChainForHwnd(pCommandQueue, hwnd, swapChainDesc); IDXGISwapChain3 pSwapChain3 = pSwapChain.QueryInterface<IDXGISwapChain3>(); return pSwapChain3; } public ID3D12Device5 CreateDevice(IDXGIFactory4 pDxgiFactory) { // Find the HW adapter IDXGIAdapter1 pAdapter; var adapters = pDxgiFactory.EnumAdapters1(); for (uint i = 0; i < adapters.Length; i++) { pAdapter = adapters[i]; AdapterDescription1 desc = pAdapter.Description1; // Skip SW adapters if (desc.Flags.HasFlag(AdapterFlags.Software)) continue; #if DEBUG if (D3D12.D3D12GetDebugInterface<ID3D12Debug>(out var pDx12Debug).Success) { pDx12Debug.EnableDebugLayer(); } #endif var res = D3D12.D3D12CreateDevice(pAdapter, Vortice.Direct3D.FeatureLevel.Level_12_0, out ID3D12Device pDevice); FeatureDataD3D12Options5 features5 = pDevice.CheckFeatureSupport<FeatureDataD3D12Options5>(Vortice.Direct3D12.Feature.Options5); if (features5.RaytracingTier == RaytracingTier.NotSupported) { throw new NotSupportedException("Raytracing is not supported on this device.Make sure your GPU supports DXR(such as Nvidia's Volta or Turing RTX) and you're on the latest drivers.The DXR fallback layer is not supported."); } return pDevice.QueryInterface<ID3D12Device5>(); } return null; } public ID3D12CommandQueue CreateCommandQueue(ID3D12Device5 pDevice) { ID3D12CommandQueue pQueue; CommandQueueDescription cpDesc = new CommandQueueDescription(); cpDesc.Flags = CommandQueueFlags.None; cpDesc.Type = CommandListType.Direct; pQueue = pDevice.CreateCommandQueue(cpDesc); return pQueue; } public ID3D12DescriptorHeap CreateDescriptorHeap(ID3D12Device5 pDevice, int count, DescriptorHeapType type, bool shaderVisible) { DescriptorHeapDescription desc = new DescriptorHeapDescription(); desc.DescriptorCount = count; desc.Type = type; desc.Flags = shaderVisible ? DescriptorHeapFlags.ShaderVisible : DescriptorHeapFlags.None; ID3D12DescriptorHeap pHeap; pHeap = pDevice.CreateDescriptorHeap(desc); return pHeap; } public CpuDescriptorHandle CreateRTV(ID3D12Device5 pDevice, ID3D12Resource pResource, ID3D12DescriptorHeap pHeap, ref uint usedHeapEntries, Format format) { RenderTargetViewDescription desc = new RenderTargetViewDescription(); desc.ViewDimension = RenderTargetViewDimension.Texture2D; desc.Format = format; desc.Texture2D = new Texture2DRenderTargetView(); desc.Texture2D.MipSlice = 0; CpuDescriptorHandle rtvHandle = pHeap.GetCPUDescriptorHandleForHeapStart(); rtvHandle.Ptr += usedHeapEntries * pDevice.GetDescriptorHandleIncrementSize(DescriptorHeapType.RenderTargetView); usedHeapEntries++; pDevice.CreateRenderTargetView(pResource, desc, rtvHandle); return rtvHandle; } public void ResourceBarrier(ID3D12GraphicsCommandList4 pCmdLit, ID3D12Resource pResource, ResourceStates stateBefore, ResourceStates stateAfter) { ResourceBarrier barrier = new ResourceBarrier(new ResourceTransitionBarrier(pResource, stateBefore, stateAfter)); pCmdLit.ResourceBarrier(barrier); } public uint SubmitCommandList(ID3D12GraphicsCommandList4 pCmdList, ID3D12CommandQueue pCmdQueue, ID3D12Fence pFence, uint fenceValue) { pCmdList.Close(); pCmdQueue.ExecuteCommandList(pCmdList); fenceValue++; pCmdQueue.Signal(pFence, fenceValue); return fenceValue; } } }
43.452381
242
0.663196
[ "MIT" ]
Jorgemagic/CSharpDirectXRaytracing
05-ShaderTable/RTX/D3D12GraphicsContext.cs
5,477
C#
using AutoMapper; using Microsoft.EntityFrameworkCore; using MyDiet.Business.IRepository; using MyDiet.Data; using MyDiet.Models; using MyDiet.Models.Dtos; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace MyDiet.Business { public class MealRepository : IMealRepository { private readonly ApplicationDbContext _ctx; private readonly IMapper _mapper; private const string NAME_PARAMETER = "Name"; public MealRepository(ApplicationDbContext ctx, IMapper mapper) { _ctx = ctx; _mapper = mapper; } public async Task<IList<MealDto>> GetAll() { return _mapper.Map<IList<Meal>, IList<MealDto>>(await _ctx.Meals.ToListAsync()); } public async Task<MealDto> Get(int id) { Meal mealFromDb = await _ctx.Meals.FindAsync(id); return _mapper.Map<Meal, MealDto>(mealFromDb); } public async Task Create(MealDto entity) { Meal mealToAdd = _mapper.Map<MealDto, Meal>(entity); await _ctx.Meals.AddAsync(mealToAdd); await _ctx.SaveChangesAsync(); } public async Task Update(int id, MealDto entity) { Meal mealFromDb = await _ctx.Meals.FindAsync(id); Meal mealToUpdate = _mapper.Map<MealDto, Meal>(entity); _ctx.Entry(mealFromDb).CurrentValues.SetValues(mealToUpdate); await _ctx.SaveChangesAsync(); } public async Task Delete(int id) { Meal mealFromDb = await _ctx.Meals.FindAsync(id); _ctx.Meals.Remove(mealFromDb); await _ctx.SaveChangesAsync(); } public async Task<bool> AddMealToDiet(int dietId, int mealId) { bool exists = await _ctx.DietMeals.AnyAsync(dm => dm.DietId == dietId && dm.MealId == mealId); if(!exists) { DietMeal dietMeal = new DietMeal { MealId = mealId, DietId = dietId }; await _ctx.AddAsync(dietMeal); await _ctx.SaveChangesAsync(); return true; } return false; } public async Task RemoveMealFromDiet(int dietId, int mealId) { DietMeal dietMeal = await _ctx.DietMeals.Where(dm => dm.DietId == dietId && dm.MealId == mealId).FirstOrDefaultAsync(); _ctx.Remove(dietMeal); await _ctx.SaveChangesAsync(); } public bool CheckIfUnique(string parameter, MealDto entity) { if(parameter.Equals(NAME_PARAMETER)) { return _ctx.Meals.Any(m => m.Name == entity.Name); } return false; } public async Task<bool> AddProductToMeal(int mealId, int productId) { bool exists = await _ctx.MealProducts.AnyAsync(mp => mp.MealId == mealId && mp.ProductId == productId); if(!exists) { MealProduct mealProduct = new MealProduct { MealId = mealId, ProductId = productId }; await _ctx.AddAsync(mealProduct); await _ctx.SaveChangesAsync(); return true; } return false; } public async Task RemoveProductFromMeal(int mealId, int productId) { MealProduct mealProduct = await _ctx.MealProducts.FirstOrDefaultAsync(mp => mp.MealId == mealId && mp.ProductId == productId); _ctx.Remove(mealProduct); await _ctx.SaveChangesAsync(); } } }
30.15873
138
0.561579
[ "MIT" ]
FrancescoRepo/MyDiet
MyDiet/Business/MealRepository.cs
3,802
C#
/************************************************************************* * Copyright 2010-2013 Eucalyptus Systems, Inc. * * Redistribution and use of this software 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. * * 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. ************************************************************************/ using System; using System.Collections.Generic; //using System.Linq; using System.Text; namespace Com.Eucalyptus { public interface IManagedThread { void TerminateAsync(); void TerminateSync(); } }
44.675
76
0.68047
[ "BSD-2-Clause" ]
sjones4/windows-integration
EucaCommon/Utility/IManagedThread.cs
1,789
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated from a template. // // Manual changes to this file may cause unexpected behavior in your application. // Manual changes to this file will be overwritten if the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Data.Objects; using System.Data.Objects.DataClasses; using System.Data.EntityClient; using System.ComponentModel; using System.Xml.Serialization; using System.Runtime.Serialization; [assembly: EdmSchemaAttribute()] #region EDM Relationship Metadata [assembly: EdmRelationshipAttribute("CompanyModel", "FK_Company_ChiefExecutiveOfficer", "Employee", System.Data.Metadata.Edm.RelationshipMultiplicity.One, typeof(InterLinq.UnitTests.Artefacts.EntityFramework4.Employee), "Company", System.Data.Metadata.Edm.RelationshipMultiplicity.Many, typeof(InterLinq.UnitTests.Artefacts.EntityFramework4.Company), true)] [assembly: EdmRelationshipAttribute("CompanyModel", "FK_Department_Company", "Company", System.Data.Metadata.Edm.RelationshipMultiplicity.One, typeof(InterLinq.UnitTests.Artefacts.EntityFramework4.Company), "Department", System.Data.Metadata.Edm.RelationshipMultiplicity.Many, typeof(InterLinq.UnitTests.Artefacts.EntityFramework4.Department), true)] [assembly: EdmRelationshipAttribute("CompanyModel", "FK_Department_Manager", "Employee", System.Data.Metadata.Edm.RelationshipMultiplicity.One, typeof(InterLinq.UnitTests.Artefacts.EntityFramework4.Employee), "Department", System.Data.Metadata.Edm.RelationshipMultiplicity.Many, typeof(InterLinq.UnitTests.Artefacts.EntityFramework4.Department), true)] [assembly: EdmRelationshipAttribute("CompanyModel", "FK_Employee_Department", "Department", System.Data.Metadata.Edm.RelationshipMultiplicity.ZeroOrOne, typeof(InterLinq.UnitTests.Artefacts.EntityFramework4.Department), "Employee", System.Data.Metadata.Edm.RelationshipMultiplicity.Many, typeof(InterLinq.UnitTests.Artefacts.EntityFramework4.Employee), true)] #endregion namespace InterLinq.UnitTests.Artefacts.EntityFramework4 { #region Contexts /// <summary> /// No Metadata Documentation available. /// </summary> public partial class CompanyEntities : ObjectContext { #region Constructors /// <summary> /// Initializes a new CompanyEntities object using the connection string found in the 'CompanyEntities' section of the application configuration file. /// </summary> public CompanyEntities() : base("name=CompanyEntities", "CompanyEntities") { this.ContextOptions.LazyLoadingEnabled = true; OnContextCreated(); } /// <summary> /// Initialize a new CompanyEntities object. /// </summary> public CompanyEntities(string connectionString) : base(connectionString, "CompanyEntities") { this.ContextOptions.LazyLoadingEnabled = true; OnContextCreated(); } /// <summary> /// Initialize a new CompanyEntities object. /// </summary> public CompanyEntities(EntityConnection connection) : base(connection, "CompanyEntities") { this.ContextOptions.LazyLoadingEnabled = true; OnContextCreated(); } #endregion #region Partial Methods partial void OnContextCreated(); #endregion #region ObjectSet Properties /// <summary> /// No Metadata Documentation available. /// </summary> public ObjectSet<Company> Company { get { if ((_Company == null)) { _Company = base.CreateObjectSet<Company>("Company"); } return _Company; } } private ObjectSet<Company> _Company; /// <summary> /// No Metadata Documentation available. /// </summary> public ObjectSet<Department> Department { get { if ((_Department == null)) { _Department = base.CreateObjectSet<Department>("Department"); } return _Department; } } private ObjectSet<Department> _Department; /// <summary> /// No Metadata Documentation available. /// </summary> public ObjectSet<Employee> Employee { get { if ((_Employee == null)) { _Employee = base.CreateObjectSet<Employee>("Employee"); } return _Employee; } } private ObjectSet<Employee> _Employee; #endregion #region AddTo Methods /// <summary> /// Deprecated Method for adding a new object to the Company EntitySet. Consider using the .Add method of the associated ObjectSet&lt;T&gt; property instead. /// </summary> public void AddToCompany(Company company) { base.AddObject("Company", company); } /// <summary> /// Deprecated Method for adding a new object to the Department EntitySet. Consider using the .Add method of the associated ObjectSet&lt;T&gt; property instead. /// </summary> public void AddToDepartment(Department department) { base.AddObject("Department", department); } /// <summary> /// Deprecated Method for adding a new object to the Employee EntitySet. Consider using the .Add method of the associated ObjectSet&lt;T&gt; property instead. /// </summary> public void AddToEmployee(Employee employee) { base.AddObject("Employee", employee); } #endregion } #endregion #region Entities /// <summary> /// No Metadata Documentation available. /// </summary> [EdmEntityTypeAttribute(NamespaceName="CompanyModel", Name="Company")] [Serializable()] [DataContractAttribute(IsReference=true)] public partial class Company : EntityObject { #region Factory Method /// <summary> /// Create a new Company object. /// </summary> /// <param name="id">Initial value of the Id property.</param> /// <param name="name">Initial value of the Name property.</param> /// <param name="foundation">Initial value of the Foundation property.</param> /// <param name="chiefExecutiveOfficerId">Initial value of the ChiefExecutiveOfficerId property.</param> public static Company CreateCompany(global::System.Int32 id, global::System.String name, global::System.DateTime foundation, global::System.Int32 chiefExecutiveOfficerId) { Company company = new Company(); company.Id = id; company.Name = name; company.Foundation = foundation; company.ChiefExecutiveOfficerId = chiefExecutiveOfficerId; return company; } #endregion #region Primitive Properties /// <summary> /// No Metadata Documentation available. /// </summary> [EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)] [DataMemberAttribute()] public global::System.Int32 Id { get { return _Id; } set { if (_Id != value) { OnIdChanging(value); ReportPropertyChanging("Id"); _Id = StructuralObject.SetValidValue(value); ReportPropertyChanged("Id"); OnIdChanged(); } } } private global::System.Int32 _Id; partial void OnIdChanging(global::System.Int32 value); partial void OnIdChanged(); /// <summary> /// No Metadata Documentation available. /// </summary> [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)] [DataMemberAttribute()] public global::System.String Name { get { return _Name; } set { OnNameChanging(value); ReportPropertyChanging("Name"); _Name = StructuralObject.SetValidValue(value, false); ReportPropertyChanged("Name"); OnNameChanged(); } } private global::System.String _Name; partial void OnNameChanging(global::System.String value); partial void OnNameChanged(); /// <summary> /// No Metadata Documentation available. /// </summary> [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)] [DataMemberAttribute()] public global::System.DateTime Foundation { get { return _Foundation; } set { OnFoundationChanging(value); ReportPropertyChanging("Foundation"); _Foundation = StructuralObject.SetValidValue(value); ReportPropertyChanged("Foundation"); OnFoundationChanged(); } } private global::System.DateTime _Foundation; partial void OnFoundationChanging(global::System.DateTime value); partial void OnFoundationChanged(); /// <summary> /// No Metadata Documentation available. /// </summary> [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)] [DataMemberAttribute()] public global::System.Int32 ChiefExecutiveOfficerId { get { return _ChiefExecutiveOfficerId; } set { OnChiefExecutiveOfficerIdChanging(value); ReportPropertyChanging("ChiefExecutiveOfficerId"); _ChiefExecutiveOfficerId = StructuralObject.SetValidValue(value); ReportPropertyChanged("ChiefExecutiveOfficerId"); OnChiefExecutiveOfficerIdChanged(); } } private global::System.Int32 _ChiefExecutiveOfficerId; partial void OnChiefExecutiveOfficerIdChanging(global::System.Int32 value); partial void OnChiefExecutiveOfficerIdChanged(); #endregion #region Navigation Properties /// <summary> /// No Metadata Documentation available. /// </summary> [XmlIgnoreAttribute()] [SoapIgnoreAttribute()] [DataMemberAttribute()] [EdmRelationshipNavigationPropertyAttribute("CompanyModel", "FK_Company_ChiefExecutiveOfficer", "Employee")] public Employee Employee { get { return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedReference<Employee>("CompanyModel.FK_Company_ChiefExecutiveOfficer", "Employee").Value; } set { ((IEntityWithRelationships)this).RelationshipManager.GetRelatedReference<Employee>("CompanyModel.FK_Company_ChiefExecutiveOfficer", "Employee").Value = value; } } /// <summary> /// No Metadata Documentation available. /// </summary> [BrowsableAttribute(false)] [DataMemberAttribute()] public EntityReference<Employee> EmployeeReference { get { return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedReference<Employee>("CompanyModel.FK_Company_ChiefExecutiveOfficer", "Employee"); } set { if ((value != null)) { ((IEntityWithRelationships)this).RelationshipManager.InitializeRelatedReference<Employee>("CompanyModel.FK_Company_ChiefExecutiveOfficer", "Employee", value); } } } /// <summary> /// No Metadata Documentation available. /// </summary> [XmlIgnoreAttribute()] [SoapIgnoreAttribute()] [DataMemberAttribute()] [EdmRelationshipNavigationPropertyAttribute("CompanyModel", "FK_Department_Company", "Department")] public EntityCollection<Department> Department { get { return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedCollection<Department>("CompanyModel.FK_Department_Company", "Department"); } set { if ((value != null)) { ((IEntityWithRelationships)this).RelationshipManager.InitializeRelatedCollection<Department>("CompanyModel.FK_Department_Company", "Department", value); } } } #endregion } /// <summary> /// No Metadata Documentation available. /// </summary> [EdmEntityTypeAttribute(NamespaceName="CompanyModel", Name="Department")] [Serializable()] [DataContractAttribute(IsReference=true)] public partial class Department : EntityObject { #region Factory Method /// <summary> /// Create a new Department object. /// </summary> /// <param name="id">Initial value of the Id property.</param> /// <param name="name">Initial value of the Name property.</param> /// <param name="foundation">Initial value of the Foundation property.</param> /// <param name="qualityLevel">Initial value of the QualityLevel property.</param> /// <param name="companyId">Initial value of the CompanyId property.</param> /// <param name="managerId">Initial value of the ManagerId property.</param> public static Department CreateDepartment(global::System.Int32 id, global::System.String name, global::System.DateTime foundation, global::System.Int32 qualityLevel, global::System.Int32 companyId, global::System.Int32 managerId) { Department department = new Department(); department.Id = id; department.Name = name; department.Foundation = foundation; department.QualityLevel = qualityLevel; department.CompanyId = companyId; department.ManagerId = managerId; return department; } #endregion #region Primitive Properties /// <summary> /// No Metadata Documentation available. /// </summary> [EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)] [DataMemberAttribute()] public global::System.Int32 Id { get { return _Id; } set { if (_Id != value) { OnIdChanging(value); ReportPropertyChanging("Id"); _Id = StructuralObject.SetValidValue(value); ReportPropertyChanged("Id"); OnIdChanged(); } } } private global::System.Int32 _Id; partial void OnIdChanging(global::System.Int32 value); partial void OnIdChanged(); /// <summary> /// No Metadata Documentation available. /// </summary> [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)] [DataMemberAttribute()] public global::System.String Name { get { return _Name; } set { OnNameChanging(value); ReportPropertyChanging("Name"); _Name = StructuralObject.SetValidValue(value, false); ReportPropertyChanged("Name"); OnNameChanged(); } } private global::System.String _Name; partial void OnNameChanging(global::System.String value); partial void OnNameChanged(); /// <summary> /// No Metadata Documentation available. /// </summary> [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)] [DataMemberAttribute()] public global::System.DateTime Foundation { get { return _Foundation; } set { OnFoundationChanging(value); ReportPropertyChanging("Foundation"); _Foundation = StructuralObject.SetValidValue(value); ReportPropertyChanged("Foundation"); OnFoundationChanged(); } } private global::System.DateTime _Foundation; partial void OnFoundationChanging(global::System.DateTime value); partial void OnFoundationChanged(); /// <summary> /// No Metadata Documentation available. /// </summary> [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)] [DataMemberAttribute()] public global::System.Int32 QualityLevel { get { return _QualityLevel; } set { OnQualityLevelChanging(value); ReportPropertyChanging("QualityLevel"); _QualityLevel = StructuralObject.SetValidValue(value); ReportPropertyChanged("QualityLevel"); OnQualityLevelChanged(); } } private global::System.Int32 _QualityLevel; partial void OnQualityLevelChanging(global::System.Int32 value); partial void OnQualityLevelChanged(); /// <summary> /// No Metadata Documentation available. /// </summary> [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)] [DataMemberAttribute()] public global::System.Int32 CompanyId { get { return _CompanyId; } set { OnCompanyIdChanging(value); ReportPropertyChanging("CompanyId"); _CompanyId = StructuralObject.SetValidValue(value); ReportPropertyChanged("CompanyId"); OnCompanyIdChanged(); } } private global::System.Int32 _CompanyId; partial void OnCompanyIdChanging(global::System.Int32 value); partial void OnCompanyIdChanged(); /// <summary> /// No Metadata Documentation available. /// </summary> [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)] [DataMemberAttribute()] public global::System.Int32 ManagerId { get { return _ManagerId; } set { OnManagerIdChanging(value); ReportPropertyChanging("ManagerId"); _ManagerId = StructuralObject.SetValidValue(value); ReportPropertyChanged("ManagerId"); OnManagerIdChanged(); } } private global::System.Int32 _ManagerId; partial void OnManagerIdChanging(global::System.Int32 value); partial void OnManagerIdChanged(); #endregion #region Navigation Properties /// <summary> /// No Metadata Documentation available. /// </summary> [XmlIgnoreAttribute()] [SoapIgnoreAttribute()] [DataMemberAttribute()] [EdmRelationshipNavigationPropertyAttribute("CompanyModel", "FK_Department_Company", "Company")] public Company Company { get { return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedReference<Company>("CompanyModel.FK_Department_Company", "Company").Value; } set { ((IEntityWithRelationships)this).RelationshipManager.GetRelatedReference<Company>("CompanyModel.FK_Department_Company", "Company").Value = value; } } /// <summary> /// No Metadata Documentation available. /// </summary> [BrowsableAttribute(false)] [DataMemberAttribute()] public EntityReference<Company> CompanyReference { get { return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedReference<Company>("CompanyModel.FK_Department_Company", "Company"); } set { if ((value != null)) { ((IEntityWithRelationships)this).RelationshipManager.InitializeRelatedReference<Company>("CompanyModel.FK_Department_Company", "Company", value); } } } /// <summary> /// No Metadata Documentation available. /// </summary> [XmlIgnoreAttribute()] [SoapIgnoreAttribute()] [DataMemberAttribute()] [EdmRelationshipNavigationPropertyAttribute("CompanyModel", "FK_Department_Manager", "Employee")] public Employee Manager { get { return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedReference<Employee>("CompanyModel.FK_Department_Manager", "Employee").Value; } set { ((IEntityWithRelationships)this).RelationshipManager.GetRelatedReference<Employee>("CompanyModel.FK_Department_Manager", "Employee").Value = value; } } /// <summary> /// No Metadata Documentation available. /// </summary> [BrowsableAttribute(false)] [DataMemberAttribute()] public EntityReference<Employee> ManagerReference { get { return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedReference<Employee>("CompanyModel.FK_Department_Manager", "Employee"); } set { if ((value != null)) { ((IEntityWithRelationships)this).RelationshipManager.InitializeRelatedReference<Employee>("CompanyModel.FK_Department_Manager", "Employee", value); } } } /// <summary> /// No Metadata Documentation available. /// </summary> [XmlIgnoreAttribute()] [SoapIgnoreAttribute()] [DataMemberAttribute()] [EdmRelationshipNavigationPropertyAttribute("CompanyModel", "FK_Employee_Department", "Employee")] public EntityCollection<Employee> Employees { get { return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedCollection<Employee>("CompanyModel.FK_Employee_Department", "Employee"); } set { if ((value != null)) { ((IEntityWithRelationships)this).RelationshipManager.InitializeRelatedCollection<Employee>("CompanyModel.FK_Employee_Department", "Employee", value); } } } #endregion } /// <summary> /// No Metadata Documentation available. /// </summary> [EdmEntityTypeAttribute(NamespaceName="CompanyModel", Name="Employee")] [Serializable()] [DataContractAttribute(IsReference=true)] public partial class Employee : EntityObject { #region Factory Method /// <summary> /// Create a new Employee object. /// </summary> /// <param name="id">Initial value of the Id property.</param> /// <param name="name">Initial value of the Name property.</param> /// <param name="isMale">Initial value of the IsMale property.</param> /// <param name="salary">Initial value of the Salary property.</param> /// <param name="grade">Initial value of the Grade property.</param> public static Employee CreateEmployee(global::System.Int32 id, global::System.String name, global::System.Boolean isMale, global::System.Decimal salary, global::System.Int32 grade) { Employee employee = new Employee(); employee.Id = id; employee.Name = name; employee.IsMale = isMale; employee.Salary = salary; employee.Grade = grade; return employee; } #endregion #region Primitive Properties /// <summary> /// No Metadata Documentation available. /// </summary> [EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)] [DataMemberAttribute()] public global::System.Int32 Id { get { return _Id; } set { if (_Id != value) { OnIdChanging(value); ReportPropertyChanging("Id"); _Id = StructuralObject.SetValidValue(value); ReportPropertyChanged("Id"); OnIdChanged(); } } } private global::System.Int32 _Id; partial void OnIdChanging(global::System.Int32 value); partial void OnIdChanged(); /// <summary> /// No Metadata Documentation available. /// </summary> [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)] [DataMemberAttribute()] public global::System.String Name { get { return _Name; } set { OnNameChanging(value); ReportPropertyChanging("Name"); _Name = StructuralObject.SetValidValue(value, false); ReportPropertyChanged("Name"); OnNameChanged(); } } private global::System.String _Name; partial void OnNameChanging(global::System.String value); partial void OnNameChanged(); /// <summary> /// No Metadata Documentation available. /// </summary> [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)] [DataMemberAttribute()] public global::System.Boolean IsMale { get { return _IsMale; } set { OnIsMaleChanging(value); ReportPropertyChanging("IsMale"); _IsMale = StructuralObject.SetValidValue(value); ReportPropertyChanged("IsMale"); OnIsMaleChanged(); } } private global::System.Boolean _IsMale; partial void OnIsMaleChanging(global::System.Boolean value); partial void OnIsMaleChanged(); /// <summary> /// No Metadata Documentation available. /// </summary> [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)] [DataMemberAttribute()] public global::System.Decimal Salary { get { return _Salary; } set { OnSalaryChanging(value); ReportPropertyChanging("Salary"); _Salary = StructuralObject.SetValidValue(value); ReportPropertyChanged("Salary"); OnSalaryChanged(); } } private global::System.Decimal _Salary; partial void OnSalaryChanging(global::System.Decimal value); partial void OnSalaryChanged(); /// <summary> /// No Metadata Documentation available. /// </summary> [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)] [DataMemberAttribute()] public global::System.Int32 Grade { get { return _Grade; } set { OnGradeChanging(value); ReportPropertyChanging("Grade"); _Grade = StructuralObject.SetValidValue(value); ReportPropertyChanged("Grade"); OnGradeChanged(); } } private global::System.Int32 _Grade; partial void OnGradeChanging(global::System.Int32 value); partial void OnGradeChanged(); /// <summary> /// No Metadata Documentation available. /// </summary> [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=true)] [DataMemberAttribute()] public Nullable<global::System.Int32> DepartmentId { get { return _DepartmentId; } set { OnDepartmentIdChanging(value); ReportPropertyChanging("DepartmentId"); _DepartmentId = StructuralObject.SetValidValue(value); ReportPropertyChanged("DepartmentId"); OnDepartmentIdChanged(); } } private Nullable<global::System.Int32> _DepartmentId; partial void OnDepartmentIdChanging(Nullable<global::System.Int32> value); partial void OnDepartmentIdChanged(); #endregion #region Navigation Properties /// <summary> /// No Metadata Documentation available. /// </summary> [XmlIgnoreAttribute()] [SoapIgnoreAttribute()] [DataMemberAttribute()] [EdmRelationshipNavigationPropertyAttribute("CompanyModel", "FK_Company_ChiefExecutiveOfficer", "Company")] public EntityCollection<Company> Company { get { return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedCollection<Company>("CompanyModel.FK_Company_ChiefExecutiveOfficer", "Company"); } set { if ((value != null)) { ((IEntityWithRelationships)this).RelationshipManager.InitializeRelatedCollection<Company>("CompanyModel.FK_Company_ChiefExecutiveOfficer", "Company", value); } } } /// <summary> /// No Metadata Documentation available. /// </summary> [XmlIgnoreAttribute()] [SoapIgnoreAttribute()] [DataMemberAttribute()] [EdmRelationshipNavigationPropertyAttribute("CompanyModel", "FK_Department_Manager", "Department")] public EntityCollection<Department> Manager { get { return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedCollection<Department>("CompanyModel.FK_Department_Manager", "Department"); } set { if ((value != null)) { ((IEntityWithRelationships)this).RelationshipManager.InitializeRelatedCollection<Department>("CompanyModel.FK_Department_Manager", "Department", value); } } } /// <summary> /// No Metadata Documentation available. /// </summary> [XmlIgnoreAttribute()] [SoapIgnoreAttribute()] [DataMemberAttribute()] [EdmRelationshipNavigationPropertyAttribute("CompanyModel", "FK_Employee_Department", "Department")] public Department Department { get { return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedReference<Department>("CompanyModel.FK_Employee_Department", "Department").Value; } set { ((IEntityWithRelationships)this).RelationshipManager.GetRelatedReference<Department>("CompanyModel.FK_Employee_Department", "Department").Value = value; } } /// <summary> /// No Metadata Documentation available. /// </summary> [BrowsableAttribute(false)] [DataMemberAttribute()] public EntityReference<Department> DepartmentReference { get { return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedReference<Department>("CompanyModel.FK_Employee_Department", "Department"); } set { if ((value != null)) { ((IEntityWithRelationships)this).RelationshipManager.InitializeRelatedReference<Department>("CompanyModel.FK_Employee_Department", "Department", value); } } } #endregion } #endregion }
37.436404
360
0.557319
[ "MIT" ]
ErrCode/Zyan.Core.LocalIPC
branches/withoutremoting/Zyan.Tests.InterLinq/Artefacts/EntityFramework4/Company.Designer.cs
34,144
C#
using System; namespace SSA { class Test { static void empty () { } static int ret_int () { return 1; } static int simple_add (int a) { int b = 5; return a + b; } static int cmov (int a) { return a >= 10? 1: 2; } static int many_shifts (int a, int b, int c) { return a << b << c << 1; } static void test2 (int a) { int x, y, z; z = 1; if (z > a) { x = 1; if (z > 2) { y = x + 1; return; } } else { x = 2; } z = x -3; x = 4; goto next; next: z = x + 7; } static int rfib (int n) { if (n < 2) return 1; return rfib (n - 2) + rfib (n - 1); } static int test1 (int v) { int x, y; x = 1; if (v != 0) { y = 2; } else { y = x + 1; } return y; } static int for_loop () { int j = 0; for (int i = 0; i < 5; i++) { j += i; } return j; } static int many_bb2 () { int j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } return j; } static int many_bb4 () { int j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } return j; } static int many_bb8 () { int j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } return j; } static int many_bb16 () { int j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } return j; } static int many_bb32 () { int j; j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } j = 0; for (int i = 0; i < 5; i++) { j += i; } return j; } /*static int fib (int n) { int f0 = 0, f1 = 1, f2 = 0, i; if (n <= 1) goto L3; i = 2; L1: if (i <= n) goto L2; return f2; L2: f2 = f0 + f1; f0 = f1; f1 = f2; i++; goto L1; L3: return n; }*/ static int nested_loops (int n) { int m = 1000; int a = 0; for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { a++; } } return a; } static int Main() { if (test1 (1) != 2) return 1; return 0; } } }
23.641834
49
0.315841
[ "Apache-2.0" ]
121468615/mono
mono/mini/test.cs
8,251
C#
using kadynsWOTRMods.Config; using kadynsWOTRMods.Extensions; using kadynsWOTRMods.Utilities; using Kingmaker.Blueprints; using Kingmaker.Blueprints.Classes; using Kingmaker.Blueprints.Classes.Prerequisites; using Kingmaker.Blueprints.Items; using Kingmaker.Designers.Mechanics.Facts; using Kingmaker.UnitLogic.Alignments; using Kingmaker.UnitLogic.FactLogic; using Kingmaker.TextTools; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace kadynsWOTRMods.Tweaks.Deities { internal class Apsu { private static readonly BlueprintFeature GoodDomainAllowed = Resources.GetBlueprint<BlueprintFeature>("882521af8012fc749930b03dc18a69de"); private static readonly BlueprintFeature TravelDomainAllowed = Resources.GetBlueprint<BlueprintFeature>("c008853fe044bd442ae8bd22260592b7"); private static readonly BlueprintFeature ArtificeDomainAllowed = Resources.GetBlueprint<BlueprintFeature>("9656b1c7214180f4b9a6ab56f83b92fb"); private static readonly BlueprintFeature CommunityDomainAllowed = Resources.GetBlueprint<BlueprintFeature>("c87004460f3328c408d22c5ead05291f"); private static readonly BlueprintFeature LawDomainAllowed = Resources.GetBlueprint<BlueprintFeature>("092714336606cfc45a37d2ab39fabfa8"); private static readonly BlueprintFeature CrusaderSpellbook = Resources.GetBlueprint<BlueprintFeature>("673d39f7da699aa408cdda6282e7dcc0"); private static readonly BlueprintFeature ClericSpellbook = Resources.GetBlueprint<BlueprintFeature>("4673d19a0cf2fab4f885cc4d1353da33"); private static readonly BlueprintFeature InquisitorSpellbook = Resources.GetBlueprint<BlueprintFeature>("57fab75111f377248810ece84193a5a5"); private static readonly BlueprintFeature ChannelPositiveAllowed = Resources.GetBlueprint<BlueprintFeature>("8c769102f3996684fb6e09a2c4e7e5b9"); private static readonly BlueprintCharacterClass ClericClass = Resources.GetBlueprint<BlueprintCharacterClass>("67819271767a9dd4fbfd4ae700befea0"); private static readonly BlueprintCharacterClass InquistorClass = Resources.GetBlueprint<BlueprintCharacterClass>("f1a70d9e1b0b41e49874e1fa9052a1ce"); private static readonly BlueprintCharacterClass WarpriestClass = Resources.GetBlueprint<BlueprintCharacterClass>("30b5e47d47a0e37438cc5a80c96cfb99"); public static void AddApsu() { if (ModSettings.AddedContent.Deities.IsDisabled("Apsu")) { return; } BlueprintFeature ImprovedUnarmedStrike = Resources.GetBlueprint<BlueprintFeature>("7812ad3672a4b9a4fb894ea402095167"); BlueprintFeature QuarterstaffProficiency = Resources.GetBlueprint<BlueprintFeature>("aed4f88b52ae0fb468895f90da854ad4"); BlueprintFeature BloodlineDraconicSilverArcana = Resources.GetBlueprint<BlueprintFeature>("1af96d3ab792e3048b5e0ca47f3a524b"); BlueprintItem MasterworkQuarterstaff = Resources.GetBlueprint<BlueprintItem>("ad1a532601f8b644991d5012adccee6c"); BlueprintArchetype FeralChampionArchetype = Resources.GetBlueprint<BlueprintArchetype>("f68ca492c9c15e241ab73735fbd0fb9f"); BlueprintArchetype PriestOfBalance = Resources.GetBlueprint<BlueprintArchetype>("a4560e3fb5d247d68fb1a2738fcc0855"); var ApsuIcon = AssetLoader.LoadInternal("Deities", "Icon_Apsu.jpg"); var ApsuFeature = Helpers.CreateBlueprint<BlueprintFeature>("ApsuFeature", (bp => { bp.SetName("Apsu"); bp.SetDescription("\nTitles: Waybringer, The Exiled Wyrm, Maker of All " + "\nRealm: Immortal Ambulatory, a traveling demi-plane " + "\n{g|Encyclopedia:Alignment}Alignment{/g}: Lawful Good " + "\nAreas of Concern: Good Dragons, Glory, Leadership, Peace " + "\nDomains: Artifice, Good, Law, Travel, Community " + "\nSubdomains: Archon, Construct, Dragon, Exploration, Judgment, Toll, Trade " + "\nFavoured Weapon: Bite, Quarterstaff (Arcana) " + "\nHoly Symbol: Silver Dragon above Pool " + "\nSacred Colours: Metallic Colors " + "\nApsu is the patron deity of all good and metallic dragons, and one of the oldest gods of the Great Beyond. " + "Along with Tiamat, he is believed to be one of the two original creator " + "beings of the multiverse. According to draconic lore, in the dawn of time there flowed two waters, fresh and salt, " + "which became Apsu and Tiamat, parents of the first gods. However, their eldest son Dahak came to Hell to rampage, " + "then killed his siblings, whose shattered remains fell into the Material Plane and became the first metallic dragons. " + "Enraged, the fresh water descended upon the Material Plane to confront his son, saying the eternal words: " + "\"I shall then be Apsu, for I am the first\". " + "\nAppearance: Apsu appears as a regal silver dragon dwarfing the largest great wyrms. His scales sparkle with a pearlescent glow. "); bp.m_Icon = ApsuIcon; bp.Ranks = 1; bp.IsClassFeature = true; bp.HideInCharacterSheetAndLevelUp = false; bp.AddComponent<PrerequisiteNoArchetype>(c => { c.m_CharacterClass = ClericClass.ToReference<BlueprintCharacterClassReference>(); c.m_Archetype = PriestOfBalance.ToReference<BlueprintArchetypeReference>(); }); bp.AddComponent<PrerequisiteNoArchetype>(c => { c.m_CharacterClass = WarpriestClass.ToReference<BlueprintCharacterClassReference>(); c.m_Archetype = FeralChampionArchetype.ToReference<BlueprintArchetypeReference>(); }); bp.Groups = new FeatureGroup[] { FeatureGroup.Deities }; bp.AddComponent<PrerequisiteAlignment>(c => { c.Alignment = AlignmentMaskType.LawfulGood | AlignmentMaskType.LawfulNeutral | AlignmentMaskType.NeutralGood | AlignmentMaskType.TrueNeutral; }); bp.AddComponent<AddFacts>(c => { c.m_Facts = new BlueprintUnitFactReference[1] { ChannelPositiveAllowed.ToReference<BlueprintUnitFactReference>() }; }); bp.AddComponent<AddFacts>(c => { c.m_Facts = new BlueprintUnitFactReference[1] { GoodDomainAllowed.ToReference<BlueprintUnitFactReference>() }; }); bp.AddComponent<AddFacts>(c => { c.m_Facts = new BlueprintUnitFactReference[1] { LawDomainAllowed.ToReference<BlueprintUnitFactReference>() }; }); bp.AddComponent<AddFacts>(c => { c.m_Facts = new BlueprintUnitFactReference[1] { TravelDomainAllowed.ToReference<BlueprintUnitFactReference>() }; }); bp.AddComponent<AddFacts>(c => { c.m_Facts = new BlueprintUnitFactReference[1] { ArtificeDomainAllowed.ToReference<BlueprintUnitFactReference>() }; }); bp.AddComponent<AddFacts>(c => { c.m_Facts = new BlueprintUnitFactReference[1] { CommunityDomainAllowed.ToReference<BlueprintUnitFactReference>() }; }); bp.AddComponent<ForbidSpellbookOnAlignmentDeviation>(c => { c.m_Spellbooks = new BlueprintSpellbookReference[1] { CrusaderSpellbook.ToReference<BlueprintSpellbookReference>() }; c.m_Spellbooks = new BlueprintSpellbookReference[1] { ClericSpellbook.ToReference<BlueprintSpellbookReference>() }; c.m_Spellbooks = new BlueprintSpellbookReference[1] { InquisitorSpellbook.ToReference<BlueprintSpellbookReference>() }; }); bp.AddComponent<AddFeatureOnClassLevel>(c => { c.m_Class = ClericClass.ToReference<BlueprintCharacterClassReference>(); c.m_Feature = BloodlineDraconicSilverArcana.ToReference<BlueprintFeatureReference>(); c.m_Feature = QuarterstaffProficiency.ToReference<BlueprintFeatureReference>(); c.Level = 1; c.m_Archetypes = null; c.m_AdditionalClasses = new BlueprintCharacterClassReference[2] { InquistorClass.ToReference<BlueprintCharacterClassReference>(), WarpriestClass.ToReference<BlueprintCharacterClassReference>() }; }); bp.AddComponent<AddStartingEquipment>(c => { c.m_BasicItems = new BlueprintItemReference[1] { MasterworkQuarterstaff.ToReference<BlueprintItemReference>() }; c.m_RestrictedByClass = new BlueprintCharacterClassReference[3] { ClericClass.ToReference<BlueprintCharacterClassReference>(), InquistorClass.ToReference<BlueprintCharacterClassReference>(), WarpriestClass.ToReference<BlueprintCharacterClassReference>() }; }); })); } } }
56.927711
161
0.673228
[ "MIT" ]
factubsio/kadynsWoTRMods
kadynsWOTRMods/Tweaks/Deities/Apsu.cs
9,452
C#
//------------------------------------------------------------------------------ // <auto-generated> // 此代码由工具生成。 // 运行时版本:4.0.30319.42000 // // 对此文件的更改可能会导致不正确的行为,并且如果 // 重新生成代码,这些更改将会丢失。 // </auto-generated> //------------------------------------------------------------------------------ #pragma warning disable 414 namespace VassAddIn { /// [Microsoft.VisualStudio.Tools.Applications.Runtime.StartupObjectAttribute(0)] [global::System.Security.Permissions.PermissionSetAttribute(global::System.Security.Permissions.SecurityAction.Demand, Name="FullTrust")] public sealed partial class ThisAddIn : Microsoft.Office.Tools.AddInBase { internal Microsoft.Office.Tools.CustomTaskPaneCollection CustomTaskPanes; internal Microsoft.Office.Tools.SmartTagCollection VstoSmartTags; [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Tools.Office.ProgrammingModel.dll", "16.0.0.0")] private global::System.Object missing = global::System.Type.Missing; [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Tools.Office.ProgrammingModel.dll", "16.0.0.0")] internal Microsoft.Office.Interop.Excel.Application Application; /// [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Never)] public ThisAddIn(global::Microsoft.Office.Tools.Excel.ApplicationFactory factory, global::System.IServiceProvider serviceProvider) : base(factory, serviceProvider, "AddIn", "ThisAddIn") { Globals.Factory = factory; } /// [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Tools.Office.ProgrammingModel.dll", "16.0.0.0")] [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Never)] protected override void Initialize() { base.Initialize(); this.Application = this.GetHostItem<Microsoft.Office.Interop.Excel.Application>(typeof(Microsoft.Office.Interop.Excel.Application), "Application"); Globals.ThisAddIn = this; global::System.Windows.Forms.Application.EnableVisualStyles(); this.InitializeCachedData(); this.InitializeControls(); this.InitializeComponents(); this.InitializeData(); } /// [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Tools.Office.ProgrammingModel.dll", "16.0.0.0")] [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Never)] protected override void FinishInitialization() { this.InternalStartup(); this.OnStartup(); } /// [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Tools.Office.ProgrammingModel.dll", "16.0.0.0")] [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Never)] protected override void InitializeDataBindings() { this.BeginInitialization(); this.BindToData(); this.EndInitialization(); } /// [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Tools.Office.ProgrammingModel.dll", "16.0.0.0")] [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Never)] private void InitializeCachedData() { if ((this.DataHost == null)) { return; } if (this.DataHost.IsCacheInitialized) { this.DataHost.FillCachedData(this); } } /// [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Tools.Office.ProgrammingModel.dll", "16.0.0.0")] [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Never)] private void InitializeData() { } /// [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Tools.Office.ProgrammingModel.dll", "16.0.0.0")] [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Never)] private void BindToData() { } /// [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] private void StartCaching(string MemberName) { this.DataHost.StartCaching(this, MemberName); } /// [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] private void StopCaching(string MemberName) { this.DataHost.StopCaching(this, MemberName); } /// [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] private bool IsCached(string MemberName) { return this.DataHost.IsCached(this, MemberName); } /// [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Tools.Office.ProgrammingModel.dll", "16.0.0.0")] [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Never)] private void BeginInitialization() { this.BeginInit(); this.CustomTaskPanes.BeginInit(); this.VstoSmartTags.BeginInit(); } /// [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Tools.Office.ProgrammingModel.dll", "16.0.0.0")] [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Never)] private void EndInitialization() { this.VstoSmartTags.EndInit(); this.CustomTaskPanes.EndInit(); this.EndInit(); } /// [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Tools.Office.ProgrammingModel.dll", "16.0.0.0")] [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Never)] private void InitializeControls() { this.CustomTaskPanes = Globals.Factory.CreateCustomTaskPaneCollection(null, null, "CustomTaskPanes", "CustomTaskPanes", this); this.VstoSmartTags = Globals.Factory.CreateSmartTagCollection(null, null, "VstoSmartTags", "VstoSmartTags", this); } /// [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Tools.Office.ProgrammingModel.dll", "16.0.0.0")] [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Never)] private void InitializeComponents() { } /// [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] private bool NeedsFill(string MemberName) { return this.DataHost.NeedsFill(this, MemberName); } /// [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Tools.Office.ProgrammingModel.dll", "16.0.0.0")] [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Never)] protected override void OnShutdown() { this.VstoSmartTags.Dispose(); this.CustomTaskPanes.Dispose(); base.OnShutdown(); } } /// [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Tools.Office.ProgrammingModel.dll", "16.0.0.0")] internal sealed partial class Globals { /// private Globals() { } private static ThisAddIn _ThisAddIn; private static global::Microsoft.Office.Tools.Excel.ApplicationFactory _factory; private static ThisRibbonCollection _ThisRibbonCollection; internal static ThisAddIn ThisAddIn { get { return _ThisAddIn; } set { if ((_ThisAddIn == null)) { _ThisAddIn = value; } else { throw new System.NotSupportedException(); } } } internal static global::Microsoft.Office.Tools.Excel.ApplicationFactory Factory { get { return _factory; } set { if ((_factory == null)) { _factory = value; } else { throw new System.NotSupportedException(); } } } internal static ThisRibbonCollection Ribbons { get { if ((_ThisRibbonCollection == null)) { _ThisRibbonCollection = new ThisRibbonCollection(_factory.GetRibbonFactory()); } return _ThisRibbonCollection; } } } /// [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Tools.Office.ProgrammingModel.dll", "16.0.0.0")] internal sealed partial class ThisRibbonCollection : Microsoft.Office.Tools.Ribbon.RibbonCollectionBase { /// internal ThisRibbonCollection(global::Microsoft.Office.Tools.Ribbon.RibbonFactory factory) : base(factory) { } } }
47.046218
159
0.647495
[ "MIT" ]
Himmelt/VassAddIn
VassAddIn/ThisAddIn.Designer.cs
11,305
C#
using PimApi.ConsoleApp.Renderers.Property; using PimApi.Entities; using System.ComponentModel.DataAnnotations; using System.Net.Http; namespace PimApi.ConsoleApp.Queries.Property { [Display( GroupName = nameof(Property), Order = 300, Description = "Shows properties")] public class GetProperties : IQuery, IQueryWithMessageRenderer, IQueryWithTopSkip { public int? Top { get; set; } public int? Skip { get; set; } IApiResponseMessageRenderer IQueryWithMessageRenderer.MessageRenderer => PropertyListRenderer.Default; public ApiResponseMessage Execute(HttpClient pimApiClient) => pimApiClient.GetAsync(new ODataQuery<PropertyDto> { Count = true, Top = this.GetTopValue(), Skip = this.GetSkipValue(), OrderBy = nameof(PropertyDto.DisplaySequence) }); } }
32.068966
110
0.650538
[ "Apache-2.0" ]
episerver/pim-api
src/PimApi.ConsoleApp/Queries/Property/GetProperties.cs
932
C#
using Framework.Core.Common.Models; using Framework.Core.Exceptions; using System; namespace Framework.Core.Extensions { public static class ValidationExtensions { public static void IsNotNotOrEmpty<TException>(this string str, string errorMessage) where TException : AggregateValidationException { if (string.IsNullOrEmpty(str) || string.IsNullOrWhiteSpace(str)) throw (TException)Activator.CreateInstance(typeof(TException), errorMessage); } public static void IsDateTimeIsFromNowOn<TException>(this DateTimeOffset dateTime, string errorMessage) where TException : AggregateValidationException { if (dateTime == default || dateTime < DateTimeOffset.UtcNow ) throw (TException)Activator.CreateInstance(typeof(TException), errorMessage); } public static void Validate<TException>(this ValidationModel model) where TException : AggregateValidationException { if (model == null) throw new Exception("validation model is empty"); if (model.IsValid == true) return; throw (TException)Activator.CreateInstance(typeof(TException), model.GetValidationErrorMessages()); } } }
38.848485
159
0.682527
[ "MIT" ]
RezaPouya/ModularMonolithApp
0_frameworks/Framework.Core/Extensions/ValidationExtensions.cs
1,284
C#
/*The MIT License (MIT) Copyright (c) 2014 PMU Staff 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.Collections.Generic; using System.Drawing; using System.Text; using PMU.Core; using Client.Logic.Graphics; using SdlDotNet.Widgets; namespace Client.Logic.Menus { /// <summary> /// Description of mnuLinkShop. /// </summary> class mnuMoveRecall : Widgets.BorderedPanel, Core.IMenu { public bool Modal { get; set; } bool loaded; Label[] lblVisibleItems; Label lblItemCollection; Widgets.MenuItemPicker itemPicker; public int currentTen; Label lblItemNum; public List<int> RecallMoves { get; set; } public Widgets.BorderedPanel MenuPanel { get { return this; } } public mnuMoveRecall(string name) : base(name) { base.Size = new Size(315, 360); base.MenuDirection = Enums.MenuDirection.Vertical; base.Location = new Point(10, 40); itemPicker = new Widgets.MenuItemPicker("itemPicker"); itemPicker.Location = new Point(18, 63); lblItemCollection = new Label("lblItemCollection"); lblItemCollection.AutoSize = true; lblItemCollection.Font = FontManager.LoadFont("PMU", 48); lblItemCollection.Text = "Move Recall"; lblItemCollection.Location = new Point(20, 0); lblItemCollection.ForeColor = Color.WhiteSmoke; lblItemNum = new Label("lblItemNum"); //lblItemNum.Size = new Size(100, 30); lblItemNum.AutoSize = true; lblItemNum.Location = new Point(196, 15); lblItemNum.Font = FontManager.LoadFont("PMU", 32); lblItemNum.BackColor = Color.Transparent; lblItemNum.Text = "0/0"; lblItemNum.ForeColor = Color.WhiteSmoke; lblVisibleItems = new Label[10]; for (int i = 0; i < lblVisibleItems.Length; i++) { lblVisibleItems[i] = new Label("lblVisibleItems" + i); //lblVisibleItems[i].AutoSize = true; //lblVisibleItems[i].Size = new Size(200, 32); lblVisibleItems[i].Width = 200; lblVisibleItems[i].Font = FontManager.LoadFont("PMU", 32); lblVisibleItems[i].Location = new Point(35, (i * 30) + 48); //lblVisibleItems[i].HoverColor = Color.Red; lblVisibleItems[i].ForeColor = Color.WhiteSmoke; lblVisibleItems[i].Click += new EventHandler<SdlDotNet.Widgets.MouseButtonEventArgs>(moveItem_Click); this.AddWidget(lblVisibleItems[i]); } this.AddWidget(lblItemCollection); this.AddWidget(lblItemNum); this.AddWidget(itemPicker); //DisplayItems(currentTen * 10 + 1); //ChangeSelected((itemSelected - 1) % 10); //UpdateSelectedItemInfo(); //loaded = true; lblVisibleItems[0].Text = "Loading..."; } public void LoadRecallMoves(string[] parse) { RecallMoves = new List<int>(); if (parse.Length <= 2) { lblVisibleItems[0].Text = "Nothing"; return; } for (int i = 1; i < parse.Length - 1; i++) { RecallMoves.Add(parse[i].ToInt()); } DisplayItems(currentTen * 10); lblItemNum.Text = (currentTen + 1) + "/" + ((RecallMoves.Count - 1) / 10 + 1); loaded = true; } public void ChangeSelected(int itemNum) { itemPicker.Location = new Point(18, 63 + (30 * itemNum)); itemPicker.SelectedItem = itemNum; } void moveItem_Click(object sender, SdlDotNet.Widgets.MouseButtonEventArgs e) { if (loaded) { if (RecallMoves[currentTen * 10 + Array.IndexOf(lblVisibleItems, sender)] > 0) { ChangeSelected(Array.IndexOf(lblVisibleItems, sender)); Music.Music.AudioPlayer.PlaySoundEffect("beep1.wav"); //mnuRecallMoveSelected selectedMenu = (mnuRecallMoveSelected)Windows.WindowSwitcher.GameWindow.MenuManager.FindMenu("mnuRecallMoveSelected"); //if (selectedMenu != null) //{ // Windows.WindowSwitcher.GameWindow.MenuManager.RemoveMenu(selectedMenu); //selectedMenu.ItemSlot = GetSelectedItemSlot(); //selectedMenu.ItemNum = BankItems[GetSelectedItemSlot()].Num; //} // Windows.WindowSwitcher.GameWindow.MenuManager.AddMenu(new Menus.mnuRecallMoveSelected("mnuRecallMoveSelected", GetSelectedItemSlot())); // Windows.WindowSwitcher.GameWindow.MenuManager.SetActiveMenu("mnuRecallMoveSelected"); } } } public void DisplayItems(int startNum) { this.BeginUpdate(); for (int i = 0; i < lblVisibleItems.Length; i++) { //shop menu; lists items and their prices if (startNum + i >= RecallMoves.Count) { lblVisibleItems[i].Text = ""; }else if (RecallMoves[startNum + i] < 1){ lblVisibleItems[i].Text = "---"; } else { lblVisibleItems[i].Text = Moves.MoveHelper.Moves[RecallMoves[startNum + i]].Name; } } this.EndUpdate(); } private int GetSelectedItemSlot() { return itemPicker.SelectedItem + currentTen * 10; } public override void OnKeyboardDown(SdlDotNet.Input.KeyboardEventArgs e) { if (RecallMoves.Count == 0) { return; } if (loaded) { base.OnKeyboardDown(e); switch (e.Key) { case SdlDotNet.Input.Key.DownArrow: { if (itemPicker.SelectedItem >= 9 || currentTen*10 + itemPicker.SelectedItem >= RecallMoves.Count - 1) { ChangeSelected(0); //DisplayItems(1); } else { ChangeSelected(itemPicker.SelectedItem + 1); } Music.Music.AudioPlayer.PlaySoundEffect("beep1.wav"); } break; case SdlDotNet.Input.Key.UpArrow: { if (itemPicker.SelectedItem <= 0) { ChangeSelected(9); } else { ChangeSelected(itemPicker.SelectedItem - 1); } if (currentTen*10 + itemPicker.SelectedItem > RecallMoves.Count) { ChangeSelected(RecallMoves.Count - currentTen*10 - 1); } Music.Music.AudioPlayer.PlaySoundEffect("beep1.wav"); } break; case SdlDotNet.Input.Key.LeftArrow: { //int itemSlot = (currentTen + 1) - 10;//System.Math.Max(1, GetSelectedItemSlot() - (11 - itemPicker.SelectedItem)); if (currentTen <= 0) { currentTen = ((RecallMoves.Count - 1) / 10); } else { currentTen--; } if (currentTen*10 + itemPicker.SelectedItem >= RecallMoves.Count) { ChangeSelected(RecallMoves.Count - currentTen*10 - 1); } DisplayItems(currentTen * 10); lblItemNum.Text = (currentTen + 1) + "/" + ((RecallMoves.Count - 1) / 10 + 1); Music.Music.AudioPlayer.PlaySoundEffect("beep4.wav"); } break; case SdlDotNet.Input.Key.RightArrow: { //int itemSlot = currentTen + 1 + 10; if (currentTen >= ((RecallMoves.Count - 1) / 10)) { currentTen = 0; } else { currentTen++; } if (currentTen*10 + itemPicker.SelectedItem >= RecallMoves.Count) { ChangeSelected(RecallMoves.Count - currentTen*10 - 1); } DisplayItems(currentTen * 10); lblItemNum.Text = (currentTen + 1) + "/" + ((RecallMoves.Count - 1) / 10 + 1); Music.Music.AudioPlayer.PlaySoundEffect("beep4.wav"); } break; case SdlDotNet.Input.Key.Return: { if (GetSelectedItemSlot() > -1 && GetSelectedItemSlot() < RecallMoves.Count && RecallMoves[GetSelectedItemSlot()] > -1) { //Windows.WindowSwitcher.GameWindow.MenuManager.AddMenu(new Menus.mnuRecallMoveSelected("mnuRecallMoveSelected", GetSelectedItemSlot())); //Windows.WindowSwitcher.GameWindow.MenuManager.SetActiveMenu("mnuRecallMoveSelected"); Network.Messenger.SendRecallMove(RecallMoves[GetSelectedItemSlot()]); MenuSwitcher.CloseAllMenus(); } } break; } } } } }
40.085911
169
0.490527
[ "MIT" ]
PMUniverse/PMU-Client
Client/Menus/mnuMoveRecall.cs
11,667
C#
using System; using System.Collections.Generic; using System.Text; using FlubuCore.Context; using FlubuCore.Tasks; using FlubuCore.Tasks.Process; namespace FlubuCore.Azure.Tasks.Ad { public partial class AzureAdGroupCreateTask : ExternalProcessTaskBase<AzureAdGroupCreateTask> { /// <summary> /// Create a group in the directory. /// </summary> public AzureAdGroupCreateTask(string displayName = null , string mailNickname = null) { WithArguments("az ad group create"); WithArguments("--display-name"); if (!string.IsNullOrEmpty(displayName)) { WithArguments(displayName); } WithArguments("--mail-nickname"); if (!string.IsNullOrEmpty(mailNickname)) { WithArguments(mailNickname); } } protected override string Description { get; set; } } }
25.105263
98
0.60587
[ "MIT" ]
flubu-core/FlubuCore.Azure
FlubuCore.Azure/Tasks/Ad/AzureAdGroupCreateTask.cs
954
C#
namespace PhotoShare.Client.Core.Commands { using System; using System.Linq; using PhotoShare.Client.Utilities; using PhotoShare.Data; using PhotoShare.Models; public class CreateAlbumCommand : ICommand { public string Execute(string[] data) { var username = data[0]; var title = data[1]; var colorToString = data[2]; var tags = data.Skip(3).Select(tag => TagUtilities.ValidateOrTransform(tag)).ToArray(); using (PhotoShareContext context = new PhotoShareContext()) { if (Session.User == null || Session.User.Username != username) { throw new InvalidOperationException("Invalid credentials!"); } var user = context.Users.SingleOrDefault(u => u.Username == username); if (user == null) { throw new ArgumentException($"User {username} not found!"); } if (context.Albums.SingleOrDefault(a => a.Name == title) != null) { throw new ArgumentException($"Album {title} exists!"); } object color; Enum.TryParse(typeof(Color), colorToString, out color); if (color == null) { throw new ArgumentException($"Color {colorToString} not found!"); } foreach (var tag in tags) { if (context.Tags.SingleOrDefault(t => t.Name == tag) == null) { throw new ArgumentException("Invalid tags!"); } } Album album = new Album { Name = title, BackgroundColor = (Color) color }; context.AlbumRoles.Add(new AlbumRole { User = user, Album = album, Role = Role.Owner }); foreach (var tag in tags) { var currentTag = context.Tags.SingleOrDefault(t => t.Name == tag); context.AlbumTags.Add(new AlbumTag { Tag = currentTag, Album = album }); } context.SaveChanges(); return $"Album {title} successfully created!"; } } } }
30.928571
99
0.443803
[ "MIT" ]
vpaleshnikov/SoftUni-CSharpDBFundamentalsModule
Databases Advanced - Entity Framework/07. Best Practices and Architecture/PhotoShare/PhotoShare.Client/Core/Commands/CreateAlbumCommand.cs
2,600
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Lpp.Dns.DataMart.Client { public partial class OutputPathSelectionForm : Form { List<OutputPathSelectionItem> _outputPaths = new List<OutputPathSelectionItem>(); public IDictionary<Guid, string> OutputPaths { get { return _outputPaths.ToDictionary(item => item.Identifier, item => item.OutputPath); } } public OutputPathSelectionForm() { InitializeComponent(); } public OutputPathSelectionForm(IDictionary<Guid, string> queryIdentifiers) { var qi = queryIdentifiers ?? new Dictionary<Guid, string>(); foreach(var identifier in qi) { _outputPaths.Add(new OutputPathSelectionItem { Descriptor = identifier.Value, Identifier = identifier.Key }); } InitializeComponent(); dataGridView1.AutoGenerateColumns = false; dataGridView1.DataSource = _outputPaths; } private void btnContinue_Click(object sender, EventArgs e) { this.DialogResult = DialogResult.OK; this.Close(); } private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e) { if(e.ColumnIndex == 2) { OutputPathSelectionItem item = _outputPaths[e.RowIndex]; var dialog = new SaveFileDialog() { AddExtension = true, Filter = "CSV Files (*.csv)|*.csv|All Files (*.*)|*.*", DefaultExt="csv", RestoreDirectory=true }; if (!string.IsNullOrEmpty(item.OutputPath)) { dialog.FileName = System.IO.Path.GetFileName(item.OutputPath); dialog.InitialDirectory = System.IO.Path.GetDirectoryName(item.OutputPath); } if (dialog.ShowDialog(this) == DialogResult.OK) { item.OutputPath = dialog.FileName; dataGridView1.InvalidateRow(e.RowIndex); } } } } internal class OutputPathSelectionItem { public Guid Identifier { get; set; } public string Descriptor { get; set; } public string OutputPath { get; set; } } }
31.675
171
0.587609
[ "Apache-2.0" ]
Missouri-BMI/popmednet
Lpp.Adapters/Lpp.Dns.DataMart.Client/Forms/OutputPathSelectionForm.cs
2,536
C#
using Alex.Networking.Java.Packets.Play; using Alex.Worlds; using ConcreteMC.MolangSharp.Attributes; namespace Alex.Entities.Passive { public abstract class ChestedHorse : AbstractHorse { /// <inheritdoc /> [MoProperty("is_chested")] public override bool IsChested { get { return base.IsChested; } set { base.IsChested = value; InvokeControllerUpdate(); /* var modelRenderer = ModelRenderer; if (modelRenderer != null) { modelRenderer.SetVisibility("Bag1", value); modelRenderer.SetVisibility("Bag2", value); }*/ } } /// <inheritdoc /> protected ChestedHorse(World level) : base(level) { } /// <inheritdoc /> protected override void HandleJavaMeta(MetaDataEntry entry) { base.HandleJavaMeta(entry); if (entry.Index == 19 && entry is MetadataBool val) { IsChested = val.Value; } } } }
19.391304
61
0.656951
[ "MPL-2.0" ]
ConcreteMC/Alex
src/Alex/Entities/Passive/ChestedHorse.cs
892
C#
namespace SiteConstructor.Framework.Table { public class Sort { public string Predicate { get; set; } public bool Reverse { get; set; } } }
17
45
0.605882
[ "MIT" ]
LeshaOrlov/SiteConstructor
SiteConstructor.Framework/SmartTable/Sort.cs
172
C#
using Extensions.Enums; using Extensions.ListViewHelp; using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Linq; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; namespace Extensions { /// <summary>Represents a collection of useful reusable methods.</summary> public static class Functions { /// <summary>Verifies that the requested file exists and that its file size is greater than zero. If not, it extracts the embedded file to the local output folder.</summary> /// <param name="resourceStream">Resource Stream from Assembly.GetExecutingAssembly().GetManifestResourceStream()</param> /// <param name="resourceName">Resource name</param> public static void VerifyFileIntegrity(Stream resourceStream, string resourceName) => VerifyFileIntegrity(resourceStream, resourceName, Directory.GetCurrentDirectory()); /// <summary>Verifies that the requested file exists and that its file size is greater than zero. If not, it extracts the embedded file to the local output folder.</summary> /// <param name="resourceStream">Resource Stream from Assembly.GetExecutingAssembly().GetManifestResourceStream()</param> /// <param name="resourceName">Resource name</param> /// <param name="directory">Directory to be extracted to</param> public static void VerifyFileIntegrity(Stream resourceStream, string resourceName, string directory) { FileInfo fileInfo = new FileInfo(Path.Combine(directory, resourceName)); if (!File.Exists(Path.Combine(directory, resourceName)) || fileInfo.Length == 0) ExtractEmbeddedResource(resourceStream, resourceName, directory); } /// <summary>Extracts an embedded resource from a Stream.</summary> /// <param name="resourceStream">Resource Stream from Assembly.GetExecutingAssembly().GetManifestResourceStream()</param> /// <param name="resourceName">Resource name</param> public static void ExtractEmbeddedResource(Stream resourceStream, string resourceName) => ExtractEmbeddedResource(resourceStream, resourceName, Directory.GetCurrentDirectory()); /// <summary>Extracts an embedded resource from a Stream.</summary> /// <param name="resourceStream">Resource Stream from Assembly.GetExecutingAssembly().GetManifestResourceStream()</param> /// <param name="resourceName">Resource name</param> /// <param name="directory">Directory to be extracted to</param> public static void ExtractEmbeddedResource(Stream resourceStream, string resourceName, string directory) { if (resourceStream != null) { using (BinaryReader r = new BinaryReader(resourceStream)) { using (FileStream fs = new FileStream(directory + "\\" + resourceName, FileMode.OpenOrCreate)) { using (BinaryWriter w = new BinaryWriter(fs)) { w.Write(r.ReadBytes((int)resourceStream.Length)); } } } } } /// <summary>Turns several Keyboard.Keys into a list of Keys which can be tested using List.Any.</summary> /// <param name="keys">Array of Keys</param> /// <returns>Returns list of Keys' IsKeyDown state</returns> private static IEnumerable<bool> GetListOfKeys(params Key[] keys) => keys.Select(Keyboard.IsKeyDown).ToList(); #region Control Manipulation /// <summary>Adds a blank line between a TextBox's current text and the text to be added.</summary> /// <param name="tb">TextBox</param> /// <param name="newText">Text to be added</param> public static void AddTextToTextBox(TextBox tb, string newText) { tb.Text = string.IsNullOrWhiteSpace(tb.Text) ? newText : $"{tb.Text}\n\n{newText}"; tb.Focus(); tb.CaretIndex = tb.Text.Length; tb.ScrollToEnd(); } /// <summary>Modifies a ListView to be sortable by a newly clicked column.</summary> /// <param name="sender">Passed column</param> /// <param name="sort">Class containing current column and adorner sort</param> /// <param name="currentListView">ListView needing modification</param> /// <param name="color">Color for the adorner</param> public static ListViewSort ListViewColumnHeaderClick(object sender, ListViewSort sort, ListView currentListView, string color) { Color selectedColor = Colors.Black; if (!string.IsNullOrWhiteSpace(color)) selectedColor = (Color)ColorConverter.ConvertFromString(color); GridViewColumnHeader column = (sender as GridViewColumnHeader); if (column != null) { string sortBy = column.Tag.ToString(); if (sort.Column != null) { AdornerLayer.GetAdornerLayer(sort.Column).Remove(sort.Adorner); currentListView.Items.SortDescriptions.Clear(); } ListSortDirection newDir = ListSortDirection.Ascending; if (Equals(sort.Column, column) && sort.Adorner.Direction == newDir) newDir = ListSortDirection.Descending; sort.Column = column; sort.Adorner = new SortAdorner(sort.Column, newDir, selectedColor); AdornerLayer.GetAdornerLayer(sort.Column).Add(sort.Adorner); currentListView.Items.SortDescriptions.Add(new SortDescription(sortBy, newDir)); } return sort; } /// <summary>Selects all text in passed PasswordBox.</summary> /// <param name="sender">Object to be cast</param> public static void PasswordBoxGotFocus(object sender) { PasswordBox txt = (PasswordBox)sender; txt.SelectAll(); } /// <summary>Previews a pressed key and determines whether or not it is acceptable input.</summary> /// <param name="e">Key being pressed</param> /// <param name="keyType">Type of input allowed</param> public static void PreviewKeyDown(KeyEventArgs e, KeyType keyType) { Key k = e.Key; IEnumerable<bool> keys = GetListOfKeys(Key.Back, Key.Delete, Key.Home, Key.End, Key.LeftShift, Key.RightShift, Key.Enter, Key.Tab, Key.LeftAlt, Key.RightAlt, Key.Left, Key.Right, Key.LeftCtrl, Key.RightCtrl, Key.Escape); switch (keyType) { case KeyType.Decimals: e.Handled = !keys.Any(key => key) && (Key.D0 > k || k > Key.D9) && (Key.NumPad0 > k || k > Key.NumPad9) && k != Key.Decimal && k != Key.OemPeriod; break; case KeyType.Integers: e.Handled = !keys.Any(key => key) && (Key.D0 > k || k > Key.D9) && (Key.NumPad0 > k || k > Key.NumPad9); break; case KeyType.Letters: e.Handled = !keys.Any(key => key) && (Key.A > k || k > Key.Z) && (Key.D0 > k || k > Key.D9) && (Key.NumPad0 > k || k > Key.NumPad9); break; case KeyType.LettersSpace: e.Handled = !keys.Any(key => key) && (Key.A > k || k > Key.Z) && k != Key.Space; break; case KeyType.LettersSpaceComma: e.Handled = !keys.Any(key => key) && (Key.A > k || k > Key.Z) && k != Key.Space && k != Key.OemComma; break; case KeyType.LettersIntegersSpace: e.Handled = !keys.Any(key => key) && (Key.A > k || k > Key.Z) && (Key.D0 > k || k > Key.D9) && (Key.NumPad0 > k || k > Key.NumPad9) && k != Key.Space; break; case KeyType.LettersIntegersSpaceComma: e.Handled = !keys.Any(key => key) && (Key.A > k || k > Key.Z) && (Key.D0 > k || k > Key.D9) && (Key.NumPad0 > k || k > Key.NumPad9) && k != Key.Space && k != Key.OemComma; break; case KeyType.NegativeDecimals: e.Handled = !keys.Any(key => key) && (Key.D0 > k || k > Key.D9) && (Key.NumPad0 > k || k > Key.NumPad9) && k != Key.Decimal && k != Key.Subtract && k != Key.OemPeriod && k != Key.OemMinus; break; case KeyType.NegativeIntegers: e.Handled = !keys.Any(key => key) && (Key.D0 > k || k > Key.D9) && (Key.NumPad0 > k || k > Key.NumPad9) && k != Key.Subtract && k != Key.OemMinus; break; default: throw new ArgumentOutOfRangeException(nameof(keyType), keyType, null); //&& !(Key.D0 <= k && k <= Key.D9) && !(Key.NumPad0 <= k && k <= Key.NumPad9)) //|| k == Key.OemMinus || k == Key.Subtract || k == Key.Decimal || k == Key.OemPeriod) //System.Media.SystemSound ss = System.Media.SystemSounds.Beep; //ss.Play(); } } /// <summary>Selects all text in passed TextBox.</summary> /// <param name="sender">Object to be cast</param> public static void TextBoxGotFocus(object sender) { TextBox txt = (TextBox)sender; txt.SelectAll(); } /// <summary>Deletes all text in textbox which isn't acceptable input.</summary> /// <param name="sender">Object to be cast</param> /// <param name="keyType">Type of input allowed</param> public static void TextBoxTextChanged(object sender, KeyType keyType) { TextBox txt = (TextBox)sender; switch (keyType) { case KeyType.Decimals: txt.Text = new string((from c in txt.Text where char.IsDigit(c) || c.IsPeriod() select c).ToArray()); if (txt.Text.Substring(txt.Text.IndexOf(".", StringComparison.Ordinal) + 1).Contains(".")) txt.Text = txt.Text.Substring(0, txt.Text.IndexOf(".", StringComparison.Ordinal) + 1) + txt.Text .Substring(txt.Text.IndexOf(".", StringComparison.Ordinal) + 1).Replace(".", ""); break; case KeyType.Integers: txt.Text = new string((from c in txt.Text where char.IsDigit(c) select c).ToArray()); break; case KeyType.Letters: txt.Text = new string((from c in txt.Text where char.IsLetter(c) select c).ToArray()); break; case KeyType.LettersSpace: txt.Text = new string((from c in txt.Text where char.IsLetter(c) || c.IsSpace() select c).ToArray()); break; case KeyType.LettersSpaceComma: txt.Text = new string((from c in txt.Text where char.IsLetter(c) || c.IsSpace() || c.IsComma() select c).ToArray()); break; case KeyType.LettersIntegersSpace: txt.Text = new string((from c in txt.Text where char.IsLetterOrDigit(c) || c.IsSpace() select c).ToArray()); break; case KeyType.LettersIntegersSpaceComma: txt.Text = new string((from c in txt.Text where char.IsLetterOrDigit(c) || c.IsSpace() || c.IsComma() select c).ToArray()); break; case KeyType.NegativeDecimals: txt.Text = new string((from c in txt.Text where char.IsDigit(c) || c.IsPeriod() || c.IsHyphen() select c).ToArray()); if (txt.Text.Substring(txt.Text.IndexOf(".", StringComparison.Ordinal) + 1).Contains(".")) txt.Text = txt.Text.Substring(0, txt.Text.IndexOf(".", StringComparison.Ordinal) + 1) + txt.Text .Substring(txt.Text.IndexOf(".", StringComparison.Ordinal) + 1).Replace(".", ""); if (txt.Text.Substring(txt.Text.IndexOf("-", StringComparison.Ordinal) + 1).Contains("-")) txt.Text = txt.Text.Substring(0, txt.Text.IndexOf("-", StringComparison.Ordinal) + 1) + txt.Text .Substring(txt.Text.IndexOf("-", StringComparison.Ordinal) + 1).Replace("-", ""); break; case KeyType.NegativeIntegers: txt.Text = new string((from c in txt.Text where char.IsDigit(c) || c.IsHyphen() select c).ToArray()); if (txt.Text.Substring(txt.Text.IndexOf("-", StringComparison.Ordinal) + 1).Contains("-")) txt.Text = txt.Text.Substring(0, txt.Text.IndexOf("-", StringComparison.Ordinal) + 1) + txt.Text .Substring(txt.Text.IndexOf("-", StringComparison.Ordinal) + 1).Replace("-", ""); break; default: throw new ArgumentOutOfRangeException(nameof(keyType), keyType, null); } } #endregion Control Manipulation #region Random Number Generation /// <summary>Generates a random number between min and max (inclusive).</summary> /// <param name="min">Inclusive minimum number</param> /// <param name="max">Inclusive maximum number</param> /// <param name="lowerLimit">Minimum limit for the method, regardless of min and max.</param> /// <param name="upperLimit">Maximum limit for the method, regardless of min and max.</param> /// <returns>Returns randomly generated integer between min and max with an upper limit of upperLimit.</returns> public static int GenerateRandomNumber(int min, int max, int lowerLimit = int.MinValue, int upperLimit = int.MaxValue) { if (min < lowerLimit) min = lowerLimit; if (max > upperLimit) max = upperLimit; int result = min < max ? ThreadSafeRandom.ThisThreadsRandom.Next(min, max + 1) : ThreadSafeRandom.ThisThreadsRandom.Next(max, min + 1); return result; } #endregion Random Number Generation } }
51.323432
185
0.534178
[ "MIT" ]
pfthroaway/Backup
Extensions/Functions.cs
15,553
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("RestService.Tests")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("RestService.Tests")] [assembly: AssemblyCopyright("Copyright © Microsoft 2011")] [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("82e64c30-e78c-4c26-9328-9184d9f9d078")] // 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.486486
85
0.730322
[ "BSD-3-Clause" ]
TellagoDevLabs/Hermes
src/RestService.Tests/Properties/AssemblyInfo.cs
1,464
C#
namespace Blog.Data.Repositories.MailLists { using Models.Emails; using DataAccess; using Data.Base; public interface IMailListRepository : IRepository<MailList>, ITransientRepository { } }
19.636364
86
0.722222
[ "MIT" ]
KaloyanIT/BlogSystem
src/Blog.Data.Repositories/MailLists/IMailListRepository.cs
218
C#
using System; using System.Buffers; using System.Runtime.CompilerServices; #if NETCOREAPP using System.Runtime.Intrinsics.X86; #endif using Quickenshtein.Internal; namespace Quickenshtein { /// <summary> /// Quick Levenshtein Distance Calculator /// </summary> public static partial class Levenshtein { #if NETSTANDARD [MethodImpl(MethodImplOptions.NoInlining)] public static int GetDistance(string source, string target) { return GetDistance(source, target, CalculationOptions.Default); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static unsafe int GetDistance(string source, string target, CalculationOptions calculationOptions) { //Shortcut any processing if either string is empty if (source == null || source.Length == 0) { return target?.Length ?? 0; } if (target == null || target.Length == 0) { return source.Length; } fixed (char* sourcePtr = source) fixed (char* targetPtr = target) { return CalculateDistance(sourcePtr, targetPtr, source.Length, target.Length, calculationOptions); } } #endif public static unsafe int GetDistance(ReadOnlySpan<char> source, ReadOnlySpan<char> target) { return GetDistance(source, target, CalculationOptions.Default); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static unsafe int GetDistance(ReadOnlySpan<char> source, ReadOnlySpan<char> target, CalculationOptions calculationOptions) { var sourceLength = source.Length; var targetLength = target.Length; //Shortcut any processing if either string is empty if (sourceLength == 0) { return targetLength; } if (targetLength == 0) { return sourceLength; } fixed (char* sourcePtr = source) fixed (char* targetPtr = target) { return CalculateDistance(sourcePtr, targetPtr, sourceLength, targetLength, calculationOptions); } } private static unsafe int CalculateDistance(char* sourcePtr, char* targetPtr, int sourceLength, int targetLength, CalculationOptions calculationOptions) { //Identify and trim any common prefix or suffix between the strings var offset = DataHelper.GetIndexOfFirstNonMatchingCharacter(sourcePtr, targetPtr, sourceLength, targetLength); sourcePtr += offset; targetPtr += offset; sourceLength -= offset; targetLength -= offset; DataHelper.TrimLengthOfMatchingCharacters(sourcePtr, targetPtr, ref sourceLength, ref targetLength); //Check the trimmed values are not empty if (sourceLength == 0) { return targetLength; } if (targetLength == 0) { return sourceLength; } //Switch around variables so outer loop has fewer iterations if (targetLength < sourceLength) { var tempSourcePtr = sourcePtr; sourcePtr = targetPtr; targetPtr = tempSourcePtr; (sourceLength, targetLength) = (targetLength, sourceLength); } if (targetLength >= calculationOptions.EnableThreadingAfterXCharacters) { return CalculateDistance_MultiThreaded(sourcePtr, targetPtr, sourceLength, targetLength, calculationOptions); } #if NETCOREAPP if (Sse41.IsSupported) { //Levenshtein Distance diagonal calculation inspired by Anna Henningsen's C implementation //https://github.com/addaleax/levenshtein-sse if (sourceLength > 16 && sourceLength < ushort.MaxValue && targetLength < ushort.MaxValue) { var diag1Array = ArrayPool<ushort>.Shared.Rent(sourceLength + 1); var diag2Array = ArrayPool<ushort>.Shared.Rent(sourceLength + 1); fixed (void* diag1Ptr = diag1Array) fixed (void* diag2Ptr = diag2Array) { var result = CalculateDiagonal_MinSse41<ushort>(diag1Ptr, diag2Ptr, sourcePtr, sourceLength, targetPtr, targetLength); ArrayPool<ushort>.Shared.Return(diag1Array); ArrayPool<ushort>.Shared.Return(diag2Array); return result; } } else { var diag1Array = ArrayPool<int>.Shared.Rent(sourceLength + 1); var diag2Array = ArrayPool<int>.Shared.Rent(sourceLength + 1); fixed (void* diag1Ptr = diag1Array) fixed (void* diag2Ptr = diag2Array) { var result = CalculateDiagonal_MinSse41<int>(diag1Ptr, diag2Ptr, sourcePtr, sourceLength, targetPtr, targetLength); ArrayPool<int>.Shared.Return(diag1Array); ArrayPool<int>.Shared.Return(diag2Array); return result; } } } #endif var pooledArray = ArrayPool<int>.Shared.Rent(targetLength); fixed (int* previousRowPtr = pooledArray) { DataHelper.SequentialFill(previousRowPtr, targetLength); var rowIndex = 0; //Levenshtein Distance outer loop unrolling inspired by Gustaf Andersson's JS implementation //https://github.com/gustf/js-levenshtein/blob/55ca1bf22bd55aa81cb5836c63582da6e9fb5fb0/index.js#L71-L90 CalculateRows_4Rows(previousRowPtr, sourcePtr, sourceLength, ref rowIndex, targetPtr, targetLength); //Calculate Single Rows for (; rowIndex < sourceLength; rowIndex++) { var lastSubstitutionCost = rowIndex; var lastInsertionCost = rowIndex + 1; var sourcePrevChar = sourcePtr[rowIndex]; CalculateRow(previousRowPtr, targetPtr, targetLength, sourcePrevChar, lastInsertionCost, lastSubstitutionCost); } var result = previousRowPtr[targetLength - 1]; ArrayPool<int>.Shared.Return(pooledArray); return result; } } } }
30.959538
154
0.722741
[ "MIT" ]
Daniel-Svensson/Quickenshtein
src/Quickenshtein/Levenshtein.cs
5,358
C#
using System.Runtime.InteropServices; namespace X86Sharp { [StructLayout(LayoutKind.Sequential)] public struct GDT { private ushort _limit1; private ushort _base1; private byte _base2; private sbyte _access; private sbyte _limit2AndFlags; private byte _base3; public uint Limit { get => (uint)(_limit1 + (_limit2AndFlags & 0x0f) << 0x10); set { _limit1 = (ushort)value; _limit2AndFlags = (sbyte)((value & 0x0fffffff) >> 0x10); } } public uint BaseAddress { get => (uint)(_base1 + (_base2 << 0x10) + (_base3 << 0x18)); set { _base1 = (ushort)value; _base2 = (byte)(value >> 0x10); _base3 = (byte)(value >> 0x18); } } private bool GetAccessNthBit(int n) => (_access & n) == n; private void SetAccessNthBit(int n, bool val) { if (val) _access |= (sbyte)n; else _access &= (sbyte)~n; } private bool GetFlagNthBit(int n) => (_limit2AndFlags & n) == n; private void SetFlagNthBit(int n, bool val) { if (val) _limit2AndFlags |= (sbyte)n; else _limit2AndFlags |= (sbyte)~n; } #region Access public bool Accessed { get => GetAccessNthBit(0x01); set => SetAccessNthBit(0x01, value); } public bool IsReadable => IsCode && GetAccessNthBit(0x02); public bool IsWritable { get => !IsCode && GetAccessNthBit(0x02); set => SetAccessNthBit(0x02, value); } public bool Conforming => IsCode && GetAccessNthBit(0x04); public bool Expansion => !IsCode && GetAccessNthBit(0x04); public bool IsCode { get => GetAccessNthBit(0x08); set => SetAccessNthBit(0x08, value); } public bool IsSystemSegment => GetAccessNthBit(0x10); public byte PrevLevel => (byte)(_access & 0x60); public bool IsPresent => GetAccessNthBit(0x80); #endregion #region Flags public bool Is32Bit { get => GetFlagNthBit(0x40); set => SetFlagNthBit(0x40, value); } public bool Granularity => GetFlagNthBit(0x80); #endregion } }
25.27451
72
0.496509
[ "MIT" ]
20chan/X86Sharp
X86Sharp/GDT.cs
2,580
C#
using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Text.Json.Serialization; using EntityConfiguration.Entities.Base; using EntityConfiguration.Entities.Owned; namespace EntityConfiguration.Entities { [Table("Products", Schema = "Store")] public class Product : EntityBase { public ProductDetails Details { get; set; } = new ProductDetails(); public bool IsFeatured { get; set; } [DataType(DataType.Currency)] public decimal UnitCost { get; set; } [DataType(DataType.Currency)] public decimal CurrentPrice { get; set; } public int UnitsInStock { get; set; } [Required] public int CategoryId { get; set; } [JsonIgnore] [ForeignKey(nameof(CategoryId))] public Category CategoryNavigation { get; set; } [InverseProperty(nameof(ShoppingCartRecord.ProductNavigation))] public List<ShoppingCartRecord> ShoppingCartRecords { get; set; } = new List<ShoppingCartRecord>(); [InverseProperty(nameof(OrderDetail.ProductNavigation))] public List<OrderDetail> OrderDetails { get; set; } = new List<OrderDetail>(); [NotMapped] public string CategoryName => CategoryNavigation?.CategoryName; } }
35.828571
79
0.739234
[ "BSD-3-Clause", "MIT" ]
RomitMehta/presentations
DOTNETCORE/Channel9_EFCoreShows/EntityFrameworkCoreExamples/DbContextConfiguration/Entities/Product.cs
1,256
C#
using System.Collections.Generic; using Essensoft.Paylink.Alipay.Response; namespace Essensoft.Paylink.Alipay.Request { /// <summary> /// alipay.ins.data.dsb.estimate.sync /// </summary> public class AlipayInsDataDsbEstimateSyncRequest : IAlipayRequest<AlipayInsDataDsbEstimateSyncResponse> { /// <summary> /// 同步机构定损/核损结果 /// </summary> public string BizContent { get; set; } #region IAlipayRequest Members private bool needEncrypt = false; private string apiVersion = "1.0"; private string terminalType; private string terminalInfo; private string prodCode; private string notifyUrl; private string returnUrl; private AlipayObject bizModel; private Dictionary<string, string> udfParams; //add user-defined text parameters public void SetNeedEncrypt(bool needEncrypt) { this.needEncrypt = needEncrypt; } public bool GetNeedEncrypt() { return needEncrypt; } public void SetNotifyUrl(string notifyUrl) { this.notifyUrl = notifyUrl; } public string GetNotifyUrl() { return notifyUrl; } public void SetReturnUrl(string returnUrl) { this.returnUrl = returnUrl; } public string GetReturnUrl() { return returnUrl; } public void SetTerminalType(string terminalType) { this.terminalType = terminalType; } public string GetTerminalType() { return terminalType; } public void SetTerminalInfo(string terminalInfo) { this.terminalInfo = terminalInfo; } public string GetTerminalInfo() { return terminalInfo; } public void SetProdCode(string prodCode) { this.prodCode = prodCode; } public string GetProdCode() { return prodCode; } public string GetApiName() { return "alipay.ins.data.dsb.estimate.sync"; } public void SetApiVersion(string apiVersion) { this.apiVersion = apiVersion; } public string GetApiVersion() { return apiVersion; } public void PutOtherTextParam(string key, string value) { if (udfParams == null) { udfParams = new Dictionary<string, string>(); } udfParams.Add(key, value); } public IDictionary<string, string> GetParameters() { var parameters = new AlipayDictionary { { "biz_content", BizContent } }; if (udfParams != null) { parameters.AddAll(udfParams); } return parameters; } public AlipayObject GetBizModel() { return bizModel; } public void SetBizModel(AlipayObject bizModel) { this.bizModel = bizModel; } #endregion } }
23.507246
107
0.537916
[ "MIT" ]
Frunck8206/payment
src/Essensoft.Paylink.Alipay/Request/AlipayInsDataDsbEstimateSyncRequest.cs
3,266
C#
using System; using System.Collections.Generic; public static class ArmstrongNumbers { public static bool IsArmstrongNumber(int number) { string numberString = number.ToString(); double sum = 0; foreach (char n in numberString) { sum += (int)Math.Pow((int)char.GetNumericValue(n), numberString.Length); } return sum == number; } }
22.555556
84
0.62069
[ "MIT" ]
jjkeyser/exercism
csharp/armstrong-numbers/ArmstrongNumbers.cs
408
C#
// Copyright (c) 2022 TrakHound Inc., All Rights Reserved. // This file is subject to the terms and conditions defined in // file 'LICENSE', which is part of this source code package. using MTConnect.Devices.References; namespace MTConnect.Devices.Xml { /// <summary> /// DataItemRef XML element is a pointer to a Data Entity associated with another Structural Element defined elsewhere in the XML document for a piece of equipment. /// DataItemRef allows the data associated with a data item defined in another Structural Element to be directly associated with this XML element. /// </summary> public class XmlDataItemReference : XmlReference { public XmlDataItemReference() { } public XmlDataItemReference(DataItemReference reference) { if (reference != null) { IdRef = reference.IdRef; Name = reference.Name; } } public override Reference ToReference() { var reference = new DataItemReference(); reference.IdRef = IdRef; reference.Name = Name; return reference; } } }
32.666667
168
0.640306
[ "Apache-2.0" ]
TrakHound/MTConnect
src/MTConnect.NET-XML/Devices/Xml/XmlDataItemReference.cs
1,176
C#
/* * Copyright 2010-2014 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 batch-2016-08-10.normal.json service model. */ using System; using System.Runtime.ExceptionServices; using System.Threading; using System.Threading.Tasks; using System.Collections.Generic; using Amazon.Batch.Model; using Amazon.Batch.Model.Internal.MarshallTransformations; using Amazon.Batch.Internal; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Auth; using Amazon.Runtime.Internal.Transform; namespace Amazon.Batch { /// <summary> /// Implementation for accessing Batch /// /// AWS Batch enables you to run batch computing workloads on the AWS Cloud. Batch computing /// is a common way for developers, scientists, and engineers to access large amounts /// of compute resources, and AWS Batch removes the undifferentiated heavy lifting of /// configuring and managing the required infrastructure. AWS Batch will be familiar to /// users of traditional batch computing software. This service can efficiently provision /// resources in response to jobs submitted in order to eliminate capacity constraints, /// reduce compute costs, and deliver results quickly. /// /// /// <para> /// As a fully managed service, AWS Batch enables developers, scientists, and engineers /// to run batch computing workloads of any scale. AWS Batch automatically provisions /// compute resources and optimizes the workload distribution based on the quantity and /// scale of the workloads. With AWS Batch, there is no need to install or manage batch /// computing software, which allows you to focus on analyzing results and solving problems. /// AWS Batch reduces operational complexities, saves time, and reduces costs, which makes /// it easy for developers, scientists, and engineers to run their batch jobs in the AWS /// Cloud. /// </para> /// </summary> public partial class AmazonBatchClient : AmazonServiceClient, IAmazonBatch { private static IServiceMetadata serviceMetadata = new AmazonBatchMetadata(); #region Constructors /// <summary> /// Constructs AmazonBatchClient with the credentials loaded from the application's /// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance. /// /// Example App.config with credentials set. /// <code> /// &lt;?xml version="1.0" encoding="utf-8" ?&gt; /// &lt;configuration&gt; /// &lt;appSettings&gt; /// &lt;add key="AWSProfileName" value="AWS Default"/&gt; /// &lt;/appSettings&gt; /// &lt;/configuration&gt; /// </code> /// /// </summary> public AmazonBatchClient() : base(FallbackCredentialsFactory.GetCredentials(), new AmazonBatchConfig()) { } /// <summary> /// Constructs AmazonBatchClient with the credentials loaded from the application's /// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance. /// /// Example App.config with credentials set. /// <code> /// &lt;?xml version="1.0" encoding="utf-8" ?&gt; /// &lt;configuration&gt; /// &lt;appSettings&gt; /// &lt;add key="AWSProfileName" value="AWS Default"/&gt; /// &lt;/appSettings&gt; /// &lt;/configuration&gt; /// </code> /// /// </summary> /// <param name="region">The region to connect.</param> public AmazonBatchClient(RegionEndpoint region) : base(FallbackCredentialsFactory.GetCredentials(), new AmazonBatchConfig{RegionEndpoint = region}) { } /// <summary> /// Constructs AmazonBatchClient with the credentials loaded from the application's /// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance. /// /// Example App.config with credentials set. /// <code> /// &lt;?xml version="1.0" encoding="utf-8" ?&gt; /// &lt;configuration&gt; /// &lt;appSettings&gt; /// &lt;add key="AWSProfileName" value="AWS Default"/&gt; /// &lt;/appSettings&gt; /// &lt;/configuration&gt; /// </code> /// /// </summary> /// <param name="config">The AmazonBatchClient Configuration Object</param> public AmazonBatchClient(AmazonBatchConfig config) : base(FallbackCredentialsFactory.GetCredentials(), config) { } /// <summary> /// Constructs AmazonBatchClient with AWS Credentials /// </summary> /// <param name="credentials">AWS Credentials</param> public AmazonBatchClient(AWSCredentials credentials) : this(credentials, new AmazonBatchConfig()) { } /// <summary> /// Constructs AmazonBatchClient with AWS Credentials /// </summary> /// <param name="credentials">AWS Credentials</param> /// <param name="region">The region to connect.</param> public AmazonBatchClient(AWSCredentials credentials, RegionEndpoint region) : this(credentials, new AmazonBatchConfig{RegionEndpoint = region}) { } /// <summary> /// Constructs AmazonBatchClient with AWS Credentials and an /// AmazonBatchClient Configuration object. /// </summary> /// <param name="credentials">AWS Credentials</param> /// <param name="clientConfig">The AmazonBatchClient Configuration Object</param> public AmazonBatchClient(AWSCredentials credentials, AmazonBatchConfig clientConfig) : base(credentials, clientConfig) { } /// <summary> /// Constructs AmazonBatchClient with AWS Access Key ID and AWS Secret Key /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> public AmazonBatchClient(string awsAccessKeyId, string awsSecretAccessKey) : this(awsAccessKeyId, awsSecretAccessKey, new AmazonBatchConfig()) { } /// <summary> /// Constructs AmazonBatchClient with AWS Access Key ID and AWS Secret Key /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="region">The region to connect.</param> public AmazonBatchClient(string awsAccessKeyId, string awsSecretAccessKey, RegionEndpoint region) : this(awsAccessKeyId, awsSecretAccessKey, new AmazonBatchConfig() {RegionEndpoint=region}) { } /// <summary> /// Constructs AmazonBatchClient with AWS Access Key ID, AWS Secret Key and an /// AmazonBatchClient Configuration object. /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="clientConfig">The AmazonBatchClient Configuration Object</param> public AmazonBatchClient(string awsAccessKeyId, string awsSecretAccessKey, AmazonBatchConfig clientConfig) : base(awsAccessKeyId, awsSecretAccessKey, clientConfig) { } /// <summary> /// Constructs AmazonBatchClient with AWS Access Key ID and AWS Secret Key /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="awsSessionToken">AWS Session Token</param> public AmazonBatchClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken) : this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonBatchConfig()) { } /// <summary> /// Constructs AmazonBatchClient with AWS Access Key ID and AWS Secret Key /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="awsSessionToken">AWS Session Token</param> /// <param name="region">The region to connect.</param> public AmazonBatchClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, RegionEndpoint region) : this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonBatchConfig{RegionEndpoint = region}) { } /// <summary> /// Constructs AmazonBatchClient with AWS Access Key ID, AWS Secret Key and an /// AmazonBatchClient Configuration object. /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="awsSessionToken">AWS Session Token</param> /// <param name="clientConfig">The AmazonBatchClient Configuration Object</param> public AmazonBatchClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, AmazonBatchConfig clientConfig) : base(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, clientConfig) { } #endregion #region Overrides /// <summary> /// Creates the signer for the service. /// </summary> protected override AbstractAWSSigner CreateSigner() { return new AWS4Signer(); } /// <summary> /// Capture metadata for the service. /// </summary> protected override IServiceMetadata ServiceMetadata { get { return serviceMetadata; } } #endregion #region Dispose /// <summary> /// Disposes the service client. /// </summary> protected override void Dispose(bool disposing) { base.Dispose(disposing); } #endregion #region CancelJob /// <summary> /// Cancels a job in an AWS Batch job queue. Jobs that are in the <code>SUBMITTED</code>, /// <code>PENDING</code>, or <code>RUNNABLE</code> state are cancelled. Jobs that have /// progressed to <code>STARTING</code> or <code>RUNNING</code> are not cancelled (but /// the API operation still succeeds, even if no job is cancelled); these jobs must be /// terminated with the <a>TerminateJob</a> operation. /// </summary> /// <param name="request">Container for the necessary parameters to execute the CancelJob service method.</param> /// /// <returns>The response from the CancelJob service method, as returned by Batch.</returns> /// <exception cref="Amazon.Batch.Model.ClientException"> /// These errors are usually caused by a client action, such as using an action or resource /// on behalf of a user that doesn't have permissions to use the action or resource, or /// specifying an identifier that is not valid. /// </exception> /// <exception cref="Amazon.Batch.Model.ServerException"> /// These errors are usually caused by a server issue. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/batch-2016-08-10/CancelJob">REST API Reference for CancelJob Operation</seealso> public virtual CancelJobResponse CancelJob(CancelJobRequest request) { var marshaller = CancelJobRequestMarshaller.Instance; var unmarshaller = CancelJobResponseUnmarshaller.Instance; return Invoke<CancelJobRequest,CancelJobResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the CancelJob operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CancelJob operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/batch-2016-08-10/CancelJob">REST API Reference for CancelJob Operation</seealso> public virtual Task<CancelJobResponse> CancelJobAsync(CancelJobRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = CancelJobRequestMarshaller.Instance; var unmarshaller = CancelJobResponseUnmarshaller.Instance; return InvokeAsync<CancelJobRequest,CancelJobResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region CreateComputeEnvironment /// <summary> /// Creates an AWS Batch compute environment. You can create <code>MANAGED</code> or <code>UNMANAGED</code> /// compute environments. /// /// /// <para> /// In a managed compute environment, AWS Batch manages the capacity and instance types /// of the compute resources within the environment. This is based on the compute resource /// specification that you define or the <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-launch-templates.html">launch /// template</a> that you specify when you create the compute environment. You can choose /// to use Amazon EC2 On-Demand Instances or Spot Instances in your managed compute environment. /// You can optionally set a maximum price so that Spot Instances only launch when the /// Spot Instance price is below a specified percentage of the On-Demand price. /// </para> /// <note> /// <para> /// Multi-node parallel jobs are not supported on Spot Instances. /// </para> /// </note> /// <para> /// In an unmanaged compute environment, you can manage your own compute resources. This /// provides more compute resource configuration options, such as using a custom AMI, /// but you must ensure that your AMI meets the Amazon ECS container instance AMI specification. /// For more information, see <a href="http://docs.aws.amazon.com/AmazonECS/latest/developerguide/container_instance_AMIs.html">Container /// Instance AMIs</a> in the <i>Amazon Elastic Container Service Developer Guide</i>. /// After you have created your unmanaged compute environment, you can use the <a>DescribeComputeEnvironments</a> /// operation to find the Amazon ECS cluster that is associated with it. Then, manually /// launch your container instances into that Amazon ECS cluster. For more information, /// see <a href="http://docs.aws.amazon.com/AmazonECS/latest/developerguide/launch_container_instance.html">Launching /// an Amazon ECS Container Instance</a> in the <i>Amazon Elastic Container Service Developer /// Guide</i>. /// </para> /// <note> /// <para> /// AWS Batch does not upgrade the AMIs in a compute environment after it is created (for /// example, when a newer version of the Amazon ECS-optimized AMI is available). You are /// responsible for the management of the guest operating system (including updates and /// security patches) and any additional application software or utilities that you install /// on the compute resources. To use a new AMI for your AWS Batch jobs: /// </para> /// <ol> <li> /// <para> /// Create a new compute environment with the new AMI. /// </para> /// </li> <li> /// <para> /// Add the compute environment to an existing job queue. /// </para> /// </li> <li> /// <para> /// Remove the old compute environment from your job queue. /// </para> /// </li> <li> /// <para> /// Delete the old compute environment. /// </para> /// </li> </ol> </note> /// </summary> /// <param name="request">Container for the necessary parameters to execute the CreateComputeEnvironment service method.</param> /// /// <returns>The response from the CreateComputeEnvironment service method, as returned by Batch.</returns> /// <exception cref="Amazon.Batch.Model.ClientException"> /// These errors are usually caused by a client action, such as using an action or resource /// on behalf of a user that doesn't have permissions to use the action or resource, or /// specifying an identifier that is not valid. /// </exception> /// <exception cref="Amazon.Batch.Model.ServerException"> /// These errors are usually caused by a server issue. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/batch-2016-08-10/CreateComputeEnvironment">REST API Reference for CreateComputeEnvironment Operation</seealso> public virtual CreateComputeEnvironmentResponse CreateComputeEnvironment(CreateComputeEnvironmentRequest request) { var marshaller = CreateComputeEnvironmentRequestMarshaller.Instance; var unmarshaller = CreateComputeEnvironmentResponseUnmarshaller.Instance; return Invoke<CreateComputeEnvironmentRequest,CreateComputeEnvironmentResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the CreateComputeEnvironment operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CreateComputeEnvironment operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/batch-2016-08-10/CreateComputeEnvironment">REST API Reference for CreateComputeEnvironment Operation</seealso> public virtual Task<CreateComputeEnvironmentResponse> CreateComputeEnvironmentAsync(CreateComputeEnvironmentRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = CreateComputeEnvironmentRequestMarshaller.Instance; var unmarshaller = CreateComputeEnvironmentResponseUnmarshaller.Instance; return InvokeAsync<CreateComputeEnvironmentRequest,CreateComputeEnvironmentResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region CreateJobQueue /// <summary> /// Creates an AWS Batch job queue. When you create a job queue, you associate one or /// more compute environments to the queue and assign an order of preference for the compute /// environments. /// /// /// <para> /// You also set a priority to the job queue that determines the order in which the AWS /// Batch scheduler places jobs onto its associated compute environments. For example, /// if a compute environment is associated with more than one job queue, the job queue /// with a higher priority is given preference for scheduling jobs to that compute environment. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the CreateJobQueue service method.</param> /// /// <returns>The response from the CreateJobQueue service method, as returned by Batch.</returns> /// <exception cref="Amazon.Batch.Model.ClientException"> /// These errors are usually caused by a client action, such as using an action or resource /// on behalf of a user that doesn't have permissions to use the action or resource, or /// specifying an identifier that is not valid. /// </exception> /// <exception cref="Amazon.Batch.Model.ServerException"> /// These errors are usually caused by a server issue. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/batch-2016-08-10/CreateJobQueue">REST API Reference for CreateJobQueue Operation</seealso> public virtual CreateJobQueueResponse CreateJobQueue(CreateJobQueueRequest request) { var marshaller = CreateJobQueueRequestMarshaller.Instance; var unmarshaller = CreateJobQueueResponseUnmarshaller.Instance; return Invoke<CreateJobQueueRequest,CreateJobQueueResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the CreateJobQueue operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CreateJobQueue operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/batch-2016-08-10/CreateJobQueue">REST API Reference for CreateJobQueue Operation</seealso> public virtual Task<CreateJobQueueResponse> CreateJobQueueAsync(CreateJobQueueRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = CreateJobQueueRequestMarshaller.Instance; var unmarshaller = CreateJobQueueResponseUnmarshaller.Instance; return InvokeAsync<CreateJobQueueRequest,CreateJobQueueResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DeleteComputeEnvironment /// <summary> /// Deletes an AWS Batch compute environment. /// /// /// <para> /// Before you can delete a compute environment, you must set its state to <code>DISABLED</code> /// with the <a>UpdateComputeEnvironment</a> API operation and disassociate it from any /// job queues with the <a>UpdateJobQueue</a> API operation. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the DeleteComputeEnvironment service method.</param> /// /// <returns>The response from the DeleteComputeEnvironment service method, as returned by Batch.</returns> /// <exception cref="Amazon.Batch.Model.ClientException"> /// These errors are usually caused by a client action, such as using an action or resource /// on behalf of a user that doesn't have permissions to use the action or resource, or /// specifying an identifier that is not valid. /// </exception> /// <exception cref="Amazon.Batch.Model.ServerException"> /// These errors are usually caused by a server issue. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/batch-2016-08-10/DeleteComputeEnvironment">REST API Reference for DeleteComputeEnvironment Operation</seealso> public virtual DeleteComputeEnvironmentResponse DeleteComputeEnvironment(DeleteComputeEnvironmentRequest request) { var marshaller = DeleteComputeEnvironmentRequestMarshaller.Instance; var unmarshaller = DeleteComputeEnvironmentResponseUnmarshaller.Instance; return Invoke<DeleteComputeEnvironmentRequest,DeleteComputeEnvironmentResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DeleteComputeEnvironment operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeleteComputeEnvironment operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/batch-2016-08-10/DeleteComputeEnvironment">REST API Reference for DeleteComputeEnvironment Operation</seealso> public virtual Task<DeleteComputeEnvironmentResponse> DeleteComputeEnvironmentAsync(DeleteComputeEnvironmentRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = DeleteComputeEnvironmentRequestMarshaller.Instance; var unmarshaller = DeleteComputeEnvironmentResponseUnmarshaller.Instance; return InvokeAsync<DeleteComputeEnvironmentRequest,DeleteComputeEnvironmentResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DeleteJobQueue /// <summary> /// Deletes the specified job queue. You must first disable submissions for a queue with /// the <a>UpdateJobQueue</a> operation. All jobs in the queue are terminated when you /// delete a job queue. /// /// /// <para> /// It is not necessary to disassociate compute environments from a queue before submitting /// a <code>DeleteJobQueue</code> request. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the DeleteJobQueue service method.</param> /// /// <returns>The response from the DeleteJobQueue service method, as returned by Batch.</returns> /// <exception cref="Amazon.Batch.Model.ClientException"> /// These errors are usually caused by a client action, such as using an action or resource /// on behalf of a user that doesn't have permissions to use the action or resource, or /// specifying an identifier that is not valid. /// </exception> /// <exception cref="Amazon.Batch.Model.ServerException"> /// These errors are usually caused by a server issue. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/batch-2016-08-10/DeleteJobQueue">REST API Reference for DeleteJobQueue Operation</seealso> public virtual DeleteJobQueueResponse DeleteJobQueue(DeleteJobQueueRequest request) { var marshaller = DeleteJobQueueRequestMarshaller.Instance; var unmarshaller = DeleteJobQueueResponseUnmarshaller.Instance; return Invoke<DeleteJobQueueRequest,DeleteJobQueueResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DeleteJobQueue operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeleteJobQueue operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/batch-2016-08-10/DeleteJobQueue">REST API Reference for DeleteJobQueue Operation</seealso> public virtual Task<DeleteJobQueueResponse> DeleteJobQueueAsync(DeleteJobQueueRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = DeleteJobQueueRequestMarshaller.Instance; var unmarshaller = DeleteJobQueueResponseUnmarshaller.Instance; return InvokeAsync<DeleteJobQueueRequest,DeleteJobQueueResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DeregisterJobDefinition /// <summary> /// Deregisters an AWS Batch job definition. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DeregisterJobDefinition service method.</param> /// /// <returns>The response from the DeregisterJobDefinition service method, as returned by Batch.</returns> /// <exception cref="Amazon.Batch.Model.ClientException"> /// These errors are usually caused by a client action, such as using an action or resource /// on behalf of a user that doesn't have permissions to use the action or resource, or /// specifying an identifier that is not valid. /// </exception> /// <exception cref="Amazon.Batch.Model.ServerException"> /// These errors are usually caused by a server issue. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/batch-2016-08-10/DeregisterJobDefinition">REST API Reference for DeregisterJobDefinition Operation</seealso> public virtual DeregisterJobDefinitionResponse DeregisterJobDefinition(DeregisterJobDefinitionRequest request) { var marshaller = DeregisterJobDefinitionRequestMarshaller.Instance; var unmarshaller = DeregisterJobDefinitionResponseUnmarshaller.Instance; return Invoke<DeregisterJobDefinitionRequest,DeregisterJobDefinitionResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DeregisterJobDefinition operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeregisterJobDefinition operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/batch-2016-08-10/DeregisterJobDefinition">REST API Reference for DeregisterJobDefinition Operation</seealso> public virtual Task<DeregisterJobDefinitionResponse> DeregisterJobDefinitionAsync(DeregisterJobDefinitionRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = DeregisterJobDefinitionRequestMarshaller.Instance; var unmarshaller = DeregisterJobDefinitionResponseUnmarshaller.Instance; return InvokeAsync<DeregisterJobDefinitionRequest,DeregisterJobDefinitionResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DescribeComputeEnvironments /// <summary> /// Describes one or more of your compute environments. /// /// /// <para> /// If you are using an unmanaged compute environment, you can use the <code>DescribeComputeEnvironment</code> /// operation to determine the <code>ecsClusterArn</code> that you should launch your /// Amazon ECS container instances into. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeComputeEnvironments service method.</param> /// /// <returns>The response from the DescribeComputeEnvironments service method, as returned by Batch.</returns> /// <exception cref="Amazon.Batch.Model.ClientException"> /// These errors are usually caused by a client action, such as using an action or resource /// on behalf of a user that doesn't have permissions to use the action or resource, or /// specifying an identifier that is not valid. /// </exception> /// <exception cref="Amazon.Batch.Model.ServerException"> /// These errors are usually caused by a server issue. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/batch-2016-08-10/DescribeComputeEnvironments">REST API Reference for DescribeComputeEnvironments Operation</seealso> public virtual DescribeComputeEnvironmentsResponse DescribeComputeEnvironments(DescribeComputeEnvironmentsRequest request) { var marshaller = DescribeComputeEnvironmentsRequestMarshaller.Instance; var unmarshaller = DescribeComputeEnvironmentsResponseUnmarshaller.Instance; return Invoke<DescribeComputeEnvironmentsRequest,DescribeComputeEnvironmentsResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DescribeComputeEnvironments operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeComputeEnvironments operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/batch-2016-08-10/DescribeComputeEnvironments">REST API Reference for DescribeComputeEnvironments Operation</seealso> public virtual Task<DescribeComputeEnvironmentsResponse> DescribeComputeEnvironmentsAsync(DescribeComputeEnvironmentsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = DescribeComputeEnvironmentsRequestMarshaller.Instance; var unmarshaller = DescribeComputeEnvironmentsResponseUnmarshaller.Instance; return InvokeAsync<DescribeComputeEnvironmentsRequest,DescribeComputeEnvironmentsResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DescribeJobDefinitions /// <summary> /// Describes a list of job definitions. You can specify a <code>status</code> (such as /// <code>ACTIVE</code>) to only return job definitions that match that status. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeJobDefinitions service method.</param> /// /// <returns>The response from the DescribeJobDefinitions service method, as returned by Batch.</returns> /// <exception cref="Amazon.Batch.Model.ClientException"> /// These errors are usually caused by a client action, such as using an action or resource /// on behalf of a user that doesn't have permissions to use the action or resource, or /// specifying an identifier that is not valid. /// </exception> /// <exception cref="Amazon.Batch.Model.ServerException"> /// These errors are usually caused by a server issue. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/batch-2016-08-10/DescribeJobDefinitions">REST API Reference for DescribeJobDefinitions Operation</seealso> public virtual DescribeJobDefinitionsResponse DescribeJobDefinitions(DescribeJobDefinitionsRequest request) { var marshaller = DescribeJobDefinitionsRequestMarshaller.Instance; var unmarshaller = DescribeJobDefinitionsResponseUnmarshaller.Instance; return Invoke<DescribeJobDefinitionsRequest,DescribeJobDefinitionsResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DescribeJobDefinitions operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeJobDefinitions operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/batch-2016-08-10/DescribeJobDefinitions">REST API Reference for DescribeJobDefinitions Operation</seealso> public virtual Task<DescribeJobDefinitionsResponse> DescribeJobDefinitionsAsync(DescribeJobDefinitionsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = DescribeJobDefinitionsRequestMarshaller.Instance; var unmarshaller = DescribeJobDefinitionsResponseUnmarshaller.Instance; return InvokeAsync<DescribeJobDefinitionsRequest,DescribeJobDefinitionsResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DescribeJobQueues /// <summary> /// Describes one or more of your job queues. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeJobQueues service method.</param> /// /// <returns>The response from the DescribeJobQueues service method, as returned by Batch.</returns> /// <exception cref="Amazon.Batch.Model.ClientException"> /// These errors are usually caused by a client action, such as using an action or resource /// on behalf of a user that doesn't have permissions to use the action or resource, or /// specifying an identifier that is not valid. /// </exception> /// <exception cref="Amazon.Batch.Model.ServerException"> /// These errors are usually caused by a server issue. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/batch-2016-08-10/DescribeJobQueues">REST API Reference for DescribeJobQueues Operation</seealso> public virtual DescribeJobQueuesResponse DescribeJobQueues(DescribeJobQueuesRequest request) { var marshaller = DescribeJobQueuesRequestMarshaller.Instance; var unmarshaller = DescribeJobQueuesResponseUnmarshaller.Instance; return Invoke<DescribeJobQueuesRequest,DescribeJobQueuesResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DescribeJobQueues operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeJobQueues operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/batch-2016-08-10/DescribeJobQueues">REST API Reference for DescribeJobQueues Operation</seealso> public virtual Task<DescribeJobQueuesResponse> DescribeJobQueuesAsync(DescribeJobQueuesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = DescribeJobQueuesRequestMarshaller.Instance; var unmarshaller = DescribeJobQueuesResponseUnmarshaller.Instance; return InvokeAsync<DescribeJobQueuesRequest,DescribeJobQueuesResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DescribeJobs /// <summary> /// Describes a list of AWS Batch jobs. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeJobs service method.</param> /// /// <returns>The response from the DescribeJobs service method, as returned by Batch.</returns> /// <exception cref="Amazon.Batch.Model.ClientException"> /// These errors are usually caused by a client action, such as using an action or resource /// on behalf of a user that doesn't have permissions to use the action or resource, or /// specifying an identifier that is not valid. /// </exception> /// <exception cref="Amazon.Batch.Model.ServerException"> /// These errors are usually caused by a server issue. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/batch-2016-08-10/DescribeJobs">REST API Reference for DescribeJobs Operation</seealso> public virtual DescribeJobsResponse DescribeJobs(DescribeJobsRequest request) { var marshaller = DescribeJobsRequestMarshaller.Instance; var unmarshaller = DescribeJobsResponseUnmarshaller.Instance; return Invoke<DescribeJobsRequest,DescribeJobsResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DescribeJobs operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeJobs operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/batch-2016-08-10/DescribeJobs">REST API Reference for DescribeJobs Operation</seealso> public virtual Task<DescribeJobsResponse> DescribeJobsAsync(DescribeJobsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = DescribeJobsRequestMarshaller.Instance; var unmarshaller = DescribeJobsResponseUnmarshaller.Instance; return InvokeAsync<DescribeJobsRequest,DescribeJobsResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region ListJobs /// <summary> /// Returns a list of AWS Batch jobs. /// /// /// <para> /// You must specify only one of the following: /// </para> /// <ul> <li> /// <para> /// a job queue ID to return a list of jobs in that job queue /// </para> /// </li> <li> /// <para> /// a multi-node parallel job ID to return a list of that job's nodes /// </para> /// </li> <li> /// <para> /// an array job ID to return a list of that job's children /// </para> /// </li> </ul> /// <para> /// You can filter the results by job status with the <code>jobStatus</code> parameter. /// If you do not specify a status, only <code>RUNNING</code> jobs are returned. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the ListJobs service method.</param> /// /// <returns>The response from the ListJobs service method, as returned by Batch.</returns> /// <exception cref="Amazon.Batch.Model.ClientException"> /// These errors are usually caused by a client action, such as using an action or resource /// on behalf of a user that doesn't have permissions to use the action or resource, or /// specifying an identifier that is not valid. /// </exception> /// <exception cref="Amazon.Batch.Model.ServerException"> /// These errors are usually caused by a server issue. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/batch-2016-08-10/ListJobs">REST API Reference for ListJobs Operation</seealso> public virtual ListJobsResponse ListJobs(ListJobsRequest request) { var marshaller = ListJobsRequestMarshaller.Instance; var unmarshaller = ListJobsResponseUnmarshaller.Instance; return Invoke<ListJobsRequest,ListJobsResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the ListJobs operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ListJobs operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/batch-2016-08-10/ListJobs">REST API Reference for ListJobs Operation</seealso> public virtual Task<ListJobsResponse> ListJobsAsync(ListJobsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = ListJobsRequestMarshaller.Instance; var unmarshaller = ListJobsResponseUnmarshaller.Instance; return InvokeAsync<ListJobsRequest,ListJobsResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region RegisterJobDefinition /// <summary> /// Registers an AWS Batch job definition. /// </summary> /// <param name="request">Container for the necessary parameters to execute the RegisterJobDefinition service method.</param> /// /// <returns>The response from the RegisterJobDefinition service method, as returned by Batch.</returns> /// <exception cref="Amazon.Batch.Model.ClientException"> /// These errors are usually caused by a client action, such as using an action or resource /// on behalf of a user that doesn't have permissions to use the action or resource, or /// specifying an identifier that is not valid. /// </exception> /// <exception cref="Amazon.Batch.Model.ServerException"> /// These errors are usually caused by a server issue. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/batch-2016-08-10/RegisterJobDefinition">REST API Reference for RegisterJobDefinition Operation</seealso> public virtual RegisterJobDefinitionResponse RegisterJobDefinition(RegisterJobDefinitionRequest request) { var marshaller = RegisterJobDefinitionRequestMarshaller.Instance; var unmarshaller = RegisterJobDefinitionResponseUnmarshaller.Instance; return Invoke<RegisterJobDefinitionRequest,RegisterJobDefinitionResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the RegisterJobDefinition operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the RegisterJobDefinition operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/batch-2016-08-10/RegisterJobDefinition">REST API Reference for RegisterJobDefinition Operation</seealso> public virtual Task<RegisterJobDefinitionResponse> RegisterJobDefinitionAsync(RegisterJobDefinitionRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = RegisterJobDefinitionRequestMarshaller.Instance; var unmarshaller = RegisterJobDefinitionResponseUnmarshaller.Instance; return InvokeAsync<RegisterJobDefinitionRequest,RegisterJobDefinitionResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region SubmitJob /// <summary> /// Submits an AWS Batch job from a job definition. Parameters specified during <a>SubmitJob</a> /// override parameters defined in the job definition. /// </summary> /// <param name="request">Container for the necessary parameters to execute the SubmitJob service method.</param> /// /// <returns>The response from the SubmitJob service method, as returned by Batch.</returns> /// <exception cref="Amazon.Batch.Model.ClientException"> /// These errors are usually caused by a client action, such as using an action or resource /// on behalf of a user that doesn't have permissions to use the action or resource, or /// specifying an identifier that is not valid. /// </exception> /// <exception cref="Amazon.Batch.Model.ServerException"> /// These errors are usually caused by a server issue. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/batch-2016-08-10/SubmitJob">REST API Reference for SubmitJob Operation</seealso> public virtual SubmitJobResponse SubmitJob(SubmitJobRequest request) { var marshaller = SubmitJobRequestMarshaller.Instance; var unmarshaller = SubmitJobResponseUnmarshaller.Instance; return Invoke<SubmitJobRequest,SubmitJobResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the SubmitJob operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the SubmitJob operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/batch-2016-08-10/SubmitJob">REST API Reference for SubmitJob Operation</seealso> public virtual Task<SubmitJobResponse> SubmitJobAsync(SubmitJobRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = SubmitJobRequestMarshaller.Instance; var unmarshaller = SubmitJobResponseUnmarshaller.Instance; return InvokeAsync<SubmitJobRequest,SubmitJobResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region TerminateJob /// <summary> /// Terminates a job in a job queue. Jobs that are in the <code>STARTING</code> or <code>RUNNING</code> /// state are terminated, which causes them to transition to <code>FAILED</code>. Jobs /// that have not progressed to the <code>STARTING</code> state are cancelled. /// </summary> /// <param name="request">Container for the necessary parameters to execute the TerminateJob service method.</param> /// /// <returns>The response from the TerminateJob service method, as returned by Batch.</returns> /// <exception cref="Amazon.Batch.Model.ClientException"> /// These errors are usually caused by a client action, such as using an action or resource /// on behalf of a user that doesn't have permissions to use the action or resource, or /// specifying an identifier that is not valid. /// </exception> /// <exception cref="Amazon.Batch.Model.ServerException"> /// These errors are usually caused by a server issue. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/batch-2016-08-10/TerminateJob">REST API Reference for TerminateJob Operation</seealso> public virtual TerminateJobResponse TerminateJob(TerminateJobRequest request) { var marshaller = TerminateJobRequestMarshaller.Instance; var unmarshaller = TerminateJobResponseUnmarshaller.Instance; return Invoke<TerminateJobRequest,TerminateJobResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the TerminateJob operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the TerminateJob operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/batch-2016-08-10/TerminateJob">REST API Reference for TerminateJob Operation</seealso> public virtual Task<TerminateJobResponse> TerminateJobAsync(TerminateJobRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = TerminateJobRequestMarshaller.Instance; var unmarshaller = TerminateJobResponseUnmarshaller.Instance; return InvokeAsync<TerminateJobRequest,TerminateJobResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region UpdateComputeEnvironment /// <summary> /// Updates an AWS Batch compute environment. /// </summary> /// <param name="request">Container for the necessary parameters to execute the UpdateComputeEnvironment service method.</param> /// /// <returns>The response from the UpdateComputeEnvironment service method, as returned by Batch.</returns> /// <exception cref="Amazon.Batch.Model.ClientException"> /// These errors are usually caused by a client action, such as using an action or resource /// on behalf of a user that doesn't have permissions to use the action or resource, or /// specifying an identifier that is not valid. /// </exception> /// <exception cref="Amazon.Batch.Model.ServerException"> /// These errors are usually caused by a server issue. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/batch-2016-08-10/UpdateComputeEnvironment">REST API Reference for UpdateComputeEnvironment Operation</seealso> public virtual UpdateComputeEnvironmentResponse UpdateComputeEnvironment(UpdateComputeEnvironmentRequest request) { var marshaller = UpdateComputeEnvironmentRequestMarshaller.Instance; var unmarshaller = UpdateComputeEnvironmentResponseUnmarshaller.Instance; return Invoke<UpdateComputeEnvironmentRequest,UpdateComputeEnvironmentResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the UpdateComputeEnvironment operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the UpdateComputeEnvironment operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/batch-2016-08-10/UpdateComputeEnvironment">REST API Reference for UpdateComputeEnvironment Operation</seealso> public virtual Task<UpdateComputeEnvironmentResponse> UpdateComputeEnvironmentAsync(UpdateComputeEnvironmentRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = UpdateComputeEnvironmentRequestMarshaller.Instance; var unmarshaller = UpdateComputeEnvironmentResponseUnmarshaller.Instance; return InvokeAsync<UpdateComputeEnvironmentRequest,UpdateComputeEnvironmentResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region UpdateJobQueue /// <summary> /// Updates a job queue. /// </summary> /// <param name="request">Container for the necessary parameters to execute the UpdateJobQueue service method.</param> /// /// <returns>The response from the UpdateJobQueue service method, as returned by Batch.</returns> /// <exception cref="Amazon.Batch.Model.ClientException"> /// These errors are usually caused by a client action, such as using an action or resource /// on behalf of a user that doesn't have permissions to use the action or resource, or /// specifying an identifier that is not valid. /// </exception> /// <exception cref="Amazon.Batch.Model.ServerException"> /// These errors are usually caused by a server issue. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/batch-2016-08-10/UpdateJobQueue">REST API Reference for UpdateJobQueue Operation</seealso> public virtual UpdateJobQueueResponse UpdateJobQueue(UpdateJobQueueRequest request) { var marshaller = UpdateJobQueueRequestMarshaller.Instance; var unmarshaller = UpdateJobQueueResponseUnmarshaller.Instance; return Invoke<UpdateJobQueueRequest,UpdateJobQueueResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the UpdateJobQueue operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the UpdateJobQueue operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/batch-2016-08-10/UpdateJobQueue">REST API Reference for UpdateJobQueue Operation</seealso> public virtual Task<UpdateJobQueueResponse> UpdateJobQueueAsync(UpdateJobQueueRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = UpdateJobQueueRequestMarshaller.Instance; var unmarshaller = UpdateJobQueueResponseUnmarshaller.Instance; return InvokeAsync<UpdateJobQueueRequest,UpdateJobQueueResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion } }
53.656915
224
0.671772
[ "Apache-2.0" ]
DalavanCloud/aws-sdk-net
sdk/src/Services/Batch/Generated/_bcl45/AmazonBatchClient.cs
60,525
C#
/** * The MIT License * Copyright (c) 2016 Population Register Centre (VRK) * * 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 PTV.Database.DataAccess.ApplicationDbContext; using PTV.Database.DataAccess.Interfaces; using PTV.Database.Model.Models; using PTV.Framework; using PTV.Framework.Interfaces; namespace PTV.Database.DataAccess.EntityCloners { [RegisterService(typeof(IEntityCloner<ServiceLaw>), RegisterType.Transient)] internal class ServiceLawCloner : EntityCloner<ServiceLaw> { public ServiceLawCloner(IResolveManager resolveManager, IEntityNavigationsMap entityNavigationsMap) : base(resolveManager, entityNavigationsMap) { } public override void CloningDefinition() { AddClone(i => i.Law); } } }
42.372093
152
0.751921
[ "MIT" ]
MikkoVirenius/ptv-1.7
src/PTV.Database.DataAccess/EntityCloners/ServiceLawCloner.cs
1,822
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using Microsoft.Speech.Recognition; // namespace usado pra o reconhecimento de voz, Microsoft Speech Server 11 SDK pt-BR namespace MOB { public partial class Form1 : Form { Random rnd = new Random(); private SpeechRecognitionEngine engine; // reconhecimento da voz public Form1() { InitializeComponent(); } private void LoadSpeech() { try { engine = new SpeechRecognitionEngine(); // instancia engine.SetInputToDefaultAudioDevice(); // entrada do audio Microfone string[] words = {"ola"}; // palavras Choices palavras = new Choices(); Grammar wordlist = new Grammar(new GrammarBuilder(palavras)); // carregar a gramatica engine.LoadGrammar(new Grammar(new GrammarBuilder(new Choices(words)))); engine.SpeechRecognized += new EventHandler<SpeechRecognizedEventArgs>(rec); engine.AudioLevelUpdated += new EventHandler<AudioLevelUpdatedEventArgs>(audioLevel); engine.RecognizeAsync(RecognizeMode.Multiple); // iniciar reconhecimento } catch (Exception ex) { MessageBox.Show("Ocorreu no LoadSpeech(): " + ex.Message); } } private void pictureBox1_Click(object sender, EventArgs e) { } public void rec(object s, SpeechRecognizedEventArgs e) { // resultado do audio // MessageBox.Show(e.Result.Text); string speech = e.Result.Text; // mostrar palavra reconhecida int Num = rnd.Next(1, 10); String QEvent; float conf = e.Result.Confidence; } private void audioLevel(object s, AudioLevelUpdatedEventArgs e) { this.progressBar1.Maximum = 100; this.progressBar1.Value = e.AudioLevel; } private void Form1_Load(object sender, EventArgs e) { Mob.Fala("Olá, eu sou o mób, e ainda estou em desenvolvimento"); Mob.Fala("Logo terei muitas novidades"); } } }
27.863636
120
0.588907
[ "MIT" ]
mobassistente/MOB
MOB/MOB/Form1.cs
2,456
C#
using System.Linq; using Xunit; namespace Tests { public class Array { [Fact] public void Test() { char[] characters = new char[5]; char[] characters1 = new char[] { 'a', 'b', 'c' }; char[] characters2 = { 'a', 'b', 'c' }; Assert.Equal('a',characters1[0]); Assert.Equal('b', characters1[1]); for (var i = 0; i < characters1.Length; i++) { Assert.Equal(characters1[i], characters2[i]); } } } }
23.458333
62
0.440497
[ "MIT" ]
orlicekm/CsharpCourse
Lectures/Lecture01/Assets/sln/Tests/Array.cs
563
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("AspNet.Mvc.RedirectAssist")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("AspNet.Mvc.RedirectAssist")] [assembly: AssemblyCopyright("Copyright © 2017")] [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("379a77c3-4dd8-404b-952d-3eb4aa4ae9a1")] // 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")]
38.324324
84
0.749647
[ "MIT" ]
bbishwokarma/AspNet.Mvc.ReturnUrl
AspNet.Mvc.RedirectAssist/Properties/AssemblyInfo.cs
1,421
C#
using System; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; using System.IO; using System.Xml.Linq; using AdamsLair.WinForms.ItemModels; using Duality; using Duality.IO; using Duality.Resources; using TextRenderer = Duality.Components.Renderers.TextRenderer; using Duality.Editor; using Duality.Editor.Forms; using Duality.Editor.Plugins.Base.Forms; using Duality.Editor.Properties; using Duality.Editor.UndoRedoActions; using Duality.Editor.Plugins.Base.Properties; using WeifenLuo.WinFormsUI.Docking; namespace Duality.Editor.Plugins.Base { public class EditorBasePlugin : EditorPlugin { private static readonly string ElementNamePixmapSlicer = "PixmapSlicer"; private PixmapSlicerForm slicingForm = null; private XElement pixmapSlicerSettings = null; private bool isLoading = false; public override string Id { get { return "EditorBase"; } } public PixmapSlicerForm RequestPixmapSlicerForm() { // Create a new slicing form, if none are available right now if (this.slicingForm == null || this.slicingForm.IsDisposed) { this.slicingForm = new PixmapSlicerForm(); this.slicingForm.FormClosed += this.slicingForm_FormClosed; // If there are cached settings available, apply them to the new editor if (this.pixmapSlicerSettings != null) this.slicingForm.LoadUserData(this.pixmapSlicerSettings); if (!this.isLoading) { this.slicingForm.DockPanel = DualityEditorApp.MainForm.MainDockPanel; } } // If we're not creating it as part of the loading procedure, // add it to the main docking layout directly if (!this.isLoading) { this.slicingForm.Show(DualityEditorApp.MainForm.MainDockPanel); } return this.slicingForm; } protected override void InitPlugin(MainForm main) { base.InitPlugin(main); // Request menus MenuModelItem settingsItem = main.MainMenu.RequestItem(GeneralRes.MenuName_Settings); settingsItem.SortValue = MenuModelItem.SortValue_OverBottom; settingsItem.AddItems(new[] { new MenuModelItem { Name = EditorBaseRes.MenuItemName_AppData, ActionHandler = this.menuItemAppData_Click }, new MenuModelItem { Name = EditorBaseRes.MenuItemName_UserData, ActionHandler = this.menuItemUserData_Click } }); DualityEditorApp.ObjectPropertyChanged += this.DualityEditorApp_ObjectPropertyChanged; } protected override void SaveUserData(XElement node) { if (this.slicingForm != null) { this.pixmapSlicerSettings = new XElement(ElementNamePixmapSlicer); this.slicingForm.SaveUserData(this.pixmapSlicerSettings); } if (this.slicingForm != null && !this.pixmapSlicerSettings.IsEmpty) node.Add(this.pixmapSlicerSettings); } protected override void LoadUserData(XElement node) { this.isLoading = true; foreach (XElement pixmapSlicerElem in node.Elements(ElementNamePixmapSlicer)) { int i = pixmapSlicerElem.GetAttributeValue("id", 0); if (i < 0 || i >= 1) continue; this.pixmapSlicerSettings = new XElement(pixmapSlicerElem); break; } if (this.slicingForm != null && this.pixmapSlicerSettings != null) this.slicingForm.LoadUserData(this.pixmapSlicerSettings); this.isLoading = false; } protected override IDockContent DeserializeDockContent(Type dockContentType) { this.isLoading = true; IDockContent result; if (dockContentType == typeof(PixmapSlicerForm)) result = this.RequestPixmapSlicerForm(); else result = base.DeserializeDockContent(dockContentType); this.isLoading = false; return result; } private void slicingForm_FormClosed(object sender, FormClosedEventArgs e) { this.pixmapSlicerSettings = new XElement(ElementNamePixmapSlicer); this.slicingForm.SaveUserData(this.pixmapSlicerSettings); this.slicingForm.FormClosed -= this.slicingForm_FormClosed; this.slicingForm.Dispose(); this.slicingForm = null; } private void menuItemAppData_Click(object sender, EventArgs e) { DualityEditorApp.Select(this, new ObjectSelection(new [] { DualityApp.AppData })); } private void menuItemUserData_Click(object sender, EventArgs e) { DualityEditorApp.Select(this, new ObjectSelection(new [] { DualityApp.UserData })); } private void DualityEditorApp_ObjectPropertyChanged(object sender, ObjectPropertyChangedEventArgs e) { if (e.Objects.ResourceCount > 0) { List<object> modifiedObjects = new List<object>(); foreach (Resource resource in e.Objects.Resources) { this.PropagateDependentResourceChanges(resource, modifiedObjects); } // Notify about propagated changes, but flag them as non-persistent if (modifiedObjects.Count > 0) { DualityEditorApp.NotifyObjPropChanged( this, new ObjectSelection(modifiedObjects), false); } } } private void PropagateDependentResourceChanges(ContentRef<Resource> resRef, List<object> modifiedObjects) { // If a font has been modified, reload it and update all TextRenderers if (resRef.Is<Font>()) { foreach (TextRenderer r in Scene.Current.AllObjects.GetComponents<TextRenderer>()) { if (r.Text.Fonts.Contains(resRef.As<Font>())) { r.Text.ApplySource(); modifiedObjects.Add(r); } } } // If its a Pixmap, reload all associated Textures else if (resRef.Is<Pixmap>()) { ContentRef<Pixmap> pixRef = resRef.As<Pixmap>(); foreach (ContentRef<Texture> tex in ContentProvider.GetLoadedContent<Texture>()) { if (!tex.IsAvailable) continue; if (tex.Res.BasePixmap == pixRef) { // Note: Reloading texture data every time _any_ change happens to a Pixmap // is super wasteful. Find a way to identify relevant changes, and only reload // when they happen. // An example of an unnecessary reload is changing the Pixmap atlas, where updating // the atlas only would be sufficient. tex.Res.ReloadData(); modifiedObjects.Add(tex.Res); } } } // If its a Texture, update all associated RenderTargets else if (resRef.Is<Texture>()) { if (resRef.IsLoaded) { Texture tex = resRef.As<Texture>().Res; if (tex.NeedsReload) tex.ReloadData(); } ContentRef<Texture> texRef = resRef.As<Texture>(); foreach (ContentRef<RenderTarget> rt in ContentProvider.GetLoadedContent<RenderTarget>()) { if (!rt.IsAvailable) continue; if (rt.Res.Targets.Contains(texRef)) { rt.Res.SetupTarget(); modifiedObjects.Add(rt.Res); } } } // If its some kind of shader, update all associated techniques else if (resRef.Is<Shader>()) { ContentRef<FragmentShader> fragRef = resRef.As<FragmentShader>(); ContentRef<VertexShader> vertRef = resRef.As<VertexShader>(); foreach (ContentRef<DrawTechnique> sp in ContentProvider.GetLoadedContent<DrawTechnique>()) { if (!sp.IsAvailable) continue; if (sp.Res.Fragment == fragRef || sp.Res.Vertex == vertRef) { if (sp.Res.Compiled) sp.Res.Compile(); modifiedObjects.Add(sp.Res); } } } } } }
29.953975
107
0.711971
[ "MIT" ]
Barsonax/duality
Source/Plugins/EditorBase/EditorBasePlugin.cs
7,161
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.Security.Cryptography; using Duende.IdentityServer.Configuration; using Duende.IdentityServer.Services; using Duende.IdentityServer.Stores; using Microsoft.AspNetCore.ApiAuthorization.IdentityServer.Configuration; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; using Microsoft.IdentityModel.Tokens; using Moq; namespace Microsoft.AspNetCore.ApiAuthorization.IdentityServer; public class IdentityServerJwtBearerOptionsConfigurationTest { [Fact] public void Configure_SetsUpBearerSchemeForTheLocalApi() { // Arrange var localApiDescriptor = new Mock<IIdentityServerJwtDescriptor>(); localApiDescriptor.Setup(lad => lad.GetResourceDefinitions()) .Returns(new Dictionary<string, ResourceDefinition> { ["TestAPI"] = new ResourceDefinition { Profile = ApplicationProfiles.IdentityServerJwt } }); var bearerConfiguration = new IdentityServerJwtBearerOptionsConfiguration( "authScheme", "TestAPI", localApiDescriptor.Object); var options = new JwtBearerOptions(); // Act bearerConfiguration.Configure("authScheme", options); // Assert Assert.Equal("name", options.TokenValidationParameters.NameClaimType); Assert.Equal("role", options.TokenValidationParameters.RoleClaimType); Assert.Equal("TestAPI", options.Audience); } [Fact] public async Task ResolveAuthorityAndKeysAsync_SetsUpAuthorityAndKeysOnTheTokenValidationParametersAsync() { // Arrange var localApiDescriptor = new Mock<IIdentityServerJwtDescriptor>(); localApiDescriptor.Setup(lad => lad.GetResourceDefinitions()) .Returns(new Dictionary<string, ResourceDefinition> { ["TestAPI"] = new ResourceDefinition { Profile = ApplicationProfiles.IdentityServerJwt } }); var credentialsStore = new Mock<ISigningCredentialStore>(); var key = new RsaSecurityKey(RSA.Create()); credentialsStore.Setup(cs => cs.GetSigningCredentialsAsync()) .ReturnsAsync(new SigningCredentials(key, "RS256")); var issuerName = new Mock<IIssuerNameService>(); issuerName.Setup(i => i.GetCurrentAsync()).ReturnsAsync("https://localhost"); var context = new DefaultHttpContext(); context.Request.Scheme = "https"; context.Request.Host = new HostString("localhost"); context.RequestServices = new ServiceCollection() .AddSingleton(new IdentityServerOptions()) .AddSingleton(credentialsStore.Object) .AddSingleton(issuerName.Object) .BuildServiceProvider(); var options = new JwtBearerOptions(); var args = new MessageReceivedContext(context, new AuthenticationScheme("TestAPI", null, Mock.Of<IAuthenticationHandler>().GetType()), options); // Act await IdentityServerJwtBearerOptionsConfiguration.ResolveAuthorityAndKeysAsync(args); // Assert Assert.Equal("https://localhost", options.TokenValidationParameters.ValidIssuer); Assert.Equal(key, options.TokenValidationParameters.IssuerSigningKey); } [Fact] public void Configure_IgnoresOptionsForDifferentSchemes() { // Arrange var localApiDescriptor = new Mock<IIdentityServerJwtDescriptor>(); localApiDescriptor.Setup(lad => lad.GetResourceDefinitions()) .Returns(new Dictionary<string, ResourceDefinition> { ["TestAPI"] = new ResourceDefinition { Profile = ApplicationProfiles.IdentityServerJwt } }); var bearerConfiguration = new IdentityServerJwtBearerOptionsConfiguration( "authScheme", "TestAPI", localApiDescriptor.Object); var options = new JwtBearerOptions(); // Act bearerConfiguration.Configure("otherScheme", options); // Assert Assert.NotEqual("name", options.TokenValidationParameters.NameClaimType); Assert.NotEqual("role", options.TokenValidationParameters.RoleClaimType); Assert.NotEqual("TestAPI", options.Audience); Assert.NotEqual("https://localhost", options.Authority); } [Fact] public void Configure_IgnoresOptionsForNonExistingAPIs() { // Arrange var contextAccessor = new Mock<IHttpContextAccessor>(); var context = new DefaultHttpContext(); context.Request.Scheme = "https"; context.Request.Host = new HostString("localhost"); context.RequestServices = new ServiceCollection() .AddSingleton(new IdentityServerOptions()) .BuildServiceProvider(); contextAccessor.SetupGet(ca => ca.HttpContext).Returns( context); var localApiDescriptor = new Mock<IIdentityServerJwtDescriptor>(); localApiDescriptor.Setup(lad => lad.GetResourceDefinitions()) .Returns(new Dictionary<string, ResourceDefinition> { ["TestAPI"] = new ResourceDefinition { Profile = ApplicationProfiles.IdentityServerJwt } }); var credentialsStore = new Mock<ISigningCredentialStore>(); var key = new RsaSecurityKey(RSA.Create()); credentialsStore.Setup(cs => cs.GetSigningCredentialsAsync()) .ReturnsAsync(new SigningCredentials(key, "RS256")); var bearerConfiguration = new IdentityServerJwtBearerOptionsConfiguration( "authScheme", "NonExistingApi", localApiDescriptor.Object); var options = new JwtBearerOptions(); // Act bearerConfiguration.Configure("authScheme", options); // Assert Assert.NotEqual("name", options.TokenValidationParameters.NameClaimType); Assert.NotEqual("role", options.TokenValidationParameters.RoleClaimType); Assert.NotEqual(key, options.TokenValidationParameters.IssuerSigningKey); Assert.NotEqual("TestAPI", options.Audience); Assert.NotEqual("https://localhost", options.Authority); } }
40.772152
152
0.678982
[ "MIT" ]
Akarachudra/kontur-aspnetcore-fork
src/Identity/ApiAuthorization.IdentityServer/test/Authentication/IdentityServerJwtBearerConfigurationTest.cs
6,442
C#
using System.Collections.Generic; using System; using System.Linq; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace AndroidExplorer { internal class RootNode : TreeNode { private static Regex _device_list_pattern; private DateTime _expred_date_time; static RootNode() { _device_list_pattern = new Regex(@"^(?<id>[^ ]+)\s+(?<status>device|offline)(\s+usb:(?<usb>[^ ]+))?(\s+product:(?<product>[^ ]+))?(\s+model:(?<model>[^ ]+))?(\s+device:(?<device>[^ ]+))?(\s+transport_id:(?<transport_id>[^ ]+))?$", RegexOptions.Compiled); } public RootNode(string display_name) : base(display_name) { _expred_date_time = DateTime.UtcNow; } async public override Task Update(bool forcely) { var now = DateTime.UtcNow; if (!forcely && now < _expred_date_time) return; var result_text = await ExternalCommand.Adb.Run(this, "devices -l"); if (result_text == null) return; _expred_date_time = now.AddSeconds(10); var new_devices = result_text .Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries) .Where(s => s != "List of devices attached") .Select(s => { var m = _device_list_pattern.Match(s); if (!m.Success) return null; else { return new { id = m.Groups["id"].Value, status = m.Groups["status"].Value, usb = m.Groups["usb"].Value, product = m.Groups["product"].Value, model = m.Groups["model"].Value, device = m.Groups["device"].Value, transport_id = m.Groups["transport_id"].Value, }; } }) .Where(item => item != null) .ToDictionary(item => item.id, item => item); var deleting_items = new List<DeviceNode>(); foreach (var child in Children) { var device = child as DeviceNode; if (device != null) { if (new_devices.ContainsKey(device.DeviceId)) { var new_device = new_devices[device.DeviceId]; device.Device = new_device.device; device.Model = new_device.model; device.Product = new_device.product; device.Status = new_device.status; device.Usb = new_device.usb; device.TransportId = new_device.transport_id; } else deleting_items.Add(device); } } foreach (var deleting_item in deleting_items) { deleting_item.Disconnect(); Children.Remove(deleting_item); } var current_devices = Children .Select(item => item as DeviceNode) .Where(item => item != null) .ToDictionary(item => item.DeviceId, item => item); foreach (var new_device in new_devices.Values) { if (!current_devices.ContainsKey(new_device.id)) Children.Add(new DeviceNode(new_device.id, new_device.status, new_device.usb, new_device.product, new_device.model, new_device.device, new_device.transport_id)); } foreach (var task in Children.Select(child => child.Update(false)).ToArray()) await task; } } }
39.71
266
0.47998
[ "MIT" ]
rougemeilland/androidexplorer
AndroidExplorer/RootNode.cs
3,973
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using TMPro; using System.Text; public class ComboText : MonoBehaviour { [SerializeField] AnimationClip animClip; TextMeshPro comboText; [HideInInspector] public Transform myTransform; [HideInInspector] public GameObject myGameObject; void Start() { myTransform = GetComponent<Transform>(); myGameObject = gameObject; comboText = GetComponent<TextMeshPro>(); myGameObject.SetActive(false); } public void Show_ComboText(Vector2 pos) { comboText.text = Managers.Game.combo.ToString() + " Combo"; myTransform.position = pos; StartCoroutine(Hide_ComboText()); } IEnumerator Hide_ComboText() { yield return Managers.Co.WaitSeconds(animClip.length); myGameObject.SetActive(false); } }
24.027027
67
0.685039
[ "MIT" ]
ansohxxn/tidy_mommy_3
Assets/Script/UI/Text/ComboText.cs
891
C#
using Prism.Mvvm; using System; using System.Collections.Generic; using System.Text; namespace JacksonVeroneze.Shopping.ViewModels { public class ViewModelState : BindableBase { private bool _hasNetworkAccess = false; public bool HasNetworkAccess { get => _hasNetworkAccess; set => SetProperty(ref _hasNetworkAccess, value); } private bool _isLoading = false; public bool IsLoading { get => _isLoading; set => SetProperty(ref _isLoading, value); } private bool _isBusy = false; public bool IsBusy { get => _isBusy; set => SetProperty(ref _isBusy, value); } private bool _isBusyNavigating = false; public bool IsBusyNavigating { get => _isBusyNavigating; set => SetProperty(ref _isBusyNavigating, value); } private bool _isRefresh = false; public bool IsRefresh { get => _isRefresh; set => SetProperty(ref _isRefresh, value); } private bool _isSearch = false; public bool IsSearch { get => _isSearch; set => SetProperty(ref _isSearch, value); } private bool _hasData = false; public bool HasData { get => _hasData; set => SetProperty(ref _hasData, value); } private bool _noData = false; public bool NoData { get => _noData; set => SetProperty(ref _noData, value); } private bool _hasError = false; public bool HasError { get => _hasError; set { SetProperty(ref _hasError, value); if (_hasError is true) { IsLoading = false; IsBusy = false; IsRefresh = false; IsSearch = false; HasData = false; NoData = false; } } } } }
25.758621
62
0.47568
[ "MIT" ]
dorisoy/Shopping
JacksonVeroneze.Shopping/JacksonVeroneze.Shopping/ViewModels/ViewModelState.cs
2,243
C#
using Protocol; using View.UI.Wins; namespace View.Net { public static class PResultUtils { public static string GetErrorMsg( PResult result ) { return result.ToString();//todo } public static void ShowAlter( PResult result ) { if ( result != PResult.SUCCESS ) Windows.ALERT_WIN.Open( GetErrorMsg( result ) ); } } }
18.052632
52
0.688047
[ "MIT" ]
niuniuzhu/Lockstep
Project/View/Net/PResultUtils.cs
345
C#
using System; using FarseerPhysics.Dynamics; using FarseerPhysics.Factories; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; namespace app.Desktop { public class Game1 : Game { private GraphicsDeviceManager graphics; private InputHelper inputHelper; private SpriteBatch spriteBatch; private SpriteFont font; private Body billBody; private Body platformBody; private enum BillState { ATTACKING, FIGHT_STANCE, IDLE, WALKING } private Texture2D platform; private Texture2D hillBackground; Rectangle rectangle1; Rectangle rectangle2; private Texture2D billIdle; private Texture2D billAttacking; private Texture2D billFight; private Texture2D billWalkingRightLeg; private Texture2D billWalkingLeftLeg; private BillState billState = BillState.IDLE; private Vector2 billOrigin; private Vector2 platformOrigin; private Vector2 billPosition; private Vector2 platformPosition; private Vector2 titlePosition; private Vector2 frameratePosition; private World world; // Simple camera controls private Matrix view; private Vector2 cameraPosition; private Vector2 screenCenter; private int currentFramerate; public Game1() { graphics = new GraphicsDeviceManager(this); graphics.PreferredBackBufferWidth = 1280; graphics.PreferredBackBufferHeight = 720; Content.RootDirectory = "Content"; world = new World (new Vector2 (0, 9.82f)); } /// <summary> /// Allows the game to perform any initialization it needs to before starting to run. /// This is where it can query for any required services and load any non-graphic /// related content. Calling base.Initialize will enumerate through any components /// and initialize them as well. /// </summary> protected override void Initialize() { base.Initialize(); inputHelper = new InputHelper(); billPosition = screenCenter; titlePosition = new Vector2(20, 5); frameratePosition = new Vector2(20, 25); rectangle1 = new Rectangle (0, 0, 1280, 720); rectangle2 = new Rectangle (1280, 0, 1280, 720); } /// <summary> /// LoadContent will be called once per game and is the place to load /// all of your content. /// </summary> protected override void LoadContent() { spriteBatch = new SpriteBatch(graphics.GraphicsDevice); font = Content.Load<SpriteFont>("Font"); billIdle = Content.Load<Texture2D>("shot/1"); billAttacking = Content.Load<Texture2D>("shot/2"); billFight = Content.Load<Texture2D>("shot/3"); billWalkingRightLeg = Content.Load<Texture2D>("walking/1"); billWalkingLeftLeg = Content.Load<Texture2D>("walking/2"); hillBackground = Content.Load<Texture2D>("hillBackground"); platform = Content.Load<Texture2D>("2dplatform"); /* We need XNA to draw the ground and circle at the center of the shapes */ billOrigin = new Vector2(billIdle.Width / 2f, billIdle.Height / 2f); platformOrigin = new Vector2(platform.Width / 2f, platform.Height / 2f); view = Matrix.Identity; cameraPosition = Vector2.Zero; screenCenter = new Vector2 (graphics.GraphicsDevice.Viewport.Width / 2f, graphics.GraphicsDevice.Viewport.Height / 2f); // Farseer expects objects to be scaled to MKS (meters, kilos, seconds) // 1 meters equals 64 pixels here ConvertUnits.SetDisplayUnitToSimUnitRatio(64f); billBody = BodyFactory.CreateRectangle(world, ConvertUnits.ToSimUnits(100f), ConvertUnits.ToSimUnits(100f), 1f, billPosition); // Give it some bounce and friction billBody.Restitution = 0.3f; billBody.Friction = 0.5f; platformPosition = new Vector2(5f, 650f); // Create the ground fixture platformBody = BodyFactory.CreateRectangle(world, ConvertUnits.ToSimUnits(1323f), ConvertUnits.ToSimUnits(248f), 1f, platformPosition); platformBody.IsStatic = true; platformBody.Restitution = 0.3f; platformBody.Friction = 0.5f; } protected override void UnloadContent() { } /// <summary> /// Allows the game to run logic such as updating the world, /// checking for collisions, gathering input, and playing audio. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Update(GameTime gameTime) { inputHelper.Update(); UpdateFramerate(gameTime); HandleKeyboardInput(); HandleBackgroundScroll(); //We update the world world.Step ((float)gameTime.ElapsedGameTime.TotalMilliseconds * 0.001f); base.Update(gameTime); } private void UpdateFramerate(GameTime gameTime) { var deltaTime = (float)gameTime.ElapsedGameTime.TotalSeconds; var floatFramerate = 1.0f / deltaTime; currentFramerate = (int)Math.Round(floatFramerate); } private void HandleBackgroundScroll() { if (rectangle1.X + hillBackground.Width <= 0) { rectangle1.X = rectangle2.X + hillBackground.Width; } if (rectangle2.X + hillBackground.Width <= 0) { rectangle2.X = rectangle1.X + hillBackground.Width; } } private void HandleKeyboardInput() { if (inputHelper.IsNewKeyPress (Keys.Escape)) { Exit (); } billState = BillState.IDLE; if (inputHelper.IsKeyDown(Keys.Space) && !inputHelper.IsNewKeyPress(Keys.Space)) { billState = BillState.FIGHT_STANCE; } if (inputHelper.IsKeyDown (Keys.Right)) { billState = BillState.WALKING; billPosition.X += 5f; titlePosition.X += 5f; frameratePosition.X += 5f; cameraPosition.X -= 5f; rectangle1.X += 5; rectangle2.X += 5; } else if (inputHelper.IsKeyDown (Keys.Left)) { billPosition.X -= 5f; titlePosition.X -= 5f; frameratePosition.X -= 5f; cameraPosition.X += 5f; rectangle1.X -= 5; rectangle2.X -= 5; billState = BillState.WALKING; } if (inputHelper.IsKeyDown(Keys.Down)) { billPosition.Y += 5f; billState = BillState.WALKING; //cameraPosition.Y -= 5f; } else if (inputHelper.IsKeyDown(Keys.Up)) { billPosition.Y -= 5f; billState = BillState.WALKING; //cameraPosition.Y += 5f; } if (inputHelper.IsNewKeyPress(Keys.Space)) { billState = BillState.ATTACKING; } view = Matrix.CreateTranslation (new Vector3 (cameraPosition - screenCenter, 0f)) * Matrix.CreateTranslation (new Vector3 (screenCenter, 0f)); } /// <summary> /// This is called when the game should draw itself. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.CornflowerBlue); string currentGameTimeInSeconds = gameTime.TotalGameTime.Seconds.ToString(); spriteBatch.Begin(SpriteSortMode.Deferred, null, null, null, null, null, view); spriteBatch.Draw(hillBackground, rectangle1, Color.White); spriteBatch.Draw(hillBackground, rectangle2, Color.White); DrawBill(); //spriteBatch.Draw(platform, ConvertUnits.ToDisplayUnits(platformBody.Position), null, Color.White, 0f, platformOrigin, 1f, SpriteEffects.None, 0f); spriteBatch.Draw(platform, platformPosition, Color.White); spriteBatch.DrawString(font, "Elapsed Time: " + currentGameTimeInSeconds + " seconds", titlePosition, Color.White); spriteBatch.DrawString(font, "Framerate: " + currentFramerate.ToString(), frameratePosition, Color.White); spriteBatch.End(); } private int billWalkingPosition = 0; private void DrawBill() { var thirdFrameWalkingTime = currentFramerate / 3; var twoThirdsFrameWalkingTime = thirdFrameWalkingTime * 2; switch (billState) { case BillState.IDLE: //spriteBatch.Draw(billIdle, ConvertUnits.ToDisplayUnits(billBody.Position), null, Color.White, 0f, billOrigin, 1f, SpriteEffects.None, 0f); spriteBatch.Draw(billIdle, billPosition, Color.White); break; case BillState.ATTACKING: spriteBatch.Draw(billAttacking, billPosition, Color.White); break; case BillState.WALKING: if (billWalkingPosition <= thirdFrameWalkingTime) { billWalkingPosition++; spriteBatch.Draw(billWalkingLeftLeg, billPosition, Color.White); } else if (billWalkingPosition > thirdFrameWalkingTime && billWalkingPosition <= twoThirdsFrameWalkingTime){ billWalkingPosition++; spriteBatch.Draw(billWalkingRightLeg, billPosition, Color.White); } else { billWalkingPosition = 0; spriteBatch.Draw(billWalkingLeftLeg, billPosition, Color.White); } break; case BillState.FIGHT_STANCE: billWalkingPosition = 0; spriteBatch.Draw(billFight, billPosition, Color.White); break; } } } }
36.992063
155
0.663162
[ "MIT" ]
Alemkin/monogame-platformer
app/Game1.cs
9,324
C#
using System.Threading.Tasks; namespace Pathfinder.Application.BuildingTools { /// <summary> /// Represents an abstract code runner /// </summary> public interface IRunner { /// <summary> /// Executes <paramref name="compiledAssembly"/> with the <paramref name="arguments"/> and /// returns the result as instance of <see cref="BuildingResult"/> /// </summary> /// <param name="compiledAssembly">bytes array of compiled assembly</param> /// <param name="arguments">startup arguments</param> /// <returns>instance of <see cref="BuildingResult"/></returns> Task<BuildingResult> ExecuteAsync(byte[] compiledAssembly, string[] arguments); } }
43.294118
102
0.639946
[ "MIT" ]
RomanEmreis/pathfinder
Pathfinder/Application/BuildingTools/IRunner.cs
738
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.Runtime.CompilerServices; namespace System.Reflection.Metadata.Ecma335 { internal static class HasConstantTag { internal const int NumberOfBits = 2; internal const int LargeRowSize = 0x00000001 << (16 - NumberOfBits); internal const uint Field = 0x00000000; internal const uint Param = 0x00000001; internal const uint Property = 0x00000002; internal const uint TagMask = 0x00000003; internal const TableMask TablesReferenced = TableMask.Field | TableMask.Param | TableMask.Property; internal const uint TagToTokenTypeByteVector = TokenTypeIds.FieldDef >> 24 | TokenTypeIds.ParamDef >> 16 | TokenTypeIds.Property >> 8; [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static EntityHandle ConvertToHandle(uint hasConstant) { uint tokenType = (TagToTokenTypeByteVector >> ((int)(hasConstant & TagMask) << 3)) << TokenTypeIds.RowIdBitCount; uint rowId = (hasConstant >> NumberOfBits); if (tokenType == 0 || (rowId & ~TokenTypeIds.RIDMask) != 0) { Throw.InvalidCodedIndex(); } return new EntityHandle(tokenType | rowId); } internal static uint ConvertToTag(EntityHandle token) { HandleKind tokenKind = token.Kind; uint rowId = (uint)token.RowId; if (tokenKind == HandleKind.FieldDefinition) { return rowId << NumberOfBits | Field; } else if (tokenKind == HandleKind.Parameter) { return rowId << NumberOfBits | Param; } else if (tokenKind == HandleKind.PropertyDefinition) { return rowId << NumberOfBits | Property; } return 0; } } }
35.754386
142
0.604024
[ "MIT" ]
2m0nd/runtime
src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Internal/HasConstantTag.cs
2,038
C#
using System; using System.Collections.Generic; using System.Text; namespace BapesTwitterBot.Domain.Models { public class TwitterAppSettings { public TwitterAppSettings(string key, string secret) { Key = key; Secret = secret; } public string Key { get; set; } public string Secret { get; set; } } }
18.095238
60
0.6
[ "MIT" ]
BillChirico/BapesTwitterBot
src/BapesTwitterBot.Domain/Models/TwitterAppSettings.cs
382
C#
/* * Copyright 2010-2013 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. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; namespace Amazon.Redshift.Model { /// <summary> /// <para>Describes a subnet group.</para> /// </summary> public class ClusterSubnetGroup { private string clusterSubnetGroupName; private string description; private string vpcId; private string subnetGroupStatus; private List<Subnet> subnets = new List<Subnet>(); /// <summary> /// The name of the cluster subnet group. /// /// </summary> public string ClusterSubnetGroupName { get { return this.clusterSubnetGroupName; } set { this.clusterSubnetGroupName = value; } } /// <summary> /// Sets the ClusterSubnetGroupName property /// </summary> /// <param name="clusterSubnetGroupName">The value to set for the ClusterSubnetGroupName property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public ClusterSubnetGroup WithClusterSubnetGroupName(string clusterSubnetGroupName) { this.clusterSubnetGroupName = clusterSubnetGroupName; return this; } // Check to see if ClusterSubnetGroupName property is set internal bool IsSetClusterSubnetGroupName() { return this.clusterSubnetGroupName != null; } /// <summary> /// The description of the cluster subnet group. /// /// </summary> public string Description { get { return this.description; } set { this.description = value; } } /// <summary> /// Sets the Description property /// </summary> /// <param name="description">The value to set for the Description property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public ClusterSubnetGroup WithDescription(string description) { this.description = description; return this; } // Check to see if Description property is set internal bool IsSetDescription() { return this.description != null; } /// <summary> /// The VPC ID of the cluster subnet group. /// /// </summary> public string VpcId { get { return this.vpcId; } set { this.vpcId = value; } } /// <summary> /// Sets the VpcId property /// </summary> /// <param name="vpcId">The value to set for the VpcId property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public ClusterSubnetGroup WithVpcId(string vpcId) { this.vpcId = vpcId; return this; } // Check to see if VpcId property is set internal bool IsSetVpcId() { return this.vpcId != null; } /// <summary> /// The status of the cluster subnet group. Possible values are <c>Complete</c>, <c>Incomplete</c> and <c>Invalid</c>. /// /// </summary> public string SubnetGroupStatus { get { return this.subnetGroupStatus; } set { this.subnetGroupStatus = value; } } /// <summary> /// Sets the SubnetGroupStatus property /// </summary> /// <param name="subnetGroupStatus">The value to set for the SubnetGroupStatus property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public ClusterSubnetGroup WithSubnetGroupStatus(string subnetGroupStatus) { this.subnetGroupStatus = subnetGroupStatus; return this; } // Check to see if SubnetGroupStatus property is set internal bool IsSetSubnetGroupStatus() { return this.subnetGroupStatus != null; } /// <summary> /// A list of the VPC <a>Subnet</a> elements. /// /// </summary> public List<Subnet> Subnets { get { return this.subnets; } set { this.subnets = value; } } /// <summary> /// Adds elements to the Subnets collection /// </summary> /// <param name="subnets">The values to add to the Subnets collection </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public ClusterSubnetGroup WithSubnets(params Subnet[] subnets) { foreach (Subnet element in subnets) { this.subnets.Add(element); } return this; } /// <summary> /// Adds elements to the Subnets collection /// </summary> /// <param name="subnets">The values to add to the Subnets collection </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public ClusterSubnetGroup WithSubnets(IEnumerable<Subnet> subnets) { foreach (Subnet element in subnets) { this.subnets.Add(element); } return this; } // Check to see if Subnets property is set internal bool IsSetSubnets() { return this.subnets.Count > 0; } } }
35.140704
177
0.590162
[ "Apache-2.0" ]
mahanthbeeraka/dataservices-sdk-dotnet
AWSSDK/Amazon.Redshift/Model/ClusterSubnetGroup.cs
6,993
C#
using Microsoft.AspNetCore.Components; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Dfinity.Blazor.SampleApp.Pages { public partial class Index { [Inject] public DfinityService DfinityService { get; set; } = default!; public string Output { get; set; } = "Output:"; public async Task Test() { await DfinityService.Test(); WriteOutput($"Test"); } public async Task WriteData() { WriteOutput("Writing data to IC..."); string value = DateTimeOffset.UtcNow.ToString(); await DfinityService.SetValue("time", value); WriteOutput($"Written value: {value}"); } public async Task GetData() { WriteOutput("Getting data from IC..."); string? value = await DfinityService.GetValue("time"); Console.WriteLine("Value: " + value); WriteOutput($"Get value: {value}"); } public async Task IsLoggedIn() { bool isLoggedIn = await DfinityService.IsLoggedIn(); Console.WriteLine("Logged in: " + isLoggedIn); WriteOutput($"Logged in: {isLoggedIn}"); } public async Task Login() { await DfinityService.Login(); WriteOutput($"Opend logged in window"); } public async Task Logout() { await DfinityService.Logout(); WriteOutput($"Loggout"); } public async Task WriteDataForUser() { if (!(await DfinityService.IsLoggedIn())) WriteOutput("WARNING: this will fail, user is not logged in."); string value = DateTimeOffset.UtcNow.ToString(); WriteOutput("Writing data to IC..."); await DfinityService.SetValueForUser("time", value); WriteOutput($"Write value for current user: {value}"); } public async Task GetDataForUser() { if (!(await DfinityService.IsLoggedIn())) WriteOutput("WARNING: this will fail, user is not logged in."); WriteOutput("Getting data from IC..."); var value = await DfinityService.GetValueForUser("time"); Console.WriteLine("Uservalue: " + value); WriteOutput($"Get value for current user: {value}"); } private void WriteOutput(string text) { Output += "\r\n" + text; } } }
26.752577
79
0.549904
[ "MIT" ]
michielpost/Dfinity.Blazor
src/Dfinity.Blazor.SampleApp/Pages/Index.razor.cs
2,597
C#
using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using System; using System.Threading.Tasks; using Localist.Server.Services; using Localist.Shared; namespace Localist.Server.Controllers { [Route("api/[controller]")] [ApiController] public class AccountController : ControllerBase { readonly IAccountService accountService; readonly IInviteService inviteService; readonly ILoginService loginService; public AccountController( IAccountService accountService, IInviteService inviteService, ILoginService loginService) { this.accountService = accountService; this.inviteService = inviteService; this.loginService = loginService; } [HttpPost("login")] public async Task<ActionResult<IAccountResult>> Login([FromBody] LoginModel loginModel) { await HttpContext.SignOutAsync(IdentityConstants.ApplicationScheme); var loginResult = await loginService.Login( loginModel.Username, loginModel.Password, loginModel.RememberMe); return loginResult switch { FailedAccountResult failedLoginResult => Unauthorized(failedLoginResult), SuccessfulAccountResult successfulLoginResult => Ok(successfulLoginResult), _ => throw new NotImplementedException($"Unknown {nameof(loginResult)} type: {loginResult.GetType().FullName}") }; } [HttpPost("lost-code")] public async Task<IActionResult> LostCode([FromBody] LostCodeModel model) { // todo: log IP hash // var ip = HttpContext.Connection.RemoteIpAddress?.ToString(); await inviteService.AddLostCode(model.Address); return NoContent(); } [HttpPost("register")] public async Task<ActionResult<IAccountResult>> RegisterAndLogin([FromBody] RegisterModel registerModel) { var registerResult = await accountService.Register(registerModel); if (registerResult is FailedAccountResult failedRegisterResult) { return Ok(failedRegisterResult); } else if (registerResult.Successful) { return await Login(new LoginModel { Username = registerModel.Username, Password = registerModel.Password }); } else { throw new NotImplementedException( $"Unknown {nameof(registerResult)} type: {registerResult.GetType().FullName}"); } } } }
34.341463
127
0.612216
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
mark-rafter/Localist
Server/Controllers/AccountController.cs
2,818
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Resources; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Ruler.NetCore { public sealed class MainForm : Form { #region ResizeRegion enum private enum ResizeRegion { None, N, NE, E, SE, S, SW, W, NW } #endregion private readonly ToolTip _toolTip = new ToolTip(); private Point _offset; private Rectangle _mouseDownRect; private int _resizeBorderWidth = 5; private Point _mouseDownPoint; private ResizeRegion _resizeRegion = ResizeRegion.None; private readonly ContextMenuStrip _menu = new ContextMenuStrip(); private ToolStripMenuItem _verticalMenuItem; private ToolStripMenuItem _toolTipMenuItem; public MainForm() { SetStyle(ControlStyles.ResizeRedraw, true); UpdateStyles(); ResourceManager resources = new ResourceManager(typeof(MainForm)); Icon = ((Icon)(resources.GetObject("$this.Icon"))); SetUpMenu(); Text = "Ruler"; BackColor = Color.White; ClientSize = new Size(512, 128); FormBorderStyle = FormBorderStyle.None; Opacity = 0.65; ContextMenuStrip = _menu; Font = new Font("Segoe UI", 10); SetStyle(ControlStyles.DoubleBuffer | ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint, true); } private bool IsVertical { get => _verticalMenuItem.Checked; set => _verticalMenuItem.Checked = value; } private bool ShowToolTip { get => _toolTipMenuItem.Checked; set { _toolTipMenuItem.Checked = value; if (value) { SetToolTip(); } } } private void SetUpMenu() { AddMenuItem("Stay On Top"); _verticalMenuItem = AddMenuItem("Vertical"); _toolTipMenuItem = AddMenuItem("Tool Tip"); ToolStripMenuItem opacityMenuItem = AddMenuItem("Opacity"); _menu.Items.Add(new ToolStripSeparator()); AddMenuItem("About"); _menu.Items.Add(new ToolStripSeparator()); AddMenuItem("Exit"); for (int i = 10; i <= 100; i += 10) { ToolStripMenuItem subMenu = new ToolStripMenuItem(i + "%"); subMenu.Click += OpacityMenuHandler; opacityMenuItem.DropDownItems.Add(subMenu); } } private ToolStripMenuItem AddMenuItem(string text, Keys shortcut = Keys.None) { ToolStripMenuItem mi = new ToolStripMenuItem(text); mi.Click += MenuHandler; mi.ShortcutKeys = shortcut; _menu.Items.Add(mi); return mi; } protected override void OnMouseDown(MouseEventArgs e) { _offset = new Point(MousePosition.X - Location.X, MousePosition.Y - Location.Y); _mouseDownPoint = MousePosition; _mouseDownRect = ClientRectangle; base.OnMouseDown(e); } protected override void OnMouseUp(MouseEventArgs e) { _resizeRegion = ResizeRegion.None; base.OnMouseUp(e); } protected override void OnMouseMove(MouseEventArgs e) { if (_resizeRegion != ResizeRegion.None) { HandleResize(); return; } Point clientCursorPos = PointToClient(MousePosition); Rectangle resizeInnerRect = ClientRectangle; resizeInnerRect.Inflate(-_resizeBorderWidth, -_resizeBorderWidth); bool inResizableArea = ClientRectangle.Contains(clientCursorPos) && !resizeInnerRect.Contains(clientCursorPos); if (inResizableArea) { ResizeRegion resizeRegion = GetResizeRegion(clientCursorPos); SetResizeCursor(resizeRegion); if (e.Button == MouseButtons.Left) { _resizeRegion = resizeRegion; HandleResize(); } } else { Cursor = Cursors.Default; if (e.Button == MouseButtons.Left) { Location = new Point(MousePosition.X - _offset.X, MousePosition.Y - _offset.Y); } } base.OnMouseMove(e); } protected override void OnResize(EventArgs e) { if (ShowToolTip) { SetToolTip(); } base.OnResize(e); } private void SetToolTip() { _toolTip.SetToolTip(this, $"Width: {Width} pixels\nHeight: {Height} pixels"); } protected override void OnKeyDown(KeyEventArgs e) { switch (e.KeyCode) { case Keys.Right: case Keys.Left: case Keys.Up: case Keys.Down: HandleMoveResizeKeystroke(e); break; case Keys.Space: ChangeOrientation(); break; } base.OnKeyDown(e); } private void HandleMoveResizeKeystroke(KeyEventArgs e) { if (e.KeyCode == Keys.Right) { if (e.Control) { if (e.Shift) { Width += 1; } else { Left += 1; } } else { Left += 5; } } else if (e.KeyCode == Keys.Left) { if (e.Control) { if (e.Shift) { Width -= 1; } else { Left -= 1; } } else { Left -= 5; } } else if (e.KeyCode == Keys.Up) { if (e.Control) { if (e.Shift) { Height -= 1; } else { Top -= 1; } } else { Top -= 5; } } else if (e.KeyCode == Keys.Down) { if (e.Control) { if (e.Shift) { Height += 1; } else { Top += 1; } } else { Top += 5; } } } private void HandleResize() { switch (_resizeRegion) { case ResizeRegion.E: { int diff = MousePosition.X - _mouseDownPoint.X; Width = _mouseDownRect.Width + diff; break; } case ResizeRegion.S: { int diff = MousePosition.Y - _mouseDownPoint.Y; Height = _mouseDownRect.Height + diff; break; } case ResizeRegion.SE: { Width = _mouseDownRect.Width + MousePosition.X - _mouseDownPoint.X; Height = _mouseDownRect.Height + MousePosition.Y - _mouseDownPoint.Y; break; } } } private void SetResizeCursor(ResizeRegion region) { switch (region) { case ResizeRegion.N: case ResizeRegion.S: Cursor = Cursors.SizeNS; break; case ResizeRegion.E: case ResizeRegion.W: Cursor = Cursors.SizeWE; break; case ResizeRegion.NW: case ResizeRegion.SE: Cursor = Cursors.SizeNWSE; break; default: Cursor = Cursors.SizeNESW; break; } } private ResizeRegion GetResizeRegion(Point clientCursorPos) { if (clientCursorPos.Y <= _resizeBorderWidth) { if (clientCursorPos.X <= _resizeBorderWidth) return ResizeRegion.NW; else if (clientCursorPos.X >= Width - _resizeBorderWidth) return ResizeRegion.NE; else return ResizeRegion.N; } else if (clientCursorPos.Y >= Height - _resizeBorderWidth) { if (clientCursorPos.X <= _resizeBorderWidth) return ResizeRegion.SW; else if (clientCursorPos.X >= Width - _resizeBorderWidth) return ResizeRegion.SE; else return ResizeRegion.S; } else { if (clientCursorPos.X <= _resizeBorderWidth) return ResizeRegion.W; else return ResizeRegion.E; } } protected override void OnPaint(PaintEventArgs e) { Graphics graphics = e.Graphics; int height = Height; int width = Width; if (IsVertical) { graphics.RotateTransform(90); graphics.TranslateTransform(0, -Width + 1); height = Width; width = Height; } DrawRuler(graphics, width, height); base.OnPaint(e); } private void DrawRuler(Graphics g, int formWidth, int formHeight) { // Border g.DrawRectangle(Pens.Black, 0, 0, formWidth - 1, formHeight - 1); // Width g.DrawString(formWidth + " pixels", Font, Brushes.Black, 10, (formHeight / 2) - (Font.Height / 2)); // Ticks for (int i = 0; i < formWidth; i++) { if (i % 2 == 0) { int tickHeight; if (i % 100 == 0) { tickHeight = 15; DrawTickLabel(g, i.ToString(), i, formHeight, tickHeight); } else if (i % 10 == 0) { tickHeight = 10; } else { tickHeight = 5; } DrawTick(g, i, formHeight, tickHeight); } } } private static void DrawTick(Graphics g, int xPos, int formHeight, int tickHeight) { // Top g.DrawLine(Pens.Black, xPos, 0, xPos, tickHeight); // Bottom g.DrawLine(Pens.Black, xPos, formHeight, xPos, formHeight - tickHeight); } private void DrawTickLabel(Graphics g, string text, int xPos, int formHeight, int height) { // Top g.DrawString(text, Font, Brushes.Black, xPos, height); // Bottom g.DrawString(text, Font, Brushes.Black, xPos, formHeight - height - Font.Height); } private void OpacityMenuHandler(object sender, EventArgs e) { ToolStripMenuItem mi = (ToolStripMenuItem)sender; Opacity = double.Parse(mi.Text.Replace("%", "")) / 100; } private void MenuHandler(object sender, EventArgs e) { ToolStripMenuItem mi = (ToolStripMenuItem)sender; switch (mi.Text) { case "Exit": Close(); break; case "Tool Tip": ShowToolTip = !ShowToolTip; break; case "Vertical": ChangeOrientation(); break; case "Stay On Top": mi.Checked = !mi.Checked; TopMost = mi.Checked; break; case "About": string message = $"Ruler v{Application.ProductVersion} by Jeff Key\nwww.sliver.com\nIcon by Kristen Magee @ www.kbecca.com"; MessageBox.Show(message, "About Ruler", MessageBoxButtons.OK, MessageBoxIcon.Information); break; default: // MessageBox.Show("Unknown menu item."); break; } } private void ChangeOrientation() { IsVertical = !IsVertical; int width = Width; Width = Height; Height = width; } } }
29.683406
131
0.443031
[ "MIT" ]
EdiWang/Ruler
src/Ruler.NetCore/MainForm.cs
13,597
C#
using System; using System.Collections.Generic; namespace KubeSampleApi.Models { public partial class ProductModel { public ProductModel() { Products = new HashSet<Product>(); ProductModelProductDescriptions = new HashSet<ProductModelProductDescription>(); } public int ProductModelId { get; set; } public string Name { get; set; } public string CatalogDescription { get; set; } public Guid Rowguid { get; set; } public DateTime ModifiedDate { get; set; } public ICollection<Product> Products { get; set; } public ICollection<ProductModelProductDescription> ProductModelProductDescriptions { get; set; } } }
30.333333
104
0.653846
[ "MIT" ]
comfycoder/azure-kubernetes-sample
KubeSampleApi/Models/ProductModel.cs
730
C#
using IvmpDotNet.SDK; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using IvmpDotNet.Imports; namespace IvmpDotNet.Wrappings { public class ScriptManager : IScriptManager { public bool LoadScript(string szScript) { return Scripts.Scripts_LoadScript(szScript); } public bool UnloadScript(string szScript) { return Scripts.Scripts_UnloadScript(szScript); } public bool ReloadScript(string szScript) { return Scripts.Scripts_ReloadScript(szScript); } public bool LoadClientScript(string szScript) { return Scripts.Scripts_LoadClientScript(szScript); } public bool UnloadClientScript(string szScript) { return Scripts.Scripts_UnloadClientScript(szScript); } public bool ReloadClientScript(string szScript) { return Scripts.Scripts_ReloadClientScript(szScript); } public bool LoadClientResource(string szResource) { return Scripts.Scripts_LoadClientResource(szResource); } public bool UnloadClientResource(string szResource) { return Scripts.Scripts_UnloadClientResource(szResource); } public bool ReloadClientResource(string szResource) { return Scripts.Scripts_ReloadClientResource(szResource); } } }
29.958333
68
0.680111
[ "MIT" ]
purm/IvmpDotNet
IvmpDotNet.Core/Wrappings/ScriptManager.cs
1,440
C#
using System.Reflection; using System.Text; namespace Classes.Models { internal class GSM { private static GSM iPhone4S; private string model; private string manufacturer; private string owner; private Battery battery; private Display display; public static GSM IPhone4S { get { return iPhone4S; } set { iPhone4S = value; } } public string Model { get { return this.model; } set { this.model = value; } } public string Manufacturer { get { return this.manufacturer; } set { this.manufacturer = value; } } public string Owner { get { return this.owner; } set { this.owner = value; } } public Battery Battery { get { return this.battery; } set { this.battery = value; } } public Display Display { get { return this.display; } set { this.display = value; } } static GSM() { IPhone4S = new GSM("iPhone 4S", "Apple", "Orlin", new Battery("Chinese", 85, 44, BatteryType.LiIon), new Display(5, 65536)); } public GSM(string model, string manufacturer, string owner, Battery battery, Display display) { this.Model = model; this.Manufacturer = manufacturer; this.Owner = owner; this.Battery = battery; this.Display = display; } public override string ToString() { var sb = new StringBuilder(); foreach (PropertyInfo propertyInfo in this.GetType().GetProperties()) { sb.AppendLine(propertyInfo.ToString()); } return sb.ToString(); } } }
20.594828
136
0.405609
[ "MIT" ]
orlindraganov/TAADefiningClasses
Classes/Models/GSM.cs
2,391
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Bbt.Campaign.Core.DbEntities { public class CustomerReportDetailEntity { public string? CampaignCode { get; set; } //"campaignCode": "1", public string? CampaignName { get; set; } //"campaignName": "Demo", public bool? IsActive { get; set; } //"isBundle": false, public bool? IsBundle { get; set; } //"isActive": true, public string? CustomerNumber { get; set; } //"customerNumber": "20070101", public string? CustomerId { get; set; } //"customerId": "12345678910", public string? CustomerType { get; set; } //"customerType": "Gercek", public string? BranchCode { get; set; } //"branchCode": "2000", public string? BusinessLine { get; set; } //"businessLine": "X", public string? EarningType { get; set; } //"earningType": "Cashback", public DateTime? CustomerJoinDate { get; set; } //"customerJoinDate": "2022-05-07T00:00:00", public string? CustomerJoinDateStr { get; set; } public decimal? EarningAmount { get; set; } //"earningAmount": 30, public string? EarningAmountStr { get; set; } //"earningAmount": 30, public decimal? EarningRate { get; set; } //"earningRate": null, public string? EarningRateStr { get; set; } //"earningRate": null, public bool? IsEarningUsed { get; set; } //"isEarningUsed": true, public DateTime? EarningUsedDate { get; set; } //"earningUsedDate": "2022-05-18T00:00:00", public string? EarningUsedDateStr { get; set; } public DateTime? CampaignStartDate { get; set; } //"campaignStartDate": "2022-05-01T00:00:00" public string? CampaignStartDateStr { get; set; } } }
53.205882
103
0.640133
[ "MIT" ]
hub-burgan-com-tr/bbt.loyalty
src/Bbt.Campaign.Api/Bbt.Campaign.Core/DbEntities/CustomerReportDetailEntity.cs
1,811
C#
using System; using System.ComponentModel; using Tizen.NUI.Binding; using Tizen.NUI.Binding.Internals; namespace Tizen.NUI.Xaml { /// This will be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] [ContentProperty("Key")] public sealed class DynamicResourceExtension : IMarkupExtension<DynamicResource> { /// This will be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public string Key { get; set; } /// This will be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public object ProvideValue(IServiceProvider serviceProvider) { return ((IMarkupExtension<DynamicResource>)this).ProvideValue(serviceProvider); } DynamicResource IMarkupExtension<DynamicResource>.ProvideValue(IServiceProvider serviceProvider) { if (Key == null) { var lineInfoProvider = serviceProvider.GetService(typeof (IXmlLineInfoProvider)) as IXmlLineInfoProvider; var lineInfo = (lineInfoProvider != null) ? lineInfoProvider.XmlLineInfo : new XmlLineInfo(); throw new XamlParseException("DynamicResource markup require a Key", lineInfo); } return new DynamicResource(Key); } } }
43.771429
121
0.686684
[ "Apache-2.0", "MIT" ]
Ali-Alzyoud/TizenFX
src/Tizen.NUI/src/public/Xaml/MarkupExtensions/DynamicResourceExtension.cs
1,532
C#
using Newtonsoft.Json; using System; using System.Collections.Generic; namespace KubeClient.Models { /// <summary> /// Represents a host path mapped into a pod. Host path volumes do not support ownership management or SELinux relabeling. /// </summary> public partial class HostPathVolumeSourceV1 { /// <summary> /// Path of the directory on the host. More info: https://kubernetes.io/docs/concepts/storage/volumes#hostpath /// </summary> [JsonProperty("path")] public string Path { get; set; } /// <summary> /// The volume type. Can be one of ["File", "Directory", "FileOrCreate", "DirectoryOrCreate", "Socket", "CharDevice", "BlockDevice"]. /// </summary> [JsonProperty("type")] public string Type { get; set; } } }
33.44
145
0.619617
[ "MIT" ]
AndreasBieber/dotnet-kube-client
src/KubeClient/Models/HostPathVolumeSourceV1.cs
836
C#
// <auto-generated /> using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using playground.Data; namespace playground.Migrations { [DbContext(typeof(DatabaseContext))] [Migration("20210203115418_AddindUserActionKeys")] partial class AddindUserActionKeys { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "5.0.2"); modelBuilder.Entity("playground.Entities.ERole", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<int>("EUserId") .HasColumnType("INTEGER"); b.Property<int>("Role") .HasColumnType("INTEGER"); b.HasKey("Id"); b.HasIndex("EUserId"); b.ToTable("Roles"); }); modelBuilder.Entity("playground.Entities.EUser", b => { b.Property<int>("id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<DateTime>("CreatedUTC") .HasColumnType("TEXT"); b.Property<string>("Email") .IsRequired() .HasColumnType("TEXT"); b.Property<string>("FirstName") .IsRequired() .HasColumnType("TEXT"); b.Property<DateTime>("LastLoginUTC") .HasColumnType("TEXT"); b.Property<string>("LastName") .IsRequired() .HasColumnType("TEXT"); b.Property<DateTime>("LastUpdatedUTC") .HasColumnType("TEXT"); b.Property<int>("LoginsCount") .HasColumnType("INTEGER"); b.Property<byte[]>("PasswordHash") .HasColumnType("BLOB"); b.Property<byte[]>("PasswordSalt") .HasColumnType("BLOB"); b.HasKey("id"); b.ToTable("Users"); }); modelBuilder.Entity("playground.Entities.EUserActionKeys", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<Guid>("ActionKey") .HasColumnType("TEXT"); b.Property<int?>("EUserid") .HasColumnType("INTEGER"); b.Property<int>("UserId") .HasColumnType("INTEGER"); b.HasKey("Id"); b.HasIndex("EUserid"); b.ToTable("UserActionKeys"); }); modelBuilder.Entity("playground.Entities.ERole", b => { b.HasOne("playground.Entities.EUser", "EUser") .WithMany("Roles") .HasForeignKey("EUserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("EUser"); }); modelBuilder.Entity("playground.Entities.EUserActionKeys", b => { b.HasOne("playground.Entities.EUser", "EUser") .WithMany("UserActionKeys") .HasForeignKey("EUserid") .OnDelete(DeleteBehavior.Cascade); b.Navigation("EUser"); }); modelBuilder.Entity("playground.Entities.EUser", b => { b.Navigation("Roles"); b.Navigation("UserActionKeys"); }); #pragma warning restore 612, 618 } } }
32.022388
75
0.451876
[ "MIT" ]
MTokarev/playground
playground/Migrations/20210203115418_AddindUserActionKeys.Designer.cs
4,293
C#
// <auto-generated> // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/talent/v4beta1/filters.proto // </auto-generated> #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace Google.Cloud.Talent.V4Beta1 { /// <summary>Holder for reflection information generated from google/cloud/talent/v4beta1/filters.proto</summary> public static partial class FiltersReflection { #region Descriptor /// <summary>File descriptor for google/cloud/talent/v4beta1/filters.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static FiltersReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "Cilnb29nbGUvY2xvdWQvdGFsZW50L3Y0YmV0YTEvZmlsdGVycy5wcm90bxIb", "Z29vZ2xlLmNsb3VkLnRhbGVudC52NGJldGExGhxnb29nbGUvYXBpL2Fubm90", "YXRpb25zLnByb3RvGihnb29nbGUvY2xvdWQvdGFsZW50L3Y0YmV0YTEvY29t", "bW9uLnByb3RvGh5nb29nbGUvcHJvdG9idWYvZHVyYXRpb24ucHJvdG8aH2dv", "b2dsZS9wcm90b2J1Zi90aW1lc3RhbXAucHJvdG8aHmdvb2dsZS9wcm90b2J1", "Zi93cmFwcGVycy5wcm90bxoWZ29vZ2xlL3R5cGUvZGF0ZS5wcm90bxoYZ29v", "Z2xlL3R5cGUvbGF0bG5nLnByb3RvGhtnb29nbGUvdHlwZS90aW1lb2ZkYXku", "cHJvdG8i4wQKCEpvYlF1ZXJ5Eg0KBXF1ZXJ5GAEgASgJEhEKCWNvbXBhbmll", "cxgCIAMoCRJFChBsb2NhdGlvbl9maWx0ZXJzGAMgAygLMisuZ29vZ2xlLmNs", "b3VkLnRhbGVudC52NGJldGExLkxvY2F0aW9uRmlsdGVyEkAKDmpvYl9jYXRl", "Z29yaWVzGAQgAygOMiguZ29vZ2xlLmNsb3VkLnRhbGVudC52NGJldGExLkpv", "YkNhdGVnb3J5EkIKDmNvbW11dGVfZmlsdGVyGAUgASgLMiouZ29vZ2xlLmNs", "b3VkLnRhbGVudC52NGJldGExLkNvbW11dGVGaWx0ZXISHQoVY29tcGFueV9k", "aXNwbGF5X25hbWVzGAYgAygJEkwKE2NvbXBlbnNhdGlvbl9maWx0ZXIYByAB", "KAsyLy5nb29nbGUuY2xvdWQudGFsZW50LnY0YmV0YTEuQ29tcGVuc2F0aW9u", "RmlsdGVyEh8KF2N1c3RvbV9hdHRyaWJ1dGVfZmlsdGVyGAggASgJEhsKE2Rp", "c2FibGVfc3BlbGxfY2hlY2sYCSABKAgSRQoQZW1wbG95bWVudF90eXBlcxgK", "IAMoDjIrLmdvb2dsZS5jbG91ZC50YWxlbnQudjRiZXRhMS5FbXBsb3ltZW50", "VHlwZRIWCg5sYW5ndWFnZV9jb2RlcxgLIAMoCRJHChJwdWJsaXNoX3RpbWVf", "cmFuZ2UYDCABKAsyKy5nb29nbGUuY2xvdWQudGFsZW50LnY0YmV0YTEuVGlt", "ZXN0YW1wUmFuZ2USFQoNZXhjbHVkZWRfam9icxgNIAMoCSKiCAoMUHJvZmls", "ZVF1ZXJ5Eg0KBXF1ZXJ5GAEgASgJEkUKEGxvY2F0aW9uX2ZpbHRlcnMYAiAD", "KAsyKy5nb29nbGUuY2xvdWQudGFsZW50LnY0YmV0YTEuTG9jYXRpb25GaWx0", "ZXISRgoRam9iX3RpdGxlX2ZpbHRlcnMYAyADKAsyKy5nb29nbGUuY2xvdWQu", "dGFsZW50LnY0YmV0YTEuSm9iVGl0bGVGaWx0ZXISRQoQZW1wbG95ZXJfZmls", "dGVycxgEIAMoCzIrLmdvb2dsZS5jbG91ZC50YWxlbnQudjRiZXRhMS5FbXBs", "b3llckZpbHRlchJHChFlZHVjYXRpb25fZmlsdGVycxgFIAMoCzIsLmdvb2ds", "ZS5jbG91ZC50YWxlbnQudjRiZXRhMS5FZHVjYXRpb25GaWx0ZXISPwoNc2tp", "bGxfZmlsdGVycxgGIAMoCzIoLmdvb2dsZS5jbG91ZC50YWxlbnQudjRiZXRh", "MS5Ta2lsbEZpbHRlchJRChZ3b3JrX2V4cGVyaWVuY2VfZmlsdGVyGAcgAygL", "MjEuZ29vZ2xlLmNsb3VkLnRhbGVudC52NGJldGExLldvcmtFeHBlcmllbmNl", "RmlsdGVyEj0KDHRpbWVfZmlsdGVycxgIIAMoCzInLmdvb2dsZS5jbG91ZC50", "YWxlbnQudjRiZXRhMS5UaW1lRmlsdGVyEjIKDmhpcmFibGVfZmlsdGVyGAkg", "ASgLMhouZ29vZ2xlLnByb3RvYnVmLkJvb2xWYWx1ZRJUChhhcHBsaWNhdGlv", "bl9kYXRlX2ZpbHRlcnMYCiADKAsyMi5nb29nbGUuY2xvdWQudGFsZW50LnY0", "YmV0YTEuQXBwbGljYXRpb25EYXRlRmlsdGVyEmUKIWFwcGxpY2F0aW9uX291", "dGNvbWVfbm90ZXNfZmlsdGVycxgLIAMoCzI6Lmdvb2dsZS5jbG91ZC50YWxl", "bnQudjRiZXRhMS5BcHBsaWNhdGlvbk91dGNvbWVOb3Rlc0ZpbHRlchJSChdh", "cHBsaWNhdGlvbl9qb2JfZmlsdGVycxgNIAMoCzIxLmdvb2dsZS5jbG91ZC50", "YWxlbnQudjRiZXRhMS5BcHBsaWNhdGlvbkpvYkZpbHRlchIfChdjdXN0b21f", "YXR0cmlidXRlX2ZpbHRlchgPIAEoCRJfCh1jYW5kaWRhdGVfYXZhaWxhYmls", "aXR5X2ZpbHRlchgQIAEoCzI4Lmdvb2dsZS5jbG91ZC50YWxlbnQudjRiZXRh", "MS5DYW5kaWRhdGVBdmFpbGFiaWxpdHlGaWx0ZXISSgoTcGVyc29uX25hbWVf", "ZmlsdGVycxgRIAMoCzItLmdvb2dsZS5jbG91ZC50YWxlbnQudjRiZXRhMS5Q", "ZXJzb25OYW1lRmlsdGVyIt8CCg5Mb2NhdGlvbkZpbHRlchIPCgdhZGRyZXNz", "GAEgASgJEhMKC3JlZ2lvbl9jb2RlGAIgASgJEiQKB2xhdF9sbmcYAyABKAsy", "Ey5nb29nbGUudHlwZS5MYXRMbmcSGQoRZGlzdGFuY2VfaW5fbWlsZXMYBCAB", "KAESYQoWdGVsZWNvbW11dGVfcHJlZmVyZW5jZRgFIAEoDjJBLmdvb2dsZS5j", "bG91ZC50YWxlbnQudjRiZXRhMS5Mb2NhdGlvbkZpbHRlci5UZWxlY29tbXV0", "ZVByZWZlcmVuY2USDwoHbmVnYXRlZBgGIAEoCCJyChVUZWxlY29tbXV0ZVBy", "ZWZlcmVuY2USJgoiVEVMRUNPTU1VVEVfUFJFRkVSRU5DRV9VTlNQRUNJRklF", "RBAAEhgKFFRFTEVDT01NVVRFX0VYQ0xVREVEEAESFwoTVEVMRUNPTU1VVEVf", "QUxMT1dFRBACIsADChJDb21wZW5zYXRpb25GaWx0ZXISSAoEdHlwZRgBIAEo", "DjI6Lmdvb2dsZS5jbG91ZC50YWxlbnQudjRiZXRhMS5Db21wZW5zYXRpb25G", "aWx0ZXIuRmlsdGVyVHlwZRJNCgV1bml0cxgCIAMoDjI+Lmdvb2dsZS5jbG91", "ZC50YWxlbnQudjRiZXRhMS5Db21wZW5zYXRpb25JbmZvLkNvbXBlbnNhdGlv", "blVuaXQSTgoFcmFuZ2UYAyABKAsyPy5nb29nbGUuY2xvdWQudGFsZW50LnY0", "YmV0YTEuQ29tcGVuc2F0aW9uSW5mby5Db21wZW5zYXRpb25SYW5nZRI4CjBp", "bmNsdWRlX2pvYnNfd2l0aF91bnNwZWNpZmllZF9jb21wZW5zYXRpb25fcmFu", "Z2UYBCABKAgihgEKCkZpbHRlclR5cGUSGwoXRklMVEVSX1RZUEVfVU5TUEVD", "SUZJRUQQABINCglVTklUX09OTFkQARITCg9VTklUX0FORF9BTU9VTlQQAhIa", "ChZBTk5VQUxJWkVEX0JBU0VfQU1PVU5UEAMSGwoXQU5OVUFMSVpFRF9UT1RB", "TF9BTU9VTlQQBCK8AwoNQ29tbXV0ZUZpbHRlchJCCg5jb21tdXRlX21ldGhv", "ZBgBIAEoDjIqLmdvb2dsZS5jbG91ZC50YWxlbnQudjRiZXRhMS5Db21tdXRl", "TWV0aG9kEi4KEXN0YXJ0X2Nvb3JkaW5hdGVzGAIgASgLMhMuZ29vZ2xlLnR5", "cGUuTGF0TG5nEjIKD3RyYXZlbF9kdXJhdGlvbhgDIAEoCzIZLmdvb2dsZS5w", "cm90b2J1Zi5EdXJhdGlvbhIhChlhbGxvd19pbXByZWNpc2VfYWRkcmVzc2Vz", "GAQgASgIEk4KDHJvYWRfdHJhZmZpYxgFIAEoDjI2Lmdvb2dsZS5jbG91ZC50", "YWxlbnQudjRiZXRhMS5Db21tdXRlRmlsdGVyLlJvYWRUcmFmZmljSAASMAoO", "ZGVwYXJ0dXJlX3RpbWUYBiABKAsyFi5nb29nbGUudHlwZS5UaW1lT2ZEYXlI", "ACJMCgtSb2FkVHJhZmZpYxIcChhST0FEX1RSQUZGSUNfVU5TUEVDSUZJRUQQ", "ABIQCgxUUkFGRklDX0ZSRUUQARINCglCVVNZX0hPVVIQAkIQCg50cmFmZmlj", "X29wdGlvbiI0Cg5Kb2JUaXRsZUZpbHRlchIRCglqb2JfdGl0bGUYASABKAkS", "DwoHbmVnYXRlZBgCIAEoCCItCgtTa2lsbEZpbHRlchINCgVza2lsbBgBIAEo", "CRIPCgduZWdhdGVkGAIgASgIIqECCg5FbXBsb3llckZpbHRlchIQCghlbXBs", "b3llchgBIAEoCRJMCgRtb2RlGAIgASgOMj4uZ29vZ2xlLmNsb3VkLnRhbGVu", "dC52NGJldGExLkVtcGxveWVyRmlsdGVyLkVtcGxveWVyRmlsdGVyTW9kZRIP", "CgduZWdhdGVkGAMgASgIIp0BChJFbXBsb3llckZpbHRlck1vZGUSJAogRU1Q", "TE9ZRVJfRklMVEVSX01PREVfVU5TUEVDSUZJRUQQABIaChZBTExfRU1QTE9Z", "TUVOVF9SRUNPUkRTEAESIwofQ1VSUkVOVF9FTVBMT1lNRU5UX1JFQ09SRFNf", "T05MWRACEiAKHFBBU1RfRU1QTE9ZTUVOVF9SRUNPUkRTX09OTFkQAyKIAQoP", "RWR1Y2F0aW9uRmlsdGVyEg4KBnNjaG9vbBgBIAEoCRIWCg5maWVsZF9vZl9z", "dHVkeRgCIAEoCRI8CgtkZWdyZWVfdHlwZRgDIAEoDjInLmdvb2dsZS5jbG91", "ZC50YWxlbnQudjRiZXRhMS5EZWdyZWVUeXBlEg8KB25lZ2F0ZWQYBiABKAgi", "fAoUV29ya0V4cGVyaWVuY2VGaWx0ZXISMQoObWluX2V4cGVyaWVuY2UYASAB", "KAsyGS5nb29nbGUucHJvdG9idWYuRHVyYXRpb24SMQoObWF4X2V4cGVyaWVu", "Y2UYAiABKAsyGS5nb29nbGUucHJvdG9idWYuRHVyYXRpb24iYwoVQXBwbGlj", "YXRpb25EYXRlRmlsdGVyEiUKCnN0YXJ0X2RhdGUYASABKAsyES5nb29nbGUu", "dHlwZS5EYXRlEiMKCGVuZF9kYXRlGAIgASgLMhEuZ29vZ2xlLnR5cGUuRGF0", "ZSJHCh1BcHBsaWNhdGlvbk91dGNvbWVOb3Rlc0ZpbHRlchIVCg1vdXRjb21l", "X25vdGVzGAEgASgJEg8KB25lZ2F0ZWQYAiABKAgiVgoUQXBwbGljYXRpb25K", "b2JGaWx0ZXISGgoSam9iX3JlcXVpc2l0aW9uX2lkGAIgASgJEhEKCWpvYl90", "aXRsZRgDIAEoCRIPCgduZWdhdGVkGAQgASgIIvwBCgpUaW1lRmlsdGVyEi4K", "CnN0YXJ0X3RpbWUYASABKAsyGi5nb29nbGUucHJvdG9idWYuVGltZXN0YW1w", "EiwKCGVuZF90aW1lGAIgASgLMhouZ29vZ2xlLnByb3RvYnVmLlRpbWVzdGFt", "cBJFCgp0aW1lX2ZpZWxkGAMgASgOMjEuZ29vZ2xlLmNsb3VkLnRhbGVudC52", "NGJldGExLlRpbWVGaWx0ZXIuVGltZUZpZWxkIkkKCVRpbWVGaWVsZBIaChZU", "SU1FX0ZJRUxEX1VOU1BFQ0lGSUVEEAASDwoLQ1JFQVRFX1RJTUUQARIPCgtV", "UERBVEVfVElNRRACIi4KG0NhbmRpZGF0ZUF2YWlsYWJpbGl0eUZpbHRlchIP", "CgduZWdhdGVkGAEgASgIIicKEFBlcnNvbk5hbWVGaWx0ZXISEwoLcGVyc29u", "X25hbWUYASABKAlCegofY29tLmdvb2dsZS5jbG91ZC50YWxlbnQudjRiZXRh", "MUIMRmlsdGVyc1Byb3RvUAFaQWdvb2dsZS5nb2xhbmcub3JnL2dlbnByb3Rv", "L2dvb2dsZWFwaXMvY2xvdWQvdGFsZW50L3Y0YmV0YTE7dGFsZW50ogIDQ1RT", "YgZwcm90bzM=")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::Google.Api.AnnotationsReflection.Descriptor, global::Google.Cloud.Talent.V4Beta1.CommonReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.DurationReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.TimestampReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.WrappersReflection.Descriptor, global::Google.Type.DateReflection.Descriptor, global::Google.Type.LatlngReflection.Descriptor, global::Google.Type.TimeofdayReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Talent.V4Beta1.JobQuery), global::Google.Cloud.Talent.V4Beta1.JobQuery.Parser, new[]{ "Query", "Companies", "LocationFilters", "JobCategories", "CommuteFilter", "CompanyDisplayNames", "CompensationFilter", "CustomAttributeFilter", "DisableSpellCheck", "EmploymentTypes", "LanguageCodes", "PublishTimeRange", "ExcludedJobs" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Talent.V4Beta1.ProfileQuery), global::Google.Cloud.Talent.V4Beta1.ProfileQuery.Parser, new[]{ "Query", "LocationFilters", "JobTitleFilters", "EmployerFilters", "EducationFilters", "SkillFilters", "WorkExperienceFilter", "TimeFilters", "HirableFilter", "ApplicationDateFilters", "ApplicationOutcomeNotesFilters", "ApplicationJobFilters", "CustomAttributeFilter", "CandidateAvailabilityFilter", "PersonNameFilters" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Talent.V4Beta1.LocationFilter), global::Google.Cloud.Talent.V4Beta1.LocationFilter.Parser, new[]{ "Address", "RegionCode", "LatLng", "DistanceInMiles", "TelecommutePreference", "Negated" }, null, new[]{ typeof(global::Google.Cloud.Talent.V4Beta1.LocationFilter.Types.TelecommutePreference) }, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Talent.V4Beta1.CompensationFilter), global::Google.Cloud.Talent.V4Beta1.CompensationFilter.Parser, new[]{ "Type", "Units", "Range", "IncludeJobsWithUnspecifiedCompensationRange" }, null, new[]{ typeof(global::Google.Cloud.Talent.V4Beta1.CompensationFilter.Types.FilterType) }, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Talent.V4Beta1.CommuteFilter), global::Google.Cloud.Talent.V4Beta1.CommuteFilter.Parser, new[]{ "CommuteMethod", "StartCoordinates", "TravelDuration", "AllowImpreciseAddresses", "RoadTraffic", "DepartureTime" }, new[]{ "TrafficOption" }, new[]{ typeof(global::Google.Cloud.Talent.V4Beta1.CommuteFilter.Types.RoadTraffic) }, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Talent.V4Beta1.JobTitleFilter), global::Google.Cloud.Talent.V4Beta1.JobTitleFilter.Parser, new[]{ "JobTitle", "Negated" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Talent.V4Beta1.SkillFilter), global::Google.Cloud.Talent.V4Beta1.SkillFilter.Parser, new[]{ "Skill", "Negated" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Talent.V4Beta1.EmployerFilter), global::Google.Cloud.Talent.V4Beta1.EmployerFilter.Parser, new[]{ "Employer", "Mode", "Negated" }, null, new[]{ typeof(global::Google.Cloud.Talent.V4Beta1.EmployerFilter.Types.EmployerFilterMode) }, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Talent.V4Beta1.EducationFilter), global::Google.Cloud.Talent.V4Beta1.EducationFilter.Parser, new[]{ "School", "FieldOfStudy", "DegreeType", "Negated" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Talent.V4Beta1.WorkExperienceFilter), global::Google.Cloud.Talent.V4Beta1.WorkExperienceFilter.Parser, new[]{ "MinExperience", "MaxExperience" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Talent.V4Beta1.ApplicationDateFilter), global::Google.Cloud.Talent.V4Beta1.ApplicationDateFilter.Parser, new[]{ "StartDate", "EndDate" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Talent.V4Beta1.ApplicationOutcomeNotesFilter), global::Google.Cloud.Talent.V4Beta1.ApplicationOutcomeNotesFilter.Parser, new[]{ "OutcomeNotes", "Negated" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Talent.V4Beta1.ApplicationJobFilter), global::Google.Cloud.Talent.V4Beta1.ApplicationJobFilter.Parser, new[]{ "JobRequisitionId", "JobTitle", "Negated" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Talent.V4Beta1.TimeFilter), global::Google.Cloud.Talent.V4Beta1.TimeFilter.Parser, new[]{ "StartTime", "EndTime", "TimeField" }, null, new[]{ typeof(global::Google.Cloud.Talent.V4Beta1.TimeFilter.Types.TimeField) }, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Talent.V4Beta1.CandidateAvailabilityFilter), global::Google.Cloud.Talent.V4Beta1.CandidateAvailabilityFilter.Parser, new[]{ "Negated" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Talent.V4Beta1.PersonNameFilter), global::Google.Cloud.Talent.V4Beta1.PersonNameFilter.Parser, new[]{ "PersonName" }, null, null, null) })); } #endregion } #region Messages /// <summary> /// Input only. /// /// The query required to perform a search query. /// </summary> public sealed partial class JobQuery : pb::IMessage<JobQuery> { private static readonly pb::MessageParser<JobQuery> _parser = new pb::MessageParser<JobQuery>(() => new JobQuery()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<JobQuery> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.Talent.V4Beta1.FiltersReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public JobQuery() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public JobQuery(JobQuery other) : this() { query_ = other.query_; companies_ = other.companies_.Clone(); locationFilters_ = other.locationFilters_.Clone(); jobCategories_ = other.jobCategories_.Clone(); commuteFilter_ = other.commuteFilter_ != null ? other.commuteFilter_.Clone() : null; companyDisplayNames_ = other.companyDisplayNames_.Clone(); compensationFilter_ = other.compensationFilter_ != null ? other.compensationFilter_.Clone() : null; customAttributeFilter_ = other.customAttributeFilter_; disableSpellCheck_ = other.disableSpellCheck_; employmentTypes_ = other.employmentTypes_.Clone(); languageCodes_ = other.languageCodes_.Clone(); publishTimeRange_ = other.publishTimeRange_ != null ? other.publishTimeRange_.Clone() : null; excludedJobs_ = other.excludedJobs_.Clone(); _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public JobQuery Clone() { return new JobQuery(this); } /// <summary>Field number for the "query" field.</summary> public const int QueryFieldNumber = 1; private string query_ = ""; /// <summary> /// Optional. The query string that matches against the job title, description, /// and location fields. /// /// The maximum number of allowed characters is 255. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Query { get { return query_; } set { query_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "companies" field.</summary> public const int CompaniesFieldNumber = 2; private static readonly pb::FieldCodec<string> _repeated_companies_codec = pb::FieldCodec.ForString(18); private readonly pbc::RepeatedField<string> companies_ = new pbc::RepeatedField<string>(); /// <summary> /// Optional. This filter specifies the company entities to search against. /// /// If a value isn't specified, jobs are searched for against all /// companies. /// /// If multiple values are specified, jobs are searched against the /// companies specified. /// /// The format is /// "projects/{project_id}/tenants/{tenant_id}/companies/{company_id}", for /// example, "projects/api-test-project/tenants/foo/companies/bar". /// /// Tenant id is optional and the default tenant is used if unspecified, for /// example, "projects/api-test-project/companies/bar". /// /// At most 20 company filters are allowed. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<string> Companies { get { return companies_; } } /// <summary>Field number for the "location_filters" field.</summary> public const int LocationFiltersFieldNumber = 3; private static readonly pb::FieldCodec<global::Google.Cloud.Talent.V4Beta1.LocationFilter> _repeated_locationFilters_codec = pb::FieldCodec.ForMessage(26, global::Google.Cloud.Talent.V4Beta1.LocationFilter.Parser); private readonly pbc::RepeatedField<global::Google.Cloud.Talent.V4Beta1.LocationFilter> locationFilters_ = new pbc::RepeatedField<global::Google.Cloud.Talent.V4Beta1.LocationFilter>(); /// <summary> /// Optional. The location filter specifies geo-regions containing the jobs to /// search against. See /// [LocationFilter][google.cloud.talent.v4beta1.LocationFilter] for more /// information. /// /// If a location value isn't specified, jobs fitting the other search /// criteria are retrieved regardless of where they're located. /// /// If multiple values are specified, jobs are retrieved from any of the /// specified locations. If different values are specified for the /// [LocationFilter.distance_in_miles][google.cloud.talent.v4beta1.LocationFilter.distance_in_miles] /// parameter, the maximum provided distance is used for all locations. /// /// At most 5 location filters are allowed. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<global::Google.Cloud.Talent.V4Beta1.LocationFilter> LocationFilters { get { return locationFilters_; } } /// <summary>Field number for the "job_categories" field.</summary> public const int JobCategoriesFieldNumber = 4; private static readonly pb::FieldCodec<global::Google.Cloud.Talent.V4Beta1.JobCategory> _repeated_jobCategories_codec = pb::FieldCodec.ForEnum(34, x => (int) x, x => (global::Google.Cloud.Talent.V4Beta1.JobCategory) x); private readonly pbc::RepeatedField<global::Google.Cloud.Talent.V4Beta1.JobCategory> jobCategories_ = new pbc::RepeatedField<global::Google.Cloud.Talent.V4Beta1.JobCategory>(); /// <summary> /// Optional. The category filter specifies the categories of jobs to search /// against. See [JobCategory][google.cloud.talent.v4beta1.JobCategory] for /// more information. /// /// If a value isn't specified, jobs from any category are searched against. /// /// If multiple values are specified, jobs from any of the specified /// categories are searched against. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<global::Google.Cloud.Talent.V4Beta1.JobCategory> JobCategories { get { return jobCategories_; } } /// <summary>Field number for the "commute_filter" field.</summary> public const int CommuteFilterFieldNumber = 5; private global::Google.Cloud.Talent.V4Beta1.CommuteFilter commuteFilter_; /// <summary> /// Optional. Allows filtering jobs by commute time with different travel /// methods (for /// example, driving or public transit). /// /// Note: This only works when you specify a /// [CommuteMethod][google.cloud.talent.v4beta1.CommuteMethod]. In this case, /// [location_filters][google.cloud.talent.v4beta1.JobQuery.location_filters] /// is ignored. /// /// Currently we don't support sorting by commute time. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Cloud.Talent.V4Beta1.CommuteFilter CommuteFilter { get { return commuteFilter_; } set { commuteFilter_ = value; } } /// <summary>Field number for the "company_display_names" field.</summary> public const int CompanyDisplayNamesFieldNumber = 6; private static readonly pb::FieldCodec<string> _repeated_companyDisplayNames_codec = pb::FieldCodec.ForString(50); private readonly pbc::RepeatedField<string> companyDisplayNames_ = new pbc::RepeatedField<string>(); /// <summary> /// Optional. This filter specifies the exact company /// [Company.display_name][google.cloud.talent.v4beta1.Company.display_name] of /// the jobs to search against. /// /// If a value isn't specified, jobs within the search results are /// associated with any company. /// /// If multiple values are specified, jobs within the search results may be /// associated with any of the specified companies. /// /// At most 20 company display name filters are allowed. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<string> CompanyDisplayNames { get { return companyDisplayNames_; } } /// <summary>Field number for the "compensation_filter" field.</summary> public const int CompensationFilterFieldNumber = 7; private global::Google.Cloud.Talent.V4Beta1.CompensationFilter compensationFilter_; /// <summary> /// Optional. This search filter is applied only to /// [Job.compensation_info][google.cloud.talent.v4beta1.Job.compensation_info]. /// For example, if the filter is specified as "Hourly job with per-hour /// compensation > $15", only jobs meeting these criteria are searched. If a /// filter isn't defined, all open jobs are searched. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Cloud.Talent.V4Beta1.CompensationFilter CompensationFilter { get { return compensationFilter_; } set { compensationFilter_ = value; } } /// <summary>Field number for the "custom_attribute_filter" field.</summary> public const int CustomAttributeFilterFieldNumber = 8; private string customAttributeFilter_ = ""; /// <summary> /// Optional. This filter specifies a structured syntax to match against the /// [Job.custom_attributes][google.cloud.talent.v4beta1.Job.custom_attributes] /// marked as `filterable`. /// /// The syntax for this expression is a subset of SQL syntax. /// /// Supported operators are: `=`, `!=`, `&lt;`, `&lt;=`, `>`, and `>=` where the /// left of the operator is a custom field key and the right of the operator /// is a number or a quoted string. You must escape backslash (\\) and /// quote (\") characters. /// /// Supported functions are `LOWER([field_name])` to /// perform a case insensitive match and `EMPTY([field_name])` to filter on the /// existence of a key. /// /// Boolean expressions (AND/OR/NOT) are supported up to 3 levels of /// nesting (for example, "((A AND B AND C) OR NOT D) AND E"), a maximum of 100 /// comparisons or functions are allowed in the expression. The expression /// must be &lt; 6000 bytes in length. /// /// Sample Query: /// `(LOWER(driving_license)="class \"a\"" OR EMPTY(driving_license)) AND /// driving_years > 10` /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string CustomAttributeFilter { get { return customAttributeFilter_; } set { customAttributeFilter_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "disable_spell_check" field.</summary> public const int DisableSpellCheckFieldNumber = 9; private bool disableSpellCheck_; /// <summary> /// Optional. This flag controls the spell-check feature. If false, the /// service attempts to correct a misspelled query, /// for example, "enginee" is corrected to "engineer". /// /// Defaults to false: a spell check is performed. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool DisableSpellCheck { get { return disableSpellCheck_; } set { disableSpellCheck_ = value; } } /// <summary>Field number for the "employment_types" field.</summary> public const int EmploymentTypesFieldNumber = 10; private static readonly pb::FieldCodec<global::Google.Cloud.Talent.V4Beta1.EmploymentType> _repeated_employmentTypes_codec = pb::FieldCodec.ForEnum(82, x => (int) x, x => (global::Google.Cloud.Talent.V4Beta1.EmploymentType) x); private readonly pbc::RepeatedField<global::Google.Cloud.Talent.V4Beta1.EmploymentType> employmentTypes_ = new pbc::RepeatedField<global::Google.Cloud.Talent.V4Beta1.EmploymentType>(); /// <summary> /// Optional. The employment type filter specifies the employment type of jobs /// to search against, such as /// [EmploymentType.FULL_TIME][google.cloud.talent.v4beta1.EmploymentType.FULL_TIME]. /// /// If a value isn't specified, jobs in the search results includes any /// employment type. /// /// If multiple values are specified, jobs in the search results include /// any of the specified employment types. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<global::Google.Cloud.Talent.V4Beta1.EmploymentType> EmploymentTypes { get { return employmentTypes_; } } /// <summary>Field number for the "language_codes" field.</summary> public const int LanguageCodesFieldNumber = 11; private static readonly pb::FieldCodec<string> _repeated_languageCodes_codec = pb::FieldCodec.ForString(90); private readonly pbc::RepeatedField<string> languageCodes_ = new pbc::RepeatedField<string>(); /// <summary> /// Optional. This filter specifies the locale of jobs to search against, /// for example, "en-US". /// /// If a value isn't specified, the search results can contain jobs in any /// locale. /// /// Language codes should be in BCP-47 format, such as "en-US" or "sr-Latn". /// For more information, see /// [Tags for Identifying Languages](https://tools.ietf.org/html/bcp47). /// /// At most 10 language code filters are allowed. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<string> LanguageCodes { get { return languageCodes_; } } /// <summary>Field number for the "publish_time_range" field.</summary> public const int PublishTimeRangeFieldNumber = 12; private global::Google.Cloud.Talent.V4Beta1.TimestampRange publishTimeRange_; /// <summary> /// Optional. Jobs published within a range specified by this filter are /// searched against. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Cloud.Talent.V4Beta1.TimestampRange PublishTimeRange { get { return publishTimeRange_; } set { publishTimeRange_ = value; } } /// <summary>Field number for the "excluded_jobs" field.</summary> public const int ExcludedJobsFieldNumber = 13; private static readonly pb::FieldCodec<string> _repeated_excludedJobs_codec = pb::FieldCodec.ForString(106); private readonly pbc::RepeatedField<string> excludedJobs_ = new pbc::RepeatedField<string>(); /// <summary> /// Optional. This filter specifies a list of job names to be excluded during /// search. /// /// At most 400 excluded job names are allowed. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<string> ExcludedJobs { get { return excludedJobs_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as JobQuery); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(JobQuery other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Query != other.Query) return false; if(!companies_.Equals(other.companies_)) return false; if(!locationFilters_.Equals(other.locationFilters_)) return false; if(!jobCategories_.Equals(other.jobCategories_)) return false; if (!object.Equals(CommuteFilter, other.CommuteFilter)) return false; if(!companyDisplayNames_.Equals(other.companyDisplayNames_)) return false; if (!object.Equals(CompensationFilter, other.CompensationFilter)) return false; if (CustomAttributeFilter != other.CustomAttributeFilter) return false; if (DisableSpellCheck != other.DisableSpellCheck) return false; if(!employmentTypes_.Equals(other.employmentTypes_)) return false; if(!languageCodes_.Equals(other.languageCodes_)) return false; if (!object.Equals(PublishTimeRange, other.PublishTimeRange)) return false; if(!excludedJobs_.Equals(other.excludedJobs_)) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Query.Length != 0) hash ^= Query.GetHashCode(); hash ^= companies_.GetHashCode(); hash ^= locationFilters_.GetHashCode(); hash ^= jobCategories_.GetHashCode(); if (commuteFilter_ != null) hash ^= CommuteFilter.GetHashCode(); hash ^= companyDisplayNames_.GetHashCode(); if (compensationFilter_ != null) hash ^= CompensationFilter.GetHashCode(); if (CustomAttributeFilter.Length != 0) hash ^= CustomAttributeFilter.GetHashCode(); if (DisableSpellCheck != false) hash ^= DisableSpellCheck.GetHashCode(); hash ^= employmentTypes_.GetHashCode(); hash ^= languageCodes_.GetHashCode(); if (publishTimeRange_ != null) hash ^= PublishTimeRange.GetHashCode(); hash ^= excludedJobs_.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Query.Length != 0) { output.WriteRawTag(10); output.WriteString(Query); } companies_.WriteTo(output, _repeated_companies_codec); locationFilters_.WriteTo(output, _repeated_locationFilters_codec); jobCategories_.WriteTo(output, _repeated_jobCategories_codec); if (commuteFilter_ != null) { output.WriteRawTag(42); output.WriteMessage(CommuteFilter); } companyDisplayNames_.WriteTo(output, _repeated_companyDisplayNames_codec); if (compensationFilter_ != null) { output.WriteRawTag(58); output.WriteMessage(CompensationFilter); } if (CustomAttributeFilter.Length != 0) { output.WriteRawTag(66); output.WriteString(CustomAttributeFilter); } if (DisableSpellCheck != false) { output.WriteRawTag(72); output.WriteBool(DisableSpellCheck); } employmentTypes_.WriteTo(output, _repeated_employmentTypes_codec); languageCodes_.WriteTo(output, _repeated_languageCodes_codec); if (publishTimeRange_ != null) { output.WriteRawTag(98); output.WriteMessage(PublishTimeRange); } excludedJobs_.WriteTo(output, _repeated_excludedJobs_codec); if (_unknownFields != null) { _unknownFields.WriteTo(output); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Query.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Query); } size += companies_.CalculateSize(_repeated_companies_codec); size += locationFilters_.CalculateSize(_repeated_locationFilters_codec); size += jobCategories_.CalculateSize(_repeated_jobCategories_codec); if (commuteFilter_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(CommuteFilter); } size += companyDisplayNames_.CalculateSize(_repeated_companyDisplayNames_codec); if (compensationFilter_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(CompensationFilter); } if (CustomAttributeFilter.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(CustomAttributeFilter); } if (DisableSpellCheck != false) { size += 1 + 1; } size += employmentTypes_.CalculateSize(_repeated_employmentTypes_codec); size += languageCodes_.CalculateSize(_repeated_languageCodes_codec); if (publishTimeRange_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(PublishTimeRange); } size += excludedJobs_.CalculateSize(_repeated_excludedJobs_codec); if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(JobQuery other) { if (other == null) { return; } if (other.Query.Length != 0) { Query = other.Query; } companies_.Add(other.companies_); locationFilters_.Add(other.locationFilters_); jobCategories_.Add(other.jobCategories_); if (other.commuteFilter_ != null) { if (commuteFilter_ == null) { CommuteFilter = new global::Google.Cloud.Talent.V4Beta1.CommuteFilter(); } CommuteFilter.MergeFrom(other.CommuteFilter); } companyDisplayNames_.Add(other.companyDisplayNames_); if (other.compensationFilter_ != null) { if (compensationFilter_ == null) { CompensationFilter = new global::Google.Cloud.Talent.V4Beta1.CompensationFilter(); } CompensationFilter.MergeFrom(other.CompensationFilter); } if (other.CustomAttributeFilter.Length != 0) { CustomAttributeFilter = other.CustomAttributeFilter; } if (other.DisableSpellCheck != false) { DisableSpellCheck = other.DisableSpellCheck; } employmentTypes_.Add(other.employmentTypes_); languageCodes_.Add(other.languageCodes_); if (other.publishTimeRange_ != null) { if (publishTimeRange_ == null) { PublishTimeRange = new global::Google.Cloud.Talent.V4Beta1.TimestampRange(); } PublishTimeRange.MergeFrom(other.PublishTimeRange); } excludedJobs_.Add(other.excludedJobs_); _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 10: { Query = input.ReadString(); break; } case 18: { companies_.AddEntriesFrom(input, _repeated_companies_codec); break; } case 26: { locationFilters_.AddEntriesFrom(input, _repeated_locationFilters_codec); break; } case 34: case 32: { jobCategories_.AddEntriesFrom(input, _repeated_jobCategories_codec); break; } case 42: { if (commuteFilter_ == null) { CommuteFilter = new global::Google.Cloud.Talent.V4Beta1.CommuteFilter(); } input.ReadMessage(CommuteFilter); break; } case 50: { companyDisplayNames_.AddEntriesFrom(input, _repeated_companyDisplayNames_codec); break; } case 58: { if (compensationFilter_ == null) { CompensationFilter = new global::Google.Cloud.Talent.V4Beta1.CompensationFilter(); } input.ReadMessage(CompensationFilter); break; } case 66: { CustomAttributeFilter = input.ReadString(); break; } case 72: { DisableSpellCheck = input.ReadBool(); break; } case 82: case 80: { employmentTypes_.AddEntriesFrom(input, _repeated_employmentTypes_codec); break; } case 90: { languageCodes_.AddEntriesFrom(input, _repeated_languageCodes_codec); break; } case 98: { if (publishTimeRange_ == null) { PublishTimeRange = new global::Google.Cloud.Talent.V4Beta1.TimestampRange(); } input.ReadMessage(PublishTimeRange); break; } case 106: { excludedJobs_.AddEntriesFrom(input, _repeated_excludedJobs_codec); break; } } } } } /// <summary> /// Filters to apply when performing the search query. /// </summary> public sealed partial class ProfileQuery : pb::IMessage<ProfileQuery> { private static readonly pb::MessageParser<ProfileQuery> _parser = new pb::MessageParser<ProfileQuery>(() => new ProfileQuery()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<ProfileQuery> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.Talent.V4Beta1.FiltersReflection.Descriptor.MessageTypes[1]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ProfileQuery() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ProfileQuery(ProfileQuery other) : this() { query_ = other.query_; locationFilters_ = other.locationFilters_.Clone(); jobTitleFilters_ = other.jobTitleFilters_.Clone(); employerFilters_ = other.employerFilters_.Clone(); educationFilters_ = other.educationFilters_.Clone(); skillFilters_ = other.skillFilters_.Clone(); workExperienceFilter_ = other.workExperienceFilter_.Clone(); timeFilters_ = other.timeFilters_.Clone(); HirableFilter = other.HirableFilter; applicationDateFilters_ = other.applicationDateFilters_.Clone(); applicationOutcomeNotesFilters_ = other.applicationOutcomeNotesFilters_.Clone(); applicationJobFilters_ = other.applicationJobFilters_.Clone(); customAttributeFilter_ = other.customAttributeFilter_; candidateAvailabilityFilter_ = other.candidateAvailabilityFilter_ != null ? other.candidateAvailabilityFilter_.Clone() : null; personNameFilters_ = other.personNameFilters_.Clone(); _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ProfileQuery Clone() { return new ProfileQuery(this); } /// <summary>Field number for the "query" field.</summary> public const int QueryFieldNumber = 1; private string query_ = ""; /// <summary> /// Optional. Keywords to match any text fields of profiles. /// /// For example, "software engineer in Palo Alto". /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Query { get { return query_; } set { query_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "location_filters" field.</summary> public const int LocationFiltersFieldNumber = 2; private static readonly pb::FieldCodec<global::Google.Cloud.Talent.V4Beta1.LocationFilter> _repeated_locationFilters_codec = pb::FieldCodec.ForMessage(18, global::Google.Cloud.Talent.V4Beta1.LocationFilter.Parser); private readonly pbc::RepeatedField<global::Google.Cloud.Talent.V4Beta1.LocationFilter> locationFilters_ = new pbc::RepeatedField<global::Google.Cloud.Talent.V4Beta1.LocationFilter>(); /// <summary> /// Optional. The location filter specifies geo-regions containing the profiles /// to search against. /// /// One of /// [LocationFilter.address][google.cloud.talent.v4beta1.LocationFilter.address] /// or /// [LocationFilter.lat_lng][google.cloud.talent.v4beta1.LocationFilter.lat_lng] /// must be provided or an error is thrown. If both /// [LocationFilter.address][google.cloud.talent.v4beta1.LocationFilter.address] /// and /// [LocationFilter.lat_lng][google.cloud.talent.v4beta1.LocationFilter.lat_lng] /// are provided, an error is thrown. /// /// The following logic is used to determine which locations in /// the profile to filter against: /// 1. All of the profile's geocoded /// [Profile.addresses][google.cloud.talent.v4beta1.Profile.addresses] where /// [Address.usage][google.cloud.talent.v4beta1.Address.usage] is PERSONAL and /// [Address.current][google.cloud.talent.v4beta1.Address.current] is true. /// 2. If the above set of locations is empty, all of the profile's geocoded /// [Profile.addresses][google.cloud.talent.v4beta1.Profile.addresses] where /// [Address.usage][google.cloud.talent.v4beta1.Address.usage] is /// CONTACT_INFO_USAGE_UNSPECIFIED and /// [Address.current][google.cloud.talent.v4beta1.Address.current] is true. /// 3. If the above set of locations is empty, all of the profile's geocoded /// [Profile.addresses][google.cloud.talent.v4beta1.Profile.addresses] where /// [Address.usage][google.cloud.talent.v4beta1.Address.usage] is PERSONAL or /// CONTACT_INFO_USAGE_UNSPECIFIED and /// [Address.current][google.cloud.talent.v4beta1.Address.current] is not set. /// /// This means that any profiles without any /// [Profile.addresses][google.cloud.talent.v4beta1.Profile.addresses] that /// match any of the above criteria will not be included in a search with /// location filter. Furthermore, any /// [Profile.addresses][google.cloud.talent.v4beta1.Profile.addresses] where /// [Address.usage][google.cloud.talent.v4beta1.Address.usage] is WORK or /// SCHOOL or where /// [Address.current][google.cloud.talent.v4beta1.Address.current] is false are /// not considered for location filter. /// /// If a location filter isn't specified, profiles fitting the other search /// criteria are retrieved regardless of where they're located. /// /// If /// [LocationFilter.negated][google.cloud.talent.v4beta1.LocationFilter.negated] /// is specified, the result doesn't contain profiles from that location. /// /// If /// [LocationFilter.address][google.cloud.talent.v4beta1.LocationFilter.address] /// is provided, the /// [LocationType][google.cloud.talent.v4beta1.Location.LocationType], center /// point (latitude and longitude), and radius are automatically detected by /// the Google Maps Geocoding API and included as well. If /// [LocationFilter.address][google.cloud.talent.v4beta1.LocationFilter.address] /// cannot be geocoded, the filter falls back to keyword search. /// /// If the detected /// [LocationType][google.cloud.talent.v4beta1.Location.LocationType] is /// [LocationType.SUB_ADMINISTRATIVE_AREA][google.cloud.talent.v4beta1.Location.LocationType.SUB_ADMINISTRATIVE_AREA], /// [LocationType.ADMINISTRATIVE_AREA][google.cloud.talent.v4beta1.Location.LocationType.ADMINISTRATIVE_AREA], /// or /// [LocationType.COUNTRY][google.cloud.talent.v4beta1.Location.LocationType.COUNTRY], /// the filter is performed against the detected location name (using exact /// text matching). Otherwise, the filter is performed against the detected /// center point and a radius of detected location radius + /// [LocationFilter.distance_in_miles][google.cloud.talent.v4beta1.LocationFilter.distance_in_miles]. /// /// If /// [LocationFilter.address][google.cloud.talent.v4beta1.LocationFilter.address] /// is provided, /// [LocationFilter.distance_in_miles][google.cloud.talent.v4beta1.LocationFilter.distance_in_miles] /// is the additional radius on top of the radius of the location geocoded from /// [LocationFilter.address][google.cloud.talent.v4beta1.LocationFilter.address]. /// If /// [LocationFilter.lat_lng][google.cloud.talent.v4beta1.LocationFilter.lat_lng] /// is provided, /// [LocationFilter.distance_in_miles][google.cloud.talent.v4beta1.LocationFilter.distance_in_miles] /// is the only radius that is used. /// /// [LocationFilter.distance_in_miles][google.cloud.talent.v4beta1.LocationFilter.distance_in_miles] /// is 10 by default. Note that the value of /// [LocationFilter.distance_in_miles][google.cloud.talent.v4beta1.LocationFilter.distance_in_miles] /// is 0 if it is unset, so the server does not differentiate /// [LocationFilter.distance_in_miles][google.cloud.talent.v4beta1.LocationFilter.distance_in_miles] /// that is explicitly set to 0 and /// [LocationFilter.distance_in_miles][google.cloud.talent.v4beta1.LocationFilter.distance_in_miles] /// that is not set. Which means that if /// [LocationFilter.distance_in_miles][google.cloud.talent.v4beta1.LocationFilter.distance_in_miles] /// is explicitly set to 0, the server will use the default value of /// [LocationFilter.distance_in_miles][google.cloud.talent.v4beta1.LocationFilter.distance_in_miles] /// which is 10. To work around this and effectively set /// [LocationFilter.distance_in_miles][google.cloud.talent.v4beta1.LocationFilter.distance_in_miles] /// to 0, we recommend setting /// [LocationFilter.distance_in_miles][google.cloud.talent.v4beta1.LocationFilter.distance_in_miles] /// to a very small decimal number (such as 0.00001). /// /// If /// [LocationFilter.distance_in_miles][google.cloud.talent.v4beta1.LocationFilter.distance_in_miles] /// is negative, an error is thrown. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<global::Google.Cloud.Talent.V4Beta1.LocationFilter> LocationFilters { get { return locationFilters_; } } /// <summary>Field number for the "job_title_filters" field.</summary> public const int JobTitleFiltersFieldNumber = 3; private static readonly pb::FieldCodec<global::Google.Cloud.Talent.V4Beta1.JobTitleFilter> _repeated_jobTitleFilters_codec = pb::FieldCodec.ForMessage(26, global::Google.Cloud.Talent.V4Beta1.JobTitleFilter.Parser); private readonly pbc::RepeatedField<global::Google.Cloud.Talent.V4Beta1.JobTitleFilter> jobTitleFilters_ = new pbc::RepeatedField<global::Google.Cloud.Talent.V4Beta1.JobTitleFilter>(); /// <summary> /// Optional. Job title filter specifies job titles of profiles to match on. /// /// If a job title isn't specified, profiles with any titles are retrieved. /// /// If multiple values are specified, profiles are retrieved with any of the /// specified job titles. /// /// If /// [JobTitleFilter.negated][google.cloud.talent.v4beta1.JobTitleFilter.negated] /// is specified, the result won't contain profiles with the job titles. /// /// For example, search for profiles with a job title "Product Manager". /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<global::Google.Cloud.Talent.V4Beta1.JobTitleFilter> JobTitleFilters { get { return jobTitleFilters_; } } /// <summary>Field number for the "employer_filters" field.</summary> public const int EmployerFiltersFieldNumber = 4; private static readonly pb::FieldCodec<global::Google.Cloud.Talent.V4Beta1.EmployerFilter> _repeated_employerFilters_codec = pb::FieldCodec.ForMessage(34, global::Google.Cloud.Talent.V4Beta1.EmployerFilter.Parser); private readonly pbc::RepeatedField<global::Google.Cloud.Talent.V4Beta1.EmployerFilter> employerFilters_ = new pbc::RepeatedField<global::Google.Cloud.Talent.V4Beta1.EmployerFilter>(); /// <summary> /// Optional. Employer filter specifies employers of profiles to match on. /// /// If an employer filter isn't specified, profiles with any employers are /// retrieved. /// /// If multiple employer filters are specified, profiles with any matching /// employers are retrieved. /// /// If /// [EmployerFilter.negated][google.cloud.talent.v4beta1.EmployerFilter.negated] /// is specified, the result won't contain profiles that match the employers. /// /// For example, search for profiles that have working experience at "Google /// LLC". /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<global::Google.Cloud.Talent.V4Beta1.EmployerFilter> EmployerFilters { get { return employerFilters_; } } /// <summary>Field number for the "education_filters" field.</summary> public const int EducationFiltersFieldNumber = 5; private static readonly pb::FieldCodec<global::Google.Cloud.Talent.V4Beta1.EducationFilter> _repeated_educationFilters_codec = pb::FieldCodec.ForMessage(42, global::Google.Cloud.Talent.V4Beta1.EducationFilter.Parser); private readonly pbc::RepeatedField<global::Google.Cloud.Talent.V4Beta1.EducationFilter> educationFilters_ = new pbc::RepeatedField<global::Google.Cloud.Talent.V4Beta1.EducationFilter>(); /// <summary> /// Optional. Education filter specifies education of profiles to match on. /// /// If an education filter isn't specified, profiles with any education are /// retrieved. /// /// If multiple education filters are specified, profiles that match any /// education filters are retrieved. /// /// If /// [EducationFilter.negated][google.cloud.talent.v4beta1.EducationFilter.negated] /// is specified, the result won't contain profiles that match the educations. /// /// For example, search for profiles with a master degree. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<global::Google.Cloud.Talent.V4Beta1.EducationFilter> EducationFilters { get { return educationFilters_; } } /// <summary>Field number for the "skill_filters" field.</summary> public const int SkillFiltersFieldNumber = 6; private static readonly pb::FieldCodec<global::Google.Cloud.Talent.V4Beta1.SkillFilter> _repeated_skillFilters_codec = pb::FieldCodec.ForMessage(50, global::Google.Cloud.Talent.V4Beta1.SkillFilter.Parser); private readonly pbc::RepeatedField<global::Google.Cloud.Talent.V4Beta1.SkillFilter> skillFilters_ = new pbc::RepeatedField<global::Google.Cloud.Talent.V4Beta1.SkillFilter>(); /// <summary> /// Optional. Skill filter specifies skill of profiles to match on. /// /// If a skill filter isn't specified, profiles with any skills are retrieved. /// /// If multiple skill filters are specified, profiles that match any skill /// filters are retrieved. /// /// If [SkillFilter.negated][google.cloud.talent.v4beta1.SkillFilter.negated] /// is specified, the result won't contain profiles that match the skills. /// /// For example, search for profiles that have "Java" and "Python" in skill /// list. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<global::Google.Cloud.Talent.V4Beta1.SkillFilter> SkillFilters { get { return skillFilters_; } } /// <summary>Field number for the "work_experience_filter" field.</summary> public const int WorkExperienceFilterFieldNumber = 7; private static readonly pb::FieldCodec<global::Google.Cloud.Talent.V4Beta1.WorkExperienceFilter> _repeated_workExperienceFilter_codec = pb::FieldCodec.ForMessage(58, global::Google.Cloud.Talent.V4Beta1.WorkExperienceFilter.Parser); private readonly pbc::RepeatedField<global::Google.Cloud.Talent.V4Beta1.WorkExperienceFilter> workExperienceFilter_ = new pbc::RepeatedField<global::Google.Cloud.Talent.V4Beta1.WorkExperienceFilter>(); /// <summary> /// Optional. Work experience filter specifies the total working experience of /// profiles to match on. /// /// If a work experience filter isn't specified, profiles with any /// professional experience are retrieved. /// /// If multiple work experience filters are specified, profiles that match any /// work experience filters are retrieved. /// /// For example, search for profiles with 10 years of work experience. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<global::Google.Cloud.Talent.V4Beta1.WorkExperienceFilter> WorkExperienceFilter { get { return workExperienceFilter_; } } /// <summary>Field number for the "time_filters" field.</summary> public const int TimeFiltersFieldNumber = 8; private static readonly pb::FieldCodec<global::Google.Cloud.Talent.V4Beta1.TimeFilter> _repeated_timeFilters_codec = pb::FieldCodec.ForMessage(66, global::Google.Cloud.Talent.V4Beta1.TimeFilter.Parser); private readonly pbc::RepeatedField<global::Google.Cloud.Talent.V4Beta1.TimeFilter> timeFilters_ = new pbc::RepeatedField<global::Google.Cloud.Talent.V4Beta1.TimeFilter>(); /// <summary> /// Optional. Time filter specifies the create/update timestamp of the profiles /// to match on. /// /// For example, search for profiles created since "2018-1-1". /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<global::Google.Cloud.Talent.V4Beta1.TimeFilter> TimeFilters { get { return timeFilters_; } } /// <summary>Field number for the "hirable_filter" field.</summary> public const int HirableFilterFieldNumber = 9; private static readonly pb::FieldCodec<bool?> _single_hirableFilter_codec = pb::FieldCodec.ForStructWrapper<bool>(74); private bool? hirableFilter_; /// <summary> /// Optional. The hirable filter specifies the profile's hirable status to /// match on. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool? HirableFilter { get { return hirableFilter_; } set { hirableFilter_ = value; } } /// <summary>Field number for the "application_date_filters" field.</summary> public const int ApplicationDateFiltersFieldNumber = 10; private static readonly pb::FieldCodec<global::Google.Cloud.Talent.V4Beta1.ApplicationDateFilter> _repeated_applicationDateFilters_codec = pb::FieldCodec.ForMessage(82, global::Google.Cloud.Talent.V4Beta1.ApplicationDateFilter.Parser); private readonly pbc::RepeatedField<global::Google.Cloud.Talent.V4Beta1.ApplicationDateFilter> applicationDateFilters_ = new pbc::RepeatedField<global::Google.Cloud.Talent.V4Beta1.ApplicationDateFilter>(); /// <summary> /// Optional. The application date filters specify application date ranges to /// match on. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<global::Google.Cloud.Talent.V4Beta1.ApplicationDateFilter> ApplicationDateFilters { get { return applicationDateFilters_; } } /// <summary>Field number for the "application_outcome_notes_filters" field.</summary> public const int ApplicationOutcomeNotesFiltersFieldNumber = 11; private static readonly pb::FieldCodec<global::Google.Cloud.Talent.V4Beta1.ApplicationOutcomeNotesFilter> _repeated_applicationOutcomeNotesFilters_codec = pb::FieldCodec.ForMessage(90, global::Google.Cloud.Talent.V4Beta1.ApplicationOutcomeNotesFilter.Parser); private readonly pbc::RepeatedField<global::Google.Cloud.Talent.V4Beta1.ApplicationOutcomeNotesFilter> applicationOutcomeNotesFilters_ = new pbc::RepeatedField<global::Google.Cloud.Talent.V4Beta1.ApplicationOutcomeNotesFilter>(); /// <summary> /// Optional. The application outcome notes filters specify the notes for the /// outcome of the job application. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<global::Google.Cloud.Talent.V4Beta1.ApplicationOutcomeNotesFilter> ApplicationOutcomeNotesFilters { get { return applicationOutcomeNotesFilters_; } } /// <summary>Field number for the "application_job_filters" field.</summary> public const int ApplicationJobFiltersFieldNumber = 13; private static readonly pb::FieldCodec<global::Google.Cloud.Talent.V4Beta1.ApplicationJobFilter> _repeated_applicationJobFilters_codec = pb::FieldCodec.ForMessage(106, global::Google.Cloud.Talent.V4Beta1.ApplicationJobFilter.Parser); private readonly pbc::RepeatedField<global::Google.Cloud.Talent.V4Beta1.ApplicationJobFilter> applicationJobFilters_ = new pbc::RepeatedField<global::Google.Cloud.Talent.V4Beta1.ApplicationJobFilter>(); /// <summary> /// Optional. The application job filters specify the job applied for in the /// application. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<global::Google.Cloud.Talent.V4Beta1.ApplicationJobFilter> ApplicationJobFilters { get { return applicationJobFilters_; } } /// <summary>Field number for the "custom_attribute_filter" field.</summary> public const int CustomAttributeFilterFieldNumber = 15; private string customAttributeFilter_ = ""; /// <summary> /// Optional. This filter specifies a structured syntax to match against the /// [Profile.custom_attributes][google.cloud.talent.v4beta1.Profile.custom_attributes] /// that are marked as `filterable`. /// /// The syntax for this expression is a subset of Google SQL syntax. /// /// String custom attributes: supported operators are =, != where the left of /// the operator is a custom field key and the right of the operator is a /// string (surrounded by quotes) value. /// /// Numeric custom attributes: Supported operators are '>', '&lt;' or '=' /// operators where the left of the operator is a custom field key and the /// right of the operator is a numeric value. /// /// Supported functions are LOWER(&lt;field_name>) to /// perform case insensitive match and EMPTY(&lt;field_name>) to filter on the /// existence of a key. /// /// Boolean expressions (AND/OR/NOT) are supported up to 3 levels of /// nesting (for example "((A AND B AND C) OR NOT D) AND E"), and there can be /// a maximum of 50 comparisons/functions in the expression. The expression /// must be &lt; 2000 characters in length. /// /// Sample Query: /// (key1 = "TEST" OR LOWER(key1)="test" OR NOT EMPTY(key1)) /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string CustomAttributeFilter { get { return customAttributeFilter_; } set { customAttributeFilter_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "candidate_availability_filter" field.</summary> public const int CandidateAvailabilityFilterFieldNumber = 16; private global::Google.Cloud.Talent.V4Beta1.CandidateAvailabilityFilter candidateAvailabilityFilter_; /// <summary> /// Optional. The candidate availability filter which filters based on /// availability signals. /// /// Signal 1: Number of days since most recent job application. See /// [Availability.JobApplicationAvailabilitySignal][google.cloud.talent.v4beta1.Availability.JobApplicationAvailabilitySignal] /// for the details of this signal. /// /// Signal 2: Number of days since last profile update. See /// [Availability.ProfileUpdateAvailabilitySignal][google.cloud.talent.v4beta1.Availability.ProfileUpdateAvailabilitySignal] /// for the details of this signal. /// /// The candidate availability filter helps a recruiter understand if a /// specific candidate is likely to be actively seeking new job opportunities /// based on an aggregated set of signals. Specifically, the intent is NOT to /// indicate the candidate's potential qualification / interest / close ability /// for a specific job. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Cloud.Talent.V4Beta1.CandidateAvailabilityFilter CandidateAvailabilityFilter { get { return candidateAvailabilityFilter_; } set { candidateAvailabilityFilter_ = value; } } /// <summary>Field number for the "person_name_filters" field.</summary> public const int PersonNameFiltersFieldNumber = 17; private static readonly pb::FieldCodec<global::Google.Cloud.Talent.V4Beta1.PersonNameFilter> _repeated_personNameFilters_codec = pb::FieldCodec.ForMessage(138, global::Google.Cloud.Talent.V4Beta1.PersonNameFilter.Parser); private readonly pbc::RepeatedField<global::Google.Cloud.Talent.V4Beta1.PersonNameFilter> personNameFilters_ = new pbc::RepeatedField<global::Google.Cloud.Talent.V4Beta1.PersonNameFilter>(); /// <summary> /// Optional. Person name filter specifies person name of profiles to match on. /// /// If multiple person name filters are specified, profiles that match any /// person name filters are retrieved. /// /// For example, search for profiles of candidates with name "John Smith". /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<global::Google.Cloud.Talent.V4Beta1.PersonNameFilter> PersonNameFilters { get { return personNameFilters_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as ProfileQuery); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(ProfileQuery other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Query != other.Query) return false; if(!locationFilters_.Equals(other.locationFilters_)) return false; if(!jobTitleFilters_.Equals(other.jobTitleFilters_)) return false; if(!employerFilters_.Equals(other.employerFilters_)) return false; if(!educationFilters_.Equals(other.educationFilters_)) return false; if(!skillFilters_.Equals(other.skillFilters_)) return false; if(!workExperienceFilter_.Equals(other.workExperienceFilter_)) return false; if(!timeFilters_.Equals(other.timeFilters_)) return false; if (HirableFilter != other.HirableFilter) return false; if(!applicationDateFilters_.Equals(other.applicationDateFilters_)) return false; if(!applicationOutcomeNotesFilters_.Equals(other.applicationOutcomeNotesFilters_)) return false; if(!applicationJobFilters_.Equals(other.applicationJobFilters_)) return false; if (CustomAttributeFilter != other.CustomAttributeFilter) return false; if (!object.Equals(CandidateAvailabilityFilter, other.CandidateAvailabilityFilter)) return false; if(!personNameFilters_.Equals(other.personNameFilters_)) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Query.Length != 0) hash ^= Query.GetHashCode(); hash ^= locationFilters_.GetHashCode(); hash ^= jobTitleFilters_.GetHashCode(); hash ^= employerFilters_.GetHashCode(); hash ^= educationFilters_.GetHashCode(); hash ^= skillFilters_.GetHashCode(); hash ^= workExperienceFilter_.GetHashCode(); hash ^= timeFilters_.GetHashCode(); if (hirableFilter_ != null) hash ^= HirableFilter.GetHashCode(); hash ^= applicationDateFilters_.GetHashCode(); hash ^= applicationOutcomeNotesFilters_.GetHashCode(); hash ^= applicationJobFilters_.GetHashCode(); if (CustomAttributeFilter.Length != 0) hash ^= CustomAttributeFilter.GetHashCode(); if (candidateAvailabilityFilter_ != null) hash ^= CandidateAvailabilityFilter.GetHashCode(); hash ^= personNameFilters_.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Query.Length != 0) { output.WriteRawTag(10); output.WriteString(Query); } locationFilters_.WriteTo(output, _repeated_locationFilters_codec); jobTitleFilters_.WriteTo(output, _repeated_jobTitleFilters_codec); employerFilters_.WriteTo(output, _repeated_employerFilters_codec); educationFilters_.WriteTo(output, _repeated_educationFilters_codec); skillFilters_.WriteTo(output, _repeated_skillFilters_codec); workExperienceFilter_.WriteTo(output, _repeated_workExperienceFilter_codec); timeFilters_.WriteTo(output, _repeated_timeFilters_codec); if (hirableFilter_ != null) { _single_hirableFilter_codec.WriteTagAndValue(output, HirableFilter); } applicationDateFilters_.WriteTo(output, _repeated_applicationDateFilters_codec); applicationOutcomeNotesFilters_.WriteTo(output, _repeated_applicationOutcomeNotesFilters_codec); applicationJobFilters_.WriteTo(output, _repeated_applicationJobFilters_codec); if (CustomAttributeFilter.Length != 0) { output.WriteRawTag(122); output.WriteString(CustomAttributeFilter); } if (candidateAvailabilityFilter_ != null) { output.WriteRawTag(130, 1); output.WriteMessage(CandidateAvailabilityFilter); } personNameFilters_.WriteTo(output, _repeated_personNameFilters_codec); if (_unknownFields != null) { _unknownFields.WriteTo(output); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Query.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Query); } size += locationFilters_.CalculateSize(_repeated_locationFilters_codec); size += jobTitleFilters_.CalculateSize(_repeated_jobTitleFilters_codec); size += employerFilters_.CalculateSize(_repeated_employerFilters_codec); size += educationFilters_.CalculateSize(_repeated_educationFilters_codec); size += skillFilters_.CalculateSize(_repeated_skillFilters_codec); size += workExperienceFilter_.CalculateSize(_repeated_workExperienceFilter_codec); size += timeFilters_.CalculateSize(_repeated_timeFilters_codec); if (hirableFilter_ != null) { size += _single_hirableFilter_codec.CalculateSizeWithTag(HirableFilter); } size += applicationDateFilters_.CalculateSize(_repeated_applicationDateFilters_codec); size += applicationOutcomeNotesFilters_.CalculateSize(_repeated_applicationOutcomeNotesFilters_codec); size += applicationJobFilters_.CalculateSize(_repeated_applicationJobFilters_codec); if (CustomAttributeFilter.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(CustomAttributeFilter); } if (candidateAvailabilityFilter_ != null) { size += 2 + pb::CodedOutputStream.ComputeMessageSize(CandidateAvailabilityFilter); } size += personNameFilters_.CalculateSize(_repeated_personNameFilters_codec); if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(ProfileQuery other) { if (other == null) { return; } if (other.Query.Length != 0) { Query = other.Query; } locationFilters_.Add(other.locationFilters_); jobTitleFilters_.Add(other.jobTitleFilters_); employerFilters_.Add(other.employerFilters_); educationFilters_.Add(other.educationFilters_); skillFilters_.Add(other.skillFilters_); workExperienceFilter_.Add(other.workExperienceFilter_); timeFilters_.Add(other.timeFilters_); if (other.hirableFilter_ != null) { if (hirableFilter_ == null || other.HirableFilter != false) { HirableFilter = other.HirableFilter; } } applicationDateFilters_.Add(other.applicationDateFilters_); applicationOutcomeNotesFilters_.Add(other.applicationOutcomeNotesFilters_); applicationJobFilters_.Add(other.applicationJobFilters_); if (other.CustomAttributeFilter.Length != 0) { CustomAttributeFilter = other.CustomAttributeFilter; } if (other.candidateAvailabilityFilter_ != null) { if (candidateAvailabilityFilter_ == null) { CandidateAvailabilityFilter = new global::Google.Cloud.Talent.V4Beta1.CandidateAvailabilityFilter(); } CandidateAvailabilityFilter.MergeFrom(other.CandidateAvailabilityFilter); } personNameFilters_.Add(other.personNameFilters_); _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 10: { Query = input.ReadString(); break; } case 18: { locationFilters_.AddEntriesFrom(input, _repeated_locationFilters_codec); break; } case 26: { jobTitleFilters_.AddEntriesFrom(input, _repeated_jobTitleFilters_codec); break; } case 34: { employerFilters_.AddEntriesFrom(input, _repeated_employerFilters_codec); break; } case 42: { educationFilters_.AddEntriesFrom(input, _repeated_educationFilters_codec); break; } case 50: { skillFilters_.AddEntriesFrom(input, _repeated_skillFilters_codec); break; } case 58: { workExperienceFilter_.AddEntriesFrom(input, _repeated_workExperienceFilter_codec); break; } case 66: { timeFilters_.AddEntriesFrom(input, _repeated_timeFilters_codec); break; } case 74: { bool? value = _single_hirableFilter_codec.Read(input); if (hirableFilter_ == null || value != false) { HirableFilter = value; } break; } case 82: { applicationDateFilters_.AddEntriesFrom(input, _repeated_applicationDateFilters_codec); break; } case 90: { applicationOutcomeNotesFilters_.AddEntriesFrom(input, _repeated_applicationOutcomeNotesFilters_codec); break; } case 106: { applicationJobFilters_.AddEntriesFrom(input, _repeated_applicationJobFilters_codec); break; } case 122: { CustomAttributeFilter = input.ReadString(); break; } case 130: { if (candidateAvailabilityFilter_ == null) { CandidateAvailabilityFilter = new global::Google.Cloud.Talent.V4Beta1.CandidateAvailabilityFilter(); } input.ReadMessage(CandidateAvailabilityFilter); break; } case 138: { personNameFilters_.AddEntriesFrom(input, _repeated_personNameFilters_codec); break; } } } } } /// <summary> /// Input only. /// /// Geographic region of the search. /// </summary> public sealed partial class LocationFilter : pb::IMessage<LocationFilter> { private static readonly pb::MessageParser<LocationFilter> _parser = new pb::MessageParser<LocationFilter>(() => new LocationFilter()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<LocationFilter> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.Talent.V4Beta1.FiltersReflection.Descriptor.MessageTypes[2]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public LocationFilter() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public LocationFilter(LocationFilter other) : this() { address_ = other.address_; regionCode_ = other.regionCode_; latLng_ = other.latLng_ != null ? other.latLng_.Clone() : null; distanceInMiles_ = other.distanceInMiles_; telecommutePreference_ = other.telecommutePreference_; negated_ = other.negated_; _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public LocationFilter Clone() { return new LocationFilter(this); } /// <summary>Field number for the "address" field.</summary> public const int AddressFieldNumber = 1; private string address_ = ""; /// <summary> /// Optional. The address name, such as "Mountain View" or "Bay Area". /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Address { get { return address_; } set { address_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "region_code" field.</summary> public const int RegionCodeFieldNumber = 2; private string regionCode_ = ""; /// <summary> /// Optional. CLDR region code of the country/region of the address. This is /// used to address ambiguity of the user-input location, for example, /// "Liverpool" against "Liverpool, NY, US" or "Liverpool, UK". /// /// Set this field to bias location resolution toward a specific country /// or territory. If this field is not set, application behavior is biased /// toward the United States by default. /// /// See http://cldr.unicode.org/ and /// http://www.unicode.org/cldr/charts/30/supplemental/territory_information.html /// for details. Example: "CH" for Switzerland. /// Note that this filter is not applicable for Profile Search related queries. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string RegionCode { get { return regionCode_; } set { regionCode_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "lat_lng" field.</summary> public const int LatLngFieldNumber = 3; private global::Google.Type.LatLng latLng_; /// <summary> /// Optional. The latitude and longitude of the geographic center to search /// from. This field is ignored if `address` is provided. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Type.LatLng LatLng { get { return latLng_; } set { latLng_ = value; } } /// <summary>Field number for the "distance_in_miles" field.</summary> public const int DistanceInMilesFieldNumber = 4; private double distanceInMiles_; /// <summary> /// Optional. The distance_in_miles is applied when the location being searched /// for is identified as a city or smaller. This field is ignored if the /// location being searched for is a state or larger. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public double DistanceInMiles { get { return distanceInMiles_; } set { distanceInMiles_ = value; } } /// <summary>Field number for the "telecommute_preference" field.</summary> public const int TelecommutePreferenceFieldNumber = 5; private global::Google.Cloud.Talent.V4Beta1.LocationFilter.Types.TelecommutePreference telecommutePreference_ = 0; /// <summary> /// Optional. Allows the client to return jobs without a /// set location, specifically, telecommuting jobs (telecommuting is considered /// by the service as a special location. /// [Job.posting_region][google.cloud.talent.v4beta1.Job.posting_region] /// indicates if a job permits telecommuting. If this field is set to /// [TelecommutePreference.TELECOMMUTE_ALLOWED][google.cloud.talent.v4beta1.LocationFilter.TelecommutePreference.TELECOMMUTE_ALLOWED], /// telecommuting jobs are searched, and /// [address][google.cloud.talent.v4beta1.LocationFilter.address] and /// [lat_lng][google.cloud.talent.v4beta1.LocationFilter.lat_lng] are ignored. /// If not set or set to /// [TelecommutePreference.TELECOMMUTE_EXCLUDED][google.cloud.talent.v4beta1.LocationFilter.TelecommutePreference.TELECOMMUTE_EXCLUDED], /// telecommute job are not searched. /// /// This filter can be used by itself to search exclusively for telecommuting /// jobs, or it can be combined with another location /// filter to search for a combination of job locations, /// such as "Mountain View" or "telecommuting" jobs. However, when used in /// combination with other location filters, telecommuting jobs can be /// treated as less relevant than other jobs in the search response. /// /// This field is only used for job search requests. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Cloud.Talent.V4Beta1.LocationFilter.Types.TelecommutePreference TelecommutePreference { get { return telecommutePreference_; } set { telecommutePreference_ = value; } } /// <summary>Field number for the "negated" field.</summary> public const int NegatedFieldNumber = 6; private bool negated_; /// <summary> /// Optional. Whether to apply negation to the filter so profiles matching the /// filter are excluded. /// /// Currently only supported in profile search. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Negated { get { return negated_; } set { negated_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as LocationFilter); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(LocationFilter other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Address != other.Address) return false; if (RegionCode != other.RegionCode) return false; if (!object.Equals(LatLng, other.LatLng)) return false; if (!pbc::ProtobufEqualityComparers.BitwiseDoubleEqualityComparer.Equals(DistanceInMiles, other.DistanceInMiles)) return false; if (TelecommutePreference != other.TelecommutePreference) return false; if (Negated != other.Negated) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Address.Length != 0) hash ^= Address.GetHashCode(); if (RegionCode.Length != 0) hash ^= RegionCode.GetHashCode(); if (latLng_ != null) hash ^= LatLng.GetHashCode(); if (DistanceInMiles != 0D) hash ^= pbc::ProtobufEqualityComparers.BitwiseDoubleEqualityComparer.GetHashCode(DistanceInMiles); if (TelecommutePreference != 0) hash ^= TelecommutePreference.GetHashCode(); if (Negated != false) hash ^= Negated.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Address.Length != 0) { output.WriteRawTag(10); output.WriteString(Address); } if (RegionCode.Length != 0) { output.WriteRawTag(18); output.WriteString(RegionCode); } if (latLng_ != null) { output.WriteRawTag(26); output.WriteMessage(LatLng); } if (DistanceInMiles != 0D) { output.WriteRawTag(33); output.WriteDouble(DistanceInMiles); } if (TelecommutePreference != 0) { output.WriteRawTag(40); output.WriteEnum((int) TelecommutePreference); } if (Negated != false) { output.WriteRawTag(48); output.WriteBool(Negated); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Address.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Address); } if (RegionCode.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(RegionCode); } if (latLng_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(LatLng); } if (DistanceInMiles != 0D) { size += 1 + 8; } if (TelecommutePreference != 0) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) TelecommutePreference); } if (Negated != false) { size += 1 + 1; } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(LocationFilter other) { if (other == null) { return; } if (other.Address.Length != 0) { Address = other.Address; } if (other.RegionCode.Length != 0) { RegionCode = other.RegionCode; } if (other.latLng_ != null) { if (latLng_ == null) { LatLng = new global::Google.Type.LatLng(); } LatLng.MergeFrom(other.LatLng); } if (other.DistanceInMiles != 0D) { DistanceInMiles = other.DistanceInMiles; } if (other.TelecommutePreference != 0) { TelecommutePreference = other.TelecommutePreference; } if (other.Negated != false) { Negated = other.Negated; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 10: { Address = input.ReadString(); break; } case 18: { RegionCode = input.ReadString(); break; } case 26: { if (latLng_ == null) { LatLng = new global::Google.Type.LatLng(); } input.ReadMessage(LatLng); break; } case 33: { DistanceInMiles = input.ReadDouble(); break; } case 40: { TelecommutePreference = (global::Google.Cloud.Talent.V4Beta1.LocationFilter.Types.TelecommutePreference) input.ReadEnum(); break; } case 48: { Negated = input.ReadBool(); break; } } } } #region Nested types /// <summary>Container for nested types declared in the LocationFilter message type.</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static partial class Types { /// <summary> /// Specify whether to include telecommute jobs. /// </summary> public enum TelecommutePreference { /// <summary> /// Default value if the telecommute preference isn't specified. /// </summary> [pbr::OriginalName("TELECOMMUTE_PREFERENCE_UNSPECIFIED")] Unspecified = 0, /// <summary> /// Exclude telecommute jobs. /// </summary> [pbr::OriginalName("TELECOMMUTE_EXCLUDED")] TelecommuteExcluded = 1, /// <summary> /// Allow telecommute jobs. /// </summary> [pbr::OriginalName("TELECOMMUTE_ALLOWED")] TelecommuteAllowed = 2, } } #endregion } /// <summary> /// Input only. /// /// Filter on job compensation type and amount. /// </summary> public sealed partial class CompensationFilter : pb::IMessage<CompensationFilter> { private static readonly pb::MessageParser<CompensationFilter> _parser = new pb::MessageParser<CompensationFilter>(() => new CompensationFilter()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<CompensationFilter> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.Talent.V4Beta1.FiltersReflection.Descriptor.MessageTypes[3]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public CompensationFilter() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public CompensationFilter(CompensationFilter other) : this() { type_ = other.type_; units_ = other.units_.Clone(); range_ = other.range_ != null ? other.range_.Clone() : null; includeJobsWithUnspecifiedCompensationRange_ = other.includeJobsWithUnspecifiedCompensationRange_; _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public CompensationFilter Clone() { return new CompensationFilter(this); } /// <summary>Field number for the "type" field.</summary> public const int TypeFieldNumber = 1; private global::Google.Cloud.Talent.V4Beta1.CompensationFilter.Types.FilterType type_ = 0; /// <summary> /// Required. Type of filter. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Cloud.Talent.V4Beta1.CompensationFilter.Types.FilterType Type { get { return type_; } set { type_ = value; } } /// <summary>Field number for the "units" field.</summary> public const int UnitsFieldNumber = 2; private static readonly pb::FieldCodec<global::Google.Cloud.Talent.V4Beta1.CompensationInfo.Types.CompensationUnit> _repeated_units_codec = pb::FieldCodec.ForEnum(18, x => (int) x, x => (global::Google.Cloud.Talent.V4Beta1.CompensationInfo.Types.CompensationUnit) x); private readonly pbc::RepeatedField<global::Google.Cloud.Talent.V4Beta1.CompensationInfo.Types.CompensationUnit> units_ = new pbc::RepeatedField<global::Google.Cloud.Talent.V4Beta1.CompensationInfo.Types.CompensationUnit>(); /// <summary> /// Required. Specify desired `base compensation entry's` /// [CompensationInfo.CompensationUnit][google.cloud.talent.v4beta1.CompensationInfo.CompensationUnit]. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<global::Google.Cloud.Talent.V4Beta1.CompensationInfo.Types.CompensationUnit> Units { get { return units_; } } /// <summary>Field number for the "range" field.</summary> public const int RangeFieldNumber = 3; private global::Google.Cloud.Talent.V4Beta1.CompensationInfo.Types.CompensationRange range_; /// <summary> /// Optional. Compensation range. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Cloud.Talent.V4Beta1.CompensationInfo.Types.CompensationRange Range { get { return range_; } set { range_ = value; } } /// <summary>Field number for the "include_jobs_with_unspecified_compensation_range" field.</summary> public const int IncludeJobsWithUnspecifiedCompensationRangeFieldNumber = 4; private bool includeJobsWithUnspecifiedCompensationRange_; /// <summary> /// Optional. If set to true, jobs with unspecified compensation range fields /// are included. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool IncludeJobsWithUnspecifiedCompensationRange { get { return includeJobsWithUnspecifiedCompensationRange_; } set { includeJobsWithUnspecifiedCompensationRange_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as CompensationFilter); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(CompensationFilter other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Type != other.Type) return false; if(!units_.Equals(other.units_)) return false; if (!object.Equals(Range, other.Range)) return false; if (IncludeJobsWithUnspecifiedCompensationRange != other.IncludeJobsWithUnspecifiedCompensationRange) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Type != 0) hash ^= Type.GetHashCode(); hash ^= units_.GetHashCode(); if (range_ != null) hash ^= Range.GetHashCode(); if (IncludeJobsWithUnspecifiedCompensationRange != false) hash ^= IncludeJobsWithUnspecifiedCompensationRange.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Type != 0) { output.WriteRawTag(8); output.WriteEnum((int) Type); } units_.WriteTo(output, _repeated_units_codec); if (range_ != null) { output.WriteRawTag(26); output.WriteMessage(Range); } if (IncludeJobsWithUnspecifiedCompensationRange != false) { output.WriteRawTag(32); output.WriteBool(IncludeJobsWithUnspecifiedCompensationRange); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Type != 0) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Type); } size += units_.CalculateSize(_repeated_units_codec); if (range_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Range); } if (IncludeJobsWithUnspecifiedCompensationRange != false) { size += 1 + 1; } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(CompensationFilter other) { if (other == null) { return; } if (other.Type != 0) { Type = other.Type; } units_.Add(other.units_); if (other.range_ != null) { if (range_ == null) { Range = new global::Google.Cloud.Talent.V4Beta1.CompensationInfo.Types.CompensationRange(); } Range.MergeFrom(other.Range); } if (other.IncludeJobsWithUnspecifiedCompensationRange != false) { IncludeJobsWithUnspecifiedCompensationRange = other.IncludeJobsWithUnspecifiedCompensationRange; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 8: { Type = (global::Google.Cloud.Talent.V4Beta1.CompensationFilter.Types.FilterType) input.ReadEnum(); break; } case 18: case 16: { units_.AddEntriesFrom(input, _repeated_units_codec); break; } case 26: { if (range_ == null) { Range = new global::Google.Cloud.Talent.V4Beta1.CompensationInfo.Types.CompensationRange(); } input.ReadMessage(Range); break; } case 32: { IncludeJobsWithUnspecifiedCompensationRange = input.ReadBool(); break; } } } } #region Nested types /// <summary>Container for nested types declared in the CompensationFilter message type.</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static partial class Types { /// <summary> /// Specify the type of filtering. /// </summary> public enum FilterType { /// <summary> /// Filter type unspecified. Position holder, INVALID, should never be used. /// </summary> [pbr::OriginalName("FILTER_TYPE_UNSPECIFIED")] Unspecified = 0, /// <summary> /// Filter by `base compensation entry's` unit. A job is a match if and /// only if the job contains a base CompensationEntry and the base /// CompensationEntry's unit matches provided /// [units][google.cloud.talent.v4beta1.CompensationFilter.units]. Populate /// one or more /// [units][google.cloud.talent.v4beta1.CompensationFilter.units]. /// /// See /// [CompensationInfo.CompensationEntry][google.cloud.talent.v4beta1.CompensationInfo.CompensationEntry] /// for definition of base compensation entry. /// </summary> [pbr::OriginalName("UNIT_ONLY")] UnitOnly = 1, /// <summary> /// Filter by `base compensation entry's` unit and amount / range. A job /// is a match if and only if the job contains a base CompensationEntry, and /// the base entry's unit matches provided /// [CompensationUnit][google.cloud.talent.v4beta1.CompensationInfo.CompensationUnit] /// and amount or range overlaps with provided /// [CompensationRange][google.cloud.talent.v4beta1.CompensationInfo.CompensationRange]. /// /// See /// [CompensationInfo.CompensationEntry][google.cloud.talent.v4beta1.CompensationInfo.CompensationEntry] /// for definition of base compensation entry. /// /// Set exactly one /// [units][google.cloud.talent.v4beta1.CompensationFilter.units] and /// populate [range][google.cloud.talent.v4beta1.CompensationFilter.range]. /// </summary> [pbr::OriginalName("UNIT_AND_AMOUNT")] UnitAndAmount = 2, /// <summary> /// Filter by annualized base compensation amount and `base compensation /// entry's` unit. Populate /// [range][google.cloud.talent.v4beta1.CompensationFilter.range] and zero or /// more [units][google.cloud.talent.v4beta1.CompensationFilter.units]. /// </summary> [pbr::OriginalName("ANNUALIZED_BASE_AMOUNT")] AnnualizedBaseAmount = 3, /// <summary> /// Filter by annualized total compensation amount and `base compensation /// entry's` unit . Populate /// [range][google.cloud.talent.v4beta1.CompensationFilter.range] and zero or /// more [units][google.cloud.talent.v4beta1.CompensationFilter.units]. /// </summary> [pbr::OriginalName("ANNUALIZED_TOTAL_AMOUNT")] AnnualizedTotalAmount = 4, } } #endregion } /// <summary> /// Input only. /// /// Parameters needed for commute search. /// </summary> public sealed partial class CommuteFilter : pb::IMessage<CommuteFilter> { private static readonly pb::MessageParser<CommuteFilter> _parser = new pb::MessageParser<CommuteFilter>(() => new CommuteFilter()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<CommuteFilter> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.Talent.V4Beta1.FiltersReflection.Descriptor.MessageTypes[4]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public CommuteFilter() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public CommuteFilter(CommuteFilter other) : this() { commuteMethod_ = other.commuteMethod_; startCoordinates_ = other.startCoordinates_ != null ? other.startCoordinates_.Clone() : null; travelDuration_ = other.travelDuration_ != null ? other.travelDuration_.Clone() : null; allowImpreciseAddresses_ = other.allowImpreciseAddresses_; switch (other.TrafficOptionCase) { case TrafficOptionOneofCase.RoadTraffic: RoadTraffic = other.RoadTraffic; break; case TrafficOptionOneofCase.DepartureTime: DepartureTime = other.DepartureTime.Clone(); break; } _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public CommuteFilter Clone() { return new CommuteFilter(this); } /// <summary>Field number for the "commute_method" field.</summary> public const int CommuteMethodFieldNumber = 1; private global::Google.Cloud.Talent.V4Beta1.CommuteMethod commuteMethod_ = 0; /// <summary> /// Required. The method of transportation for which to calculate the commute /// time. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Cloud.Talent.V4Beta1.CommuteMethod CommuteMethod { get { return commuteMethod_; } set { commuteMethod_ = value; } } /// <summary>Field number for the "start_coordinates" field.</summary> public const int StartCoordinatesFieldNumber = 2; private global::Google.Type.LatLng startCoordinates_; /// <summary> /// Required. The latitude and longitude of the location from which to /// calculate the commute time. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Type.LatLng StartCoordinates { get { return startCoordinates_; } set { startCoordinates_ = value; } } /// <summary>Field number for the "travel_duration" field.</summary> public const int TravelDurationFieldNumber = 3; private global::Google.Protobuf.WellKnownTypes.Duration travelDuration_; /// <summary> /// Required. The maximum travel time in seconds. The maximum allowed value is /// `3600s` (one hour). Format is `123s`. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Protobuf.WellKnownTypes.Duration TravelDuration { get { return travelDuration_; } set { travelDuration_ = value; } } /// <summary>Field number for the "allow_imprecise_addresses" field.</summary> public const int AllowImpreciseAddressesFieldNumber = 4; private bool allowImpreciseAddresses_; /// <summary> /// Optional. If `true`, jobs without street level addresses may also be /// returned. For city level addresses, the city center is used. For state and /// coarser level addresses, text matching is used. If this field is set to /// `false` or isn't specified, only jobs that include street level addresses /// will be returned by commute search. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool AllowImpreciseAddresses { get { return allowImpreciseAddresses_; } set { allowImpreciseAddresses_ = value; } } /// <summary>Field number for the "road_traffic" field.</summary> public const int RoadTrafficFieldNumber = 5; /// <summary> /// Optional. Specifies the traffic density to use when calculating commute /// time. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Cloud.Talent.V4Beta1.CommuteFilter.Types.RoadTraffic RoadTraffic { get { return trafficOptionCase_ == TrafficOptionOneofCase.RoadTraffic ? (global::Google.Cloud.Talent.V4Beta1.CommuteFilter.Types.RoadTraffic) trafficOption_ : 0; } set { trafficOption_ = value; trafficOptionCase_ = TrafficOptionOneofCase.RoadTraffic; } } /// <summary>Field number for the "departure_time" field.</summary> public const int DepartureTimeFieldNumber = 6; /// <summary> /// Optional. The departure time used to calculate traffic impact, /// represented as [google.type.TimeOfDay][google.type.TimeOfDay] in local /// time zone. /// /// Currently traffic model is restricted to hour level resolution. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Type.TimeOfDay DepartureTime { get { return trafficOptionCase_ == TrafficOptionOneofCase.DepartureTime ? (global::Google.Type.TimeOfDay) trafficOption_ : null; } set { trafficOption_ = value; trafficOptionCase_ = value == null ? TrafficOptionOneofCase.None : TrafficOptionOneofCase.DepartureTime; } } private object trafficOption_; /// <summary>Enum of possible cases for the "traffic_option" oneof.</summary> public enum TrafficOptionOneofCase { None = 0, RoadTraffic = 5, DepartureTime = 6, } private TrafficOptionOneofCase trafficOptionCase_ = TrafficOptionOneofCase.None; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public TrafficOptionOneofCase TrafficOptionCase { get { return trafficOptionCase_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void ClearTrafficOption() { trafficOptionCase_ = TrafficOptionOneofCase.None; trafficOption_ = null; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as CommuteFilter); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(CommuteFilter other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (CommuteMethod != other.CommuteMethod) return false; if (!object.Equals(StartCoordinates, other.StartCoordinates)) return false; if (!object.Equals(TravelDuration, other.TravelDuration)) return false; if (AllowImpreciseAddresses != other.AllowImpreciseAddresses) return false; if (RoadTraffic != other.RoadTraffic) return false; if (!object.Equals(DepartureTime, other.DepartureTime)) return false; if (TrafficOptionCase != other.TrafficOptionCase) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (CommuteMethod != 0) hash ^= CommuteMethod.GetHashCode(); if (startCoordinates_ != null) hash ^= StartCoordinates.GetHashCode(); if (travelDuration_ != null) hash ^= TravelDuration.GetHashCode(); if (AllowImpreciseAddresses != false) hash ^= AllowImpreciseAddresses.GetHashCode(); if (trafficOptionCase_ == TrafficOptionOneofCase.RoadTraffic) hash ^= RoadTraffic.GetHashCode(); if (trafficOptionCase_ == TrafficOptionOneofCase.DepartureTime) hash ^= DepartureTime.GetHashCode(); hash ^= (int) trafficOptionCase_; if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (CommuteMethod != 0) { output.WriteRawTag(8); output.WriteEnum((int) CommuteMethod); } if (startCoordinates_ != null) { output.WriteRawTag(18); output.WriteMessage(StartCoordinates); } if (travelDuration_ != null) { output.WriteRawTag(26); output.WriteMessage(TravelDuration); } if (AllowImpreciseAddresses != false) { output.WriteRawTag(32); output.WriteBool(AllowImpreciseAddresses); } if (trafficOptionCase_ == TrafficOptionOneofCase.RoadTraffic) { output.WriteRawTag(40); output.WriteEnum((int) RoadTraffic); } if (trafficOptionCase_ == TrafficOptionOneofCase.DepartureTime) { output.WriteRawTag(50); output.WriteMessage(DepartureTime); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (CommuteMethod != 0) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) CommuteMethod); } if (startCoordinates_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(StartCoordinates); } if (travelDuration_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(TravelDuration); } if (AllowImpreciseAddresses != false) { size += 1 + 1; } if (trafficOptionCase_ == TrafficOptionOneofCase.RoadTraffic) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) RoadTraffic); } if (trafficOptionCase_ == TrafficOptionOneofCase.DepartureTime) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(DepartureTime); } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(CommuteFilter other) { if (other == null) { return; } if (other.CommuteMethod != 0) { CommuteMethod = other.CommuteMethod; } if (other.startCoordinates_ != null) { if (startCoordinates_ == null) { StartCoordinates = new global::Google.Type.LatLng(); } StartCoordinates.MergeFrom(other.StartCoordinates); } if (other.travelDuration_ != null) { if (travelDuration_ == null) { TravelDuration = new global::Google.Protobuf.WellKnownTypes.Duration(); } TravelDuration.MergeFrom(other.TravelDuration); } if (other.AllowImpreciseAddresses != false) { AllowImpreciseAddresses = other.AllowImpreciseAddresses; } switch (other.TrafficOptionCase) { case TrafficOptionOneofCase.RoadTraffic: RoadTraffic = other.RoadTraffic; break; case TrafficOptionOneofCase.DepartureTime: if (DepartureTime == null) { DepartureTime = new global::Google.Type.TimeOfDay(); } DepartureTime.MergeFrom(other.DepartureTime); break; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 8: { CommuteMethod = (global::Google.Cloud.Talent.V4Beta1.CommuteMethod) input.ReadEnum(); break; } case 18: { if (startCoordinates_ == null) { StartCoordinates = new global::Google.Type.LatLng(); } input.ReadMessage(StartCoordinates); break; } case 26: { if (travelDuration_ == null) { TravelDuration = new global::Google.Protobuf.WellKnownTypes.Duration(); } input.ReadMessage(TravelDuration); break; } case 32: { AllowImpreciseAddresses = input.ReadBool(); break; } case 40: { trafficOption_ = input.ReadEnum(); trafficOptionCase_ = TrafficOptionOneofCase.RoadTraffic; break; } case 50: { global::Google.Type.TimeOfDay subBuilder = new global::Google.Type.TimeOfDay(); if (trafficOptionCase_ == TrafficOptionOneofCase.DepartureTime) { subBuilder.MergeFrom(DepartureTime); } input.ReadMessage(subBuilder); DepartureTime = subBuilder; break; } } } } #region Nested types /// <summary>Container for nested types declared in the CommuteFilter message type.</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static partial class Types { /// <summary> /// The traffic density to use when calculating commute time. /// </summary> public enum RoadTraffic { /// <summary> /// Road traffic situation isn't specified. /// </summary> [pbr::OriginalName("ROAD_TRAFFIC_UNSPECIFIED")] Unspecified = 0, /// <summary> /// Optimal commute time without considering any traffic impact. /// </summary> [pbr::OriginalName("TRAFFIC_FREE")] TrafficFree = 1, /// <summary> /// Commute time calculation takes in account the peak traffic impact. /// </summary> [pbr::OriginalName("BUSY_HOUR")] BusyHour = 2, } } #endregion } /// <summary> /// Input only. /// /// Job title of the search. /// </summary> public sealed partial class JobTitleFilter : pb::IMessage<JobTitleFilter> { private static readonly pb::MessageParser<JobTitleFilter> _parser = new pb::MessageParser<JobTitleFilter>(() => new JobTitleFilter()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<JobTitleFilter> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.Talent.V4Beta1.FiltersReflection.Descriptor.MessageTypes[5]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public JobTitleFilter() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public JobTitleFilter(JobTitleFilter other) : this() { jobTitle_ = other.jobTitle_; negated_ = other.negated_; _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public JobTitleFilter Clone() { return new JobTitleFilter(this); } /// <summary>Field number for the "job_title" field.</summary> public const int JobTitleFieldNumber = 1; private string jobTitle_ = ""; /// <summary> /// Required. The job title, for example, "Software engineer", or "Product /// manager". /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string JobTitle { get { return jobTitle_; } set { jobTitle_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "negated" field.</summary> public const int NegatedFieldNumber = 2; private bool negated_; /// <summary> /// Optional. Whether to apply negation to the filter so profiles matching the /// filter are excluded. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Negated { get { return negated_; } set { negated_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as JobTitleFilter); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(JobTitleFilter other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (JobTitle != other.JobTitle) return false; if (Negated != other.Negated) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (JobTitle.Length != 0) hash ^= JobTitle.GetHashCode(); if (Negated != false) hash ^= Negated.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (JobTitle.Length != 0) { output.WriteRawTag(10); output.WriteString(JobTitle); } if (Negated != false) { output.WriteRawTag(16); output.WriteBool(Negated); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (JobTitle.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(JobTitle); } if (Negated != false) { size += 1 + 1; } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(JobTitleFilter other) { if (other == null) { return; } if (other.JobTitle.Length != 0) { JobTitle = other.JobTitle; } if (other.Negated != false) { Negated = other.Negated; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 10: { JobTitle = input.ReadString(); break; } case 16: { Negated = input.ReadBool(); break; } } } } } /// <summary> /// Input only. /// /// Skill filter of the search. /// </summary> public sealed partial class SkillFilter : pb::IMessage<SkillFilter> { private static readonly pb::MessageParser<SkillFilter> _parser = new pb::MessageParser<SkillFilter>(() => new SkillFilter()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<SkillFilter> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.Talent.V4Beta1.FiltersReflection.Descriptor.MessageTypes[6]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public SkillFilter() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public SkillFilter(SkillFilter other) : this() { skill_ = other.skill_; negated_ = other.negated_; _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public SkillFilter Clone() { return new SkillFilter(this); } /// <summary>Field number for the "skill" field.</summary> public const int SkillFieldNumber = 1; private string skill_ = ""; /// <summary> /// Required. The skill name. For example, "java", "j2ee", and so on. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Skill { get { return skill_; } set { skill_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "negated" field.</summary> public const int NegatedFieldNumber = 2; private bool negated_; /// <summary> /// Optional. Whether to apply negation to the filter so profiles matching the /// filter are excluded. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Negated { get { return negated_; } set { negated_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as SkillFilter); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(SkillFilter other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Skill != other.Skill) return false; if (Negated != other.Negated) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Skill.Length != 0) hash ^= Skill.GetHashCode(); if (Negated != false) hash ^= Negated.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Skill.Length != 0) { output.WriteRawTag(10); output.WriteString(Skill); } if (Negated != false) { output.WriteRawTag(16); output.WriteBool(Negated); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Skill.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Skill); } if (Negated != false) { size += 1 + 1; } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(SkillFilter other) { if (other == null) { return; } if (other.Skill.Length != 0) { Skill = other.Skill; } if (other.Negated != false) { Negated = other.Negated; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 10: { Skill = input.ReadString(); break; } case 16: { Negated = input.ReadBool(); break; } } } } } /// <summary> /// Input only. /// /// Employer filter of the search. /// </summary> public sealed partial class EmployerFilter : pb::IMessage<EmployerFilter> { private static readonly pb::MessageParser<EmployerFilter> _parser = new pb::MessageParser<EmployerFilter>(() => new EmployerFilter()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<EmployerFilter> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.Talent.V4Beta1.FiltersReflection.Descriptor.MessageTypes[7]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public EmployerFilter() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public EmployerFilter(EmployerFilter other) : this() { employer_ = other.employer_; mode_ = other.mode_; negated_ = other.negated_; _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public EmployerFilter Clone() { return new EmployerFilter(this); } /// <summary>Field number for the "employer" field.</summary> public const int EmployerFieldNumber = 1; private string employer_ = ""; /// <summary> /// Required. The name of the employer, for example "Google", "Alphabet". /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Employer { get { return employer_; } set { employer_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "mode" field.</summary> public const int ModeFieldNumber = 2; private global::Google.Cloud.Talent.V4Beta1.EmployerFilter.Types.EmployerFilterMode mode_ = 0; /// <summary> /// Optional. Define set of /// [EmploymentRecord][google.cloud.talent.v4beta1.EmploymentRecord]s to search /// against. /// /// Defaults to /// [EmployerFilterMode.ALL_EMPLOYMENT_RECORDS][google.cloud.talent.v4beta1.EmployerFilter.EmployerFilterMode.ALL_EMPLOYMENT_RECORDS]. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Cloud.Talent.V4Beta1.EmployerFilter.Types.EmployerFilterMode Mode { get { return mode_; } set { mode_ = value; } } /// <summary>Field number for the "negated" field.</summary> public const int NegatedFieldNumber = 3; private bool negated_; /// <summary> /// Optional. Whether to apply negation to the filter so profiles matching the /// filter is excluded. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Negated { get { return negated_; } set { negated_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as EmployerFilter); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(EmployerFilter other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Employer != other.Employer) return false; if (Mode != other.Mode) return false; if (Negated != other.Negated) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Employer.Length != 0) hash ^= Employer.GetHashCode(); if (Mode != 0) hash ^= Mode.GetHashCode(); if (Negated != false) hash ^= Negated.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Employer.Length != 0) { output.WriteRawTag(10); output.WriteString(Employer); } if (Mode != 0) { output.WriteRawTag(16); output.WriteEnum((int) Mode); } if (Negated != false) { output.WriteRawTag(24); output.WriteBool(Negated); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Employer.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Employer); } if (Mode != 0) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Mode); } if (Negated != false) { size += 1 + 1; } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(EmployerFilter other) { if (other == null) { return; } if (other.Employer.Length != 0) { Employer = other.Employer; } if (other.Mode != 0) { Mode = other.Mode; } if (other.Negated != false) { Negated = other.Negated; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 10: { Employer = input.ReadString(); break; } case 16: { Mode = (global::Google.Cloud.Talent.V4Beta1.EmployerFilter.Types.EmployerFilterMode) input.ReadEnum(); break; } case 24: { Negated = input.ReadBool(); break; } } } } #region Nested types /// <summary>Container for nested types declared in the EmployerFilter message type.</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static partial class Types { /// <summary> /// Enum indicating which set of /// [Profile.employment_records][google.cloud.talent.v4beta1.Profile.employment_records] /// to search against. /// </summary> public enum EmployerFilterMode { /// <summary> /// Default value. /// </summary> [pbr::OriginalName("EMPLOYER_FILTER_MODE_UNSPECIFIED")] Unspecified = 0, /// <summary> /// Apply to all employers in /// [Profile.employment_records][google.cloud.talent.v4beta1.Profile.employment_records]. /// </summary> [pbr::OriginalName("ALL_EMPLOYMENT_RECORDS")] AllEmploymentRecords = 1, /// <summary> /// Apply only to current employer in /// [Profile.employment_records][google.cloud.talent.v4beta1.Profile.employment_records]. /// </summary> [pbr::OriginalName("CURRENT_EMPLOYMENT_RECORDS_ONLY")] CurrentEmploymentRecordsOnly = 2, /// <summary> /// Apply only to past (not current) employers in /// [Profile.employment_records][google.cloud.talent.v4beta1.Profile.employment_records]. /// </summary> [pbr::OriginalName("PAST_EMPLOYMENT_RECORDS_ONLY")] PastEmploymentRecordsOnly = 3, } } #endregion } /// <summary> /// Input only. /// /// Education filter of the search. /// </summary> public sealed partial class EducationFilter : pb::IMessage<EducationFilter> { private static readonly pb::MessageParser<EducationFilter> _parser = new pb::MessageParser<EducationFilter>(() => new EducationFilter()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<EducationFilter> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.Talent.V4Beta1.FiltersReflection.Descriptor.MessageTypes[8]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public EducationFilter() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public EducationFilter(EducationFilter other) : this() { school_ = other.school_; fieldOfStudy_ = other.fieldOfStudy_; degreeType_ = other.degreeType_; negated_ = other.negated_; _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public EducationFilter Clone() { return new EducationFilter(this); } /// <summary>Field number for the "school" field.</summary> public const int SchoolFieldNumber = 1; private string school_ = ""; /// <summary> /// Optional. The school name. For example "MIT", "University of California, /// Berkeley". /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string School { get { return school_; } set { school_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "field_of_study" field.</summary> public const int FieldOfStudyFieldNumber = 2; private string fieldOfStudy_ = ""; /// <summary> /// Optional. The field of study. This is to search against value provided in /// [Degree.fields_of_study][google.cloud.talent.v4beta1.Degree.fields_of_study]. /// For example "Computer Science", "Mathematics". /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string FieldOfStudy { get { return fieldOfStudy_; } set { fieldOfStudy_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "degree_type" field.</summary> public const int DegreeTypeFieldNumber = 3; private global::Google.Cloud.Talent.V4Beta1.DegreeType degreeType_ = 0; /// <summary> /// Optional. Education degree in ISCED code. Each value in degree covers a /// specific level of education, without any expansion to upper nor lower /// levels of education degree. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Cloud.Talent.V4Beta1.DegreeType DegreeType { get { return degreeType_; } set { degreeType_ = value; } } /// <summary>Field number for the "negated" field.</summary> public const int NegatedFieldNumber = 6; private bool negated_; /// <summary> /// Optional. Whether to apply negation to the filter so profiles matching the /// filter is excluded. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Negated { get { return negated_; } set { negated_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as EducationFilter); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(EducationFilter other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (School != other.School) return false; if (FieldOfStudy != other.FieldOfStudy) return false; if (DegreeType != other.DegreeType) return false; if (Negated != other.Negated) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (School.Length != 0) hash ^= School.GetHashCode(); if (FieldOfStudy.Length != 0) hash ^= FieldOfStudy.GetHashCode(); if (DegreeType != 0) hash ^= DegreeType.GetHashCode(); if (Negated != false) hash ^= Negated.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (School.Length != 0) { output.WriteRawTag(10); output.WriteString(School); } if (FieldOfStudy.Length != 0) { output.WriteRawTag(18); output.WriteString(FieldOfStudy); } if (DegreeType != 0) { output.WriteRawTag(24); output.WriteEnum((int) DegreeType); } if (Negated != false) { output.WriteRawTag(48); output.WriteBool(Negated); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (School.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(School); } if (FieldOfStudy.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(FieldOfStudy); } if (DegreeType != 0) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) DegreeType); } if (Negated != false) { size += 1 + 1; } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(EducationFilter other) { if (other == null) { return; } if (other.School.Length != 0) { School = other.School; } if (other.FieldOfStudy.Length != 0) { FieldOfStudy = other.FieldOfStudy; } if (other.DegreeType != 0) { DegreeType = other.DegreeType; } if (other.Negated != false) { Negated = other.Negated; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 10: { School = input.ReadString(); break; } case 18: { FieldOfStudy = input.ReadString(); break; } case 24: { DegreeType = (global::Google.Cloud.Talent.V4Beta1.DegreeType) input.ReadEnum(); break; } case 48: { Negated = input.ReadBool(); break; } } } } } /// <summary> /// Input only. /// /// Work experience filter. /// /// This filter is used to search for profiles with working experience length /// between /// [min_experience][google.cloud.talent.v4beta1.WorkExperienceFilter.min_experience] /// and /// [max_experience][google.cloud.talent.v4beta1.WorkExperienceFilter.max_experience]. /// </summary> public sealed partial class WorkExperienceFilter : pb::IMessage<WorkExperienceFilter> { private static readonly pb::MessageParser<WorkExperienceFilter> _parser = new pb::MessageParser<WorkExperienceFilter>(() => new WorkExperienceFilter()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<WorkExperienceFilter> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.Talent.V4Beta1.FiltersReflection.Descriptor.MessageTypes[9]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public WorkExperienceFilter() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public WorkExperienceFilter(WorkExperienceFilter other) : this() { minExperience_ = other.minExperience_ != null ? other.minExperience_.Clone() : null; maxExperience_ = other.maxExperience_ != null ? other.maxExperience_.Clone() : null; _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public WorkExperienceFilter Clone() { return new WorkExperienceFilter(this); } /// <summary>Field number for the "min_experience" field.</summary> public const int MinExperienceFieldNumber = 1; private global::Google.Protobuf.WellKnownTypes.Duration minExperience_; /// <summary> /// Optional. The minimum duration of the work experience (inclusive). /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Protobuf.WellKnownTypes.Duration MinExperience { get { return minExperience_; } set { minExperience_ = value; } } /// <summary>Field number for the "max_experience" field.</summary> public const int MaxExperienceFieldNumber = 2; private global::Google.Protobuf.WellKnownTypes.Duration maxExperience_; /// <summary> /// Optional. The maximum duration of the work experience (exclusive). /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Protobuf.WellKnownTypes.Duration MaxExperience { get { return maxExperience_; } set { maxExperience_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as WorkExperienceFilter); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(WorkExperienceFilter other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (!object.Equals(MinExperience, other.MinExperience)) return false; if (!object.Equals(MaxExperience, other.MaxExperience)) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (minExperience_ != null) hash ^= MinExperience.GetHashCode(); if (maxExperience_ != null) hash ^= MaxExperience.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (minExperience_ != null) { output.WriteRawTag(10); output.WriteMessage(MinExperience); } if (maxExperience_ != null) { output.WriteRawTag(18); output.WriteMessage(MaxExperience); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (minExperience_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(MinExperience); } if (maxExperience_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(MaxExperience); } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(WorkExperienceFilter other) { if (other == null) { return; } if (other.minExperience_ != null) { if (minExperience_ == null) { MinExperience = new global::Google.Protobuf.WellKnownTypes.Duration(); } MinExperience.MergeFrom(other.MinExperience); } if (other.maxExperience_ != null) { if (maxExperience_ == null) { MaxExperience = new global::Google.Protobuf.WellKnownTypes.Duration(); } MaxExperience.MergeFrom(other.MaxExperience); } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 10: { if (minExperience_ == null) { MinExperience = new global::Google.Protobuf.WellKnownTypes.Duration(); } input.ReadMessage(MinExperience); break; } case 18: { if (maxExperience_ == null) { MaxExperience = new global::Google.Protobuf.WellKnownTypes.Duration(); } input.ReadMessage(MaxExperience); break; } } } } } /// <summary> /// Input only. /// /// Application Date Range Filter. /// /// The API matches profiles with /// [Application.application_date][google.cloud.talent.v4beta1.Application.application_date] /// between start date and end date (both boundaries are inclusive). The filter /// is ignored if both /// [start_date][google.cloud.talent.v4beta1.ApplicationDateFilter.start_date] /// and [end_date][google.cloud.talent.v4beta1.ApplicationDateFilter.end_date] /// are missing. /// </summary> public sealed partial class ApplicationDateFilter : pb::IMessage<ApplicationDateFilter> { private static readonly pb::MessageParser<ApplicationDateFilter> _parser = new pb::MessageParser<ApplicationDateFilter>(() => new ApplicationDateFilter()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<ApplicationDateFilter> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.Talent.V4Beta1.FiltersReflection.Descriptor.MessageTypes[10]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ApplicationDateFilter() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ApplicationDateFilter(ApplicationDateFilter other) : this() { startDate_ = other.startDate_ != null ? other.startDate_.Clone() : null; endDate_ = other.endDate_ != null ? other.endDate_.Clone() : null; _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ApplicationDateFilter Clone() { return new ApplicationDateFilter(this); } /// <summary>Field number for the "start_date" field.</summary> public const int StartDateFieldNumber = 1; private global::Google.Type.Date startDate_; /// <summary> /// Optional. Start date. If it's missing, The API matches profiles with /// application date not after the end date. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Type.Date StartDate { get { return startDate_; } set { startDate_ = value; } } /// <summary>Field number for the "end_date" field.</summary> public const int EndDateFieldNumber = 2; private global::Google.Type.Date endDate_; /// <summary> /// Optional. End date. If it's missing, The API matches profiles with /// application date not before the start date. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Type.Date EndDate { get { return endDate_; } set { endDate_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as ApplicationDateFilter); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(ApplicationDateFilter other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (!object.Equals(StartDate, other.StartDate)) return false; if (!object.Equals(EndDate, other.EndDate)) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (startDate_ != null) hash ^= StartDate.GetHashCode(); if (endDate_ != null) hash ^= EndDate.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (startDate_ != null) { output.WriteRawTag(10); output.WriteMessage(StartDate); } if (endDate_ != null) { output.WriteRawTag(18); output.WriteMessage(EndDate); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (startDate_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(StartDate); } if (endDate_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(EndDate); } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(ApplicationDateFilter other) { if (other == null) { return; } if (other.startDate_ != null) { if (startDate_ == null) { StartDate = new global::Google.Type.Date(); } StartDate.MergeFrom(other.StartDate); } if (other.endDate_ != null) { if (endDate_ == null) { EndDate = new global::Google.Type.Date(); } EndDate.MergeFrom(other.EndDate); } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 10: { if (startDate_ == null) { StartDate = new global::Google.Type.Date(); } input.ReadMessage(StartDate); break; } case 18: { if (endDate_ == null) { EndDate = new global::Google.Type.Date(); } input.ReadMessage(EndDate); break; } } } } } /// <summary> /// Input only. /// /// Outcome Notes Filter. /// </summary> public sealed partial class ApplicationOutcomeNotesFilter : pb::IMessage<ApplicationOutcomeNotesFilter> { private static readonly pb::MessageParser<ApplicationOutcomeNotesFilter> _parser = new pb::MessageParser<ApplicationOutcomeNotesFilter>(() => new ApplicationOutcomeNotesFilter()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<ApplicationOutcomeNotesFilter> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.Talent.V4Beta1.FiltersReflection.Descriptor.MessageTypes[11]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ApplicationOutcomeNotesFilter() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ApplicationOutcomeNotesFilter(ApplicationOutcomeNotesFilter other) : this() { outcomeNotes_ = other.outcomeNotes_; negated_ = other.negated_; _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ApplicationOutcomeNotesFilter Clone() { return new ApplicationOutcomeNotesFilter(this); } /// <summary>Field number for the "outcome_notes" field.</summary> public const int OutcomeNotesFieldNumber = 1; private string outcomeNotes_ = ""; /// <summary> /// Required. User entered or selected outcome reason. The API does an exact /// match on the /// [Application.outcome_notes][google.cloud.talent.v4beta1.Application.outcome_notes] /// in profiles. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string OutcomeNotes { get { return outcomeNotes_; } set { outcomeNotes_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "negated" field.</summary> public const int NegatedFieldNumber = 2; private bool negated_; /// <summary> /// Optional. If true, The API excludes all candidates with any /// [Application.outcome_notes][google.cloud.talent.v4beta1.Application.outcome_notes] /// matching the outcome reason specified in the filter. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Negated { get { return negated_; } set { negated_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as ApplicationOutcomeNotesFilter); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(ApplicationOutcomeNotesFilter other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (OutcomeNotes != other.OutcomeNotes) return false; if (Negated != other.Negated) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (OutcomeNotes.Length != 0) hash ^= OutcomeNotes.GetHashCode(); if (Negated != false) hash ^= Negated.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (OutcomeNotes.Length != 0) { output.WriteRawTag(10); output.WriteString(OutcomeNotes); } if (Negated != false) { output.WriteRawTag(16); output.WriteBool(Negated); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (OutcomeNotes.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(OutcomeNotes); } if (Negated != false) { size += 1 + 1; } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(ApplicationOutcomeNotesFilter other) { if (other == null) { return; } if (other.OutcomeNotes.Length != 0) { OutcomeNotes = other.OutcomeNotes; } if (other.Negated != false) { Negated = other.Negated; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 10: { OutcomeNotes = input.ReadString(); break; } case 16: { Negated = input.ReadBool(); break; } } } } } /// <summary> /// Input only. /// /// Filter on the job information of Application. /// </summary> public sealed partial class ApplicationJobFilter : pb::IMessage<ApplicationJobFilter> { private static readonly pb::MessageParser<ApplicationJobFilter> _parser = new pb::MessageParser<ApplicationJobFilter>(() => new ApplicationJobFilter()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<ApplicationJobFilter> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.Talent.V4Beta1.FiltersReflection.Descriptor.MessageTypes[12]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ApplicationJobFilter() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ApplicationJobFilter(ApplicationJobFilter other) : this() { jobRequisitionId_ = other.jobRequisitionId_; jobTitle_ = other.jobTitle_; negated_ = other.negated_; _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ApplicationJobFilter Clone() { return new ApplicationJobFilter(this); } /// <summary>Field number for the "job_requisition_id" field.</summary> public const int JobRequisitionIdFieldNumber = 2; private string jobRequisitionId_ = ""; /// <summary> /// Optional. The job requisition id in the application. The API does an exact /// match on the /// [Job.requisition_id][google.cloud.talent.v4beta1.Job.requisition_id] of /// [Application.job][google.cloud.talent.v4beta1.Application.job] in profiles. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string JobRequisitionId { get { return jobRequisitionId_; } set { jobRequisitionId_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "job_title" field.</summary> public const int JobTitleFieldNumber = 3; private string jobTitle_ = ""; /// <summary> /// Optional. The job title in the application. The API does an exact match on /// the [Job.title][google.cloud.talent.v4beta1.Job.title] of /// [Application.job][google.cloud.talent.v4beta1.Application.job] in profiles. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string JobTitle { get { return jobTitle_; } set { jobTitle_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "negated" field.</summary> public const int NegatedFieldNumber = 4; private bool negated_; /// <summary> /// Optional. If true, the API excludes all profiles with any /// [Application.job][google.cloud.talent.v4beta1.Application.job] matching the /// filters. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Negated { get { return negated_; } set { negated_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as ApplicationJobFilter); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(ApplicationJobFilter other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (JobRequisitionId != other.JobRequisitionId) return false; if (JobTitle != other.JobTitle) return false; if (Negated != other.Negated) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (JobRequisitionId.Length != 0) hash ^= JobRequisitionId.GetHashCode(); if (JobTitle.Length != 0) hash ^= JobTitle.GetHashCode(); if (Negated != false) hash ^= Negated.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (JobRequisitionId.Length != 0) { output.WriteRawTag(18); output.WriteString(JobRequisitionId); } if (JobTitle.Length != 0) { output.WriteRawTag(26); output.WriteString(JobTitle); } if (Negated != false) { output.WriteRawTag(32); output.WriteBool(Negated); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (JobRequisitionId.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(JobRequisitionId); } if (JobTitle.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(JobTitle); } if (Negated != false) { size += 1 + 1; } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(ApplicationJobFilter other) { if (other == null) { return; } if (other.JobRequisitionId.Length != 0) { JobRequisitionId = other.JobRequisitionId; } if (other.JobTitle.Length != 0) { JobTitle = other.JobTitle; } if (other.Negated != false) { Negated = other.Negated; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 18: { JobRequisitionId = input.ReadString(); break; } case 26: { JobTitle = input.ReadString(); break; } case 32: { Negated = input.ReadBool(); break; } } } } } /// <summary> /// Input only. /// /// Filter on create timestamp or update timestamp of profiles. /// </summary> public sealed partial class TimeFilter : pb::IMessage<TimeFilter> { private static readonly pb::MessageParser<TimeFilter> _parser = new pb::MessageParser<TimeFilter>(() => new TimeFilter()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<TimeFilter> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.Talent.V4Beta1.FiltersReflection.Descriptor.MessageTypes[13]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public TimeFilter() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public TimeFilter(TimeFilter other) : this() { startTime_ = other.startTime_ != null ? other.startTime_.Clone() : null; endTime_ = other.endTime_ != null ? other.endTime_.Clone() : null; timeField_ = other.timeField_; _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public TimeFilter Clone() { return new TimeFilter(this); } /// <summary>Field number for the "start_time" field.</summary> public const int StartTimeFieldNumber = 1; private global::Google.Protobuf.WellKnownTypes.Timestamp startTime_; /// <summary> /// Optional. Start timestamp, matching profiles with the start time. If this /// field missing, The API matches profiles with create / update timestamp /// before the end timestamp. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Protobuf.WellKnownTypes.Timestamp StartTime { get { return startTime_; } set { startTime_ = value; } } /// <summary>Field number for the "end_time" field.</summary> public const int EndTimeFieldNumber = 2; private global::Google.Protobuf.WellKnownTypes.Timestamp endTime_; /// <summary> /// Optional. End timestamp, matching profiles with the end time. If this field /// missing, The API matches profiles with create / update timestamp after the /// start timestamp. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Protobuf.WellKnownTypes.Timestamp EndTime { get { return endTime_; } set { endTime_ = value; } } /// <summary>Field number for the "time_field" field.</summary> public const int TimeFieldFieldNumber = 3; private global::Google.Cloud.Talent.V4Beta1.TimeFilter.Types.TimeField timeField_ = 0; /// <summary> /// Optional. Specifies which time field to filter profiles. /// /// Defaults to /// [TimeField.CREATE_TIME][google.cloud.talent.v4beta1.TimeFilter.TimeField.CREATE_TIME]. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Cloud.Talent.V4Beta1.TimeFilter.Types.TimeField TimeField { get { return timeField_; } set { timeField_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as TimeFilter); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(TimeFilter other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (!object.Equals(StartTime, other.StartTime)) return false; if (!object.Equals(EndTime, other.EndTime)) return false; if (TimeField != other.TimeField) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (startTime_ != null) hash ^= StartTime.GetHashCode(); if (endTime_ != null) hash ^= EndTime.GetHashCode(); if (TimeField != 0) hash ^= TimeField.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (startTime_ != null) { output.WriteRawTag(10); output.WriteMessage(StartTime); } if (endTime_ != null) { output.WriteRawTag(18); output.WriteMessage(EndTime); } if (TimeField != 0) { output.WriteRawTag(24); output.WriteEnum((int) TimeField); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (startTime_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(StartTime); } if (endTime_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(EndTime); } if (TimeField != 0) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) TimeField); } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(TimeFilter other) { if (other == null) { return; } if (other.startTime_ != null) { if (startTime_ == null) { StartTime = new global::Google.Protobuf.WellKnownTypes.Timestamp(); } StartTime.MergeFrom(other.StartTime); } if (other.endTime_ != null) { if (endTime_ == null) { EndTime = new global::Google.Protobuf.WellKnownTypes.Timestamp(); } EndTime.MergeFrom(other.EndTime); } if (other.TimeField != 0) { TimeField = other.TimeField; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 10: { if (startTime_ == null) { StartTime = new global::Google.Protobuf.WellKnownTypes.Timestamp(); } input.ReadMessage(StartTime); break; } case 18: { if (endTime_ == null) { EndTime = new global::Google.Protobuf.WellKnownTypes.Timestamp(); } input.ReadMessage(EndTime); break; } case 24: { TimeField = (global::Google.Cloud.Talent.V4Beta1.TimeFilter.Types.TimeField) input.ReadEnum(); break; } } } } #region Nested types /// <summary>Container for nested types declared in the TimeFilter message type.</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static partial class Types { /// <summary> /// Time fields can be used in TimeFilter. /// </summary> public enum TimeField { /// <summary> /// Default value. /// </summary> [pbr::OriginalName("TIME_FIELD_UNSPECIFIED")] Unspecified = 0, /// <summary> /// Earliest profile create time. /// </summary> [pbr::OriginalName("CREATE_TIME")] CreateTime = 1, /// <summary> /// Latest profile update time. /// </summary> [pbr::OriginalName("UPDATE_TIME")] UpdateTime = 2, } } #endregion } /// <summary> /// Input only /// /// Filter on availability signals. /// </summary> public sealed partial class CandidateAvailabilityFilter : pb::IMessage<CandidateAvailabilityFilter> { private static readonly pb::MessageParser<CandidateAvailabilityFilter> _parser = new pb::MessageParser<CandidateAvailabilityFilter>(() => new CandidateAvailabilityFilter()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<CandidateAvailabilityFilter> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.Talent.V4Beta1.FiltersReflection.Descriptor.MessageTypes[14]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public CandidateAvailabilityFilter() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public CandidateAvailabilityFilter(CandidateAvailabilityFilter other) : this() { negated_ = other.negated_; _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public CandidateAvailabilityFilter Clone() { return new CandidateAvailabilityFilter(this); } /// <summary>Field number for the "negated" field.</summary> public const int NegatedFieldNumber = 1; private bool negated_; /// <summary> /// Optional. It is false by default. If true, API excludes all the potential /// available profiles. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Negated { get { return negated_; } set { negated_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as CandidateAvailabilityFilter); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(CandidateAvailabilityFilter other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Negated != other.Negated) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Negated != false) hash ^= Negated.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Negated != false) { output.WriteRawTag(8); output.WriteBool(Negated); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Negated != false) { size += 1 + 1; } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(CandidateAvailabilityFilter other) { if (other == null) { return; } if (other.Negated != false) { Negated = other.Negated; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 8: { Negated = input.ReadBool(); break; } } } } } /// <summary> /// Input only. /// /// Filter on person name. /// </summary> public sealed partial class PersonNameFilter : pb::IMessage<PersonNameFilter> { private static readonly pb::MessageParser<PersonNameFilter> _parser = new pb::MessageParser<PersonNameFilter>(() => new PersonNameFilter()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<PersonNameFilter> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.Talent.V4Beta1.FiltersReflection.Descriptor.MessageTypes[15]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public PersonNameFilter() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public PersonNameFilter(PersonNameFilter other) : this() { personName_ = other.personName_; _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public PersonNameFilter Clone() { return new PersonNameFilter(this); } /// <summary>Field number for the "person_name" field.</summary> public const int PersonNameFieldNumber = 1; private string personName_ = ""; /// <summary> /// Required. The person name. For example, "John Smith". /// /// Can be any combination of [PersonName.structured_name.given_name][], /// [PersonName.structured_name.middle_initial][], /// [PersonName.structured_name.family_name][], and /// [PersonName.formatted_name][google.cloud.talent.v4beta1.PersonName.formatted_name]. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string PersonName { get { return personName_; } set { personName_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as PersonNameFilter); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(PersonNameFilter other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (PersonName != other.PersonName) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (PersonName.Length != 0) hash ^= PersonName.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (PersonName.Length != 0) { output.WriteRawTag(10); output.WriteString(PersonName); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (PersonName.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(PersonName); } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(PersonNameFilter other) { if (other == null) { return; } if (other.PersonName.Length != 0) { PersonName = other.PersonName; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 10: { PersonName = input.ReadString(); break; } } } } } #endregion } #endregion Designer generated code
40.486427
517
0.677223
[ "Apache-2.0" ]
mikelehen/google-cloud-dotnet
apis/Google.Cloud.Talent.V4Beta1/Google.Cloud.Talent.V4Beta1/Filters.cs
184,942
C#
using DG.Tweening; using TMPro; using UnityEngine; [RequireComponent(typeof(CanvasGroup))] public class StatsLine : MonoBehaviour { [SerializeField] FadeZoom fadeZoom; [SerializeField] TMP_Text valueText; [SerializeField] float textTransitionDuration = 1f; public Tween TransitionIn(int finalValue = 100) { var canvasGroup = GetComponent<CanvasGroup>(); canvasGroup.alpha = 0f; var sequence = DOTween.Sequence(); var fade = fadeZoom.FadeIn(canvasGroup, transform); sequence.Append(fade); if (valueText) { float currentValue = 0f; valueText.SetText("0"); var text = DOTween.To( () => (int)currentValue, (newValue) => { currentValue = newValue; valueText.SetText(Mathf.RoundToInt(currentValue).ToString()); }, (float)finalValue, textTransitionDuration ); sequence.Append(text); } return sequence; } }
27.595238
82
0.531493
[ "MIT" ]
maksmaisak/Saxion_Y2Q2_Indie_Game
Assets/_Own/Scripts/HUD/StatsLine.cs
1,159
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using BookListRazor.Model; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.HttpsPolicy; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; namespace BookListRazor { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { // add the database connection to our pipeline services.AddDbContext<ApplicationDBContext>(option => option.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); services.AddControllersWithViews(); services.AddRazorPages(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); //route map configuration endpoints.MapRazorPages(); }); } } }
32.301587
143
0.638821
[ "Apache-2.0" ]
DevinDai13/Book-List-Razor
BookListRazor/Startup.cs
2,035
C#
using System; using HdrHistogram.Utilities; namespace HdrHistogram { /// <summary> /// Exposes methods to write values to a <see cref="ByteBuffer"/> with ZigZag LEB-128 encoding. /// </summary> public static class ZigZagEncoding { /// <summary> /// Writes a 64 bit integer (<see cref="long"/>) value to the given buffer in LEB128 ZigZag encoded format. /// </summary> /// <param name="buffer">The buffer to write to.</param> /// <param name="value">The value to write to the buffer.</param> public static void PutLong(ByteBuffer buffer, long value) { value = (value << 1) ^ (value >> 63); if (value >> 7 == 0) { buffer.Put((byte)value); } else { buffer.Put((byte)((value & 0x7F) | 0x80)); if (value >> 14 == 0) { buffer.Put((byte)(value >> 7)); } else { buffer.Put((byte)(value >> 7 | 0x80)); if (value >> 21 == 0) { buffer.Put((byte)(value >> 14)); } else { buffer.Put((byte)(value >> 14 | 0x80)); if (value >> 28 == 0) { buffer.Put((byte)(value >> 21)); } else { buffer.Put((byte)(value >> 21 | 0x80)); if (value >> 35 == 0) { buffer.Put((byte)(value >> 28)); } else { buffer.Put((byte)(value >> 28 | 0x80)); if (value >> 42 == 0) { buffer.Put((byte)(value >> 35)); } else { buffer.Put((byte)(value >> 35 | 0x80)); if (value >> 49 == 0) { buffer.Put((byte)(value >> 42)); } else { buffer.Put((byte)(value >> 42 | 0x80)); if (value >> 56 == 0) { buffer.Put((byte)(value >> 49)); } else { buffer.Put((byte)(value >> 49 | 0x80)); buffer.Put((byte)(value >> 56)); } } } } } } } } } /// <summary> /// Reads an LEB128-64b9B ZigZag encoded 64 bit integer (<see cref="long"/>) value from the given buffer. /// </summary> /// <param name="buffer">The buffer to read from.</param> /// <returns>The value read from the buffer.</returns> public static long GetLong(ByteBuffer buffer) { long v = buffer.Get(); long value = v & 0x7F; if ((v & 0x80) != 0) { v = buffer.Get(); value |= (v & 0x7F) << 7; if ((v & 0x80) != 0) { v = buffer.Get(); value |= (v & 0x7F) << 14; if ((v & 0x80) != 0) { v = buffer.Get(); value |= (v & 0x7F) << 21; if ((v & 0x80) != 0) { v = buffer.Get(); value |= (v & 0x7F) << 28; if ((v & 0x80) != 0) { v = buffer.Get(); value |= (v & 0x7F) << 35; if ((v & 0x80) != 0) { v = buffer.Get(); value |= (v & 0x7F) << 42; if ((v & 0x80) != 0) { v = buffer.Get(); value |= (v & 0x7F) << 49; if ((v & 0x80) != 0) { v = buffer.Get(); value |= v << 56; } } } } } } } } value = (value >> 1) ^ (-(value & 1)); return value; } } }
40.257576
115
0.262514
[ "CC0-1.0" ]
LeeCampbell/HdrHistogram.NET
src/HdrHistogram/ZigZagEncoding.cs
5,316
C#
using Domain.Enums; using DomainBase; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Text; namespace Domain.Entities { /// <summary> /// 账号领域实体 /// </summary> public class Account : Entity, IAggregateRoot { /// <summary> /// 账号 /// </summary> public string LoginName { get; set; } /// <summary> /// 密码 /// </summary> public string Password { get; set; } /// <summary> /// 昵称 /// </summary> public string NickName { get; set; } /// <summary> /// 账户状态 /// </summary> public AccountState State { get; set; } /// <summary> /// 用户信息 /// </summary> [NotMapped] public User User { get; set; } /// <summary> /// 用户权限 /// </summary> [NotMapped] public List<Guid> Roles { get; set; } /// <summary> /// 创建账号 /// </summary> /// <returns></returns> public void CreateAccount(string loginName, string nickName, string sourcePassword, Func<string, object[], string> md5password) { LoginName = loginName; NickName = nickName; Password = md5password(sourcePassword, new object[] { Id }); State = AccountState.Normal; //初始化时不收集用户信息 User = new User() { Gender = UserGender.Unknown }; //创建账号时角色为空 Roles = new List<Guid>(); } /// <summary> /// 修改密码 /// </summary> /// <param name="password"></param> public void UpdateNicknameOrPassword(string nickName, string password) { if (!string.IsNullOrEmpty(password)) { if (string.IsNullOrEmpty(Password)) Password = password; else if (Password == password) throw new DomainException("新旧密码不能相同!"); else Password = password; } if (!string.IsNullOrEmpty(nickName)) { this.NickName = nickName; } } /// <summary> /// 锁定用户 /// </summary> public void ChangeAccountLockState(Guid currentId) { if (Id == currentId) throw new DomainException("登录用户不能锁定自身!"); State = State == AccountState.Normal ? AccountState.Locking : AccountState.Normal; } public void SetRoles(List<Guid> roleids) { if (roleids == null || !roleids.Any()) throw new DomainException("请至少选择一个角色!"); Roles = roleids; } /// <summary> /// 检查用户状态 /// </summary> /// <param name="password"></param> /// <returns></returns> public void CheckAccountCanLogin(string password, bool loginAdmin) { if (Password != password) throw new DomainException("用户密码错误!"); if (State == AccountState.Locking) throw new DomainException("用户被锁定!"); if(loginAdmin && !Roles.Any()) { throw new DomainException("当前用户无法登录管理端!"); } } } }
30.036036
135
0.494901
[ "MIT" ]
dorisoy/EshopSample
Services/AccountService/Domain/Entities/Account.cs
3,558
C#
// Doc/Reference/Reset-Management.md #if !(UNITY_EDITOR || DEBUG) #define AL_OPTIMIZE #endif namespace Active.Core.Details{ public readonly struct Reckoning{ #if !AL_OPTIMIZE internal readonly CallInfo callInfo; #endif internal readonly ReCon.Context context; public Reckoning(bool arg, ReCon stack){ context = arg ? stack.Enter(forward: true) : null; #if !AL_OPTIMIZE callInfo = CallInfo.none; #endif } #if !AL_OPTIMIZE public Reckoning(bool arg, ReCon stack, CallInfo i){ callInfo = i; context = arg ? stack.Enter(forward: true) : null; } #endif public status this[status s]{get{ context?.Exit(); #if AL_OPTIMIZE return s; #else return s / callInfo; #endif }} }}
21.447368
58
0.61227
[ "MIT" ]
eelstork/PuP
Assets/ActiveLogic/Src/Core/Details/Reckoning.cs
815
C#
using System; using System.Threading.Tasks; namespace SharpRemote.Attributes { /// <summary> /// This attribute can be applied to methods with a return type of <see cref="Void"/> /// in order to indicate that it should behave exactly like a method that returns <see cref="Task"/>: /// The method is dispatched asynchronously, however compared to <see cref="Task"/>, there is no /// programmatic way to know when the method has finished, nor when it threw an exception. /// </summary> [AttributeUsage(AttributeTargets.Method | AttributeTargets.Event)] public sealed class AsyncRemoteAttribute : Attribute { } }
36.647059
102
0.741573
[ "MIT" ]
JTOne123/SharpRemote
SharpRemote/Attributes/AsyncRemoteAttribute.cs
625
C#
// <auto-generated /> using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Metadata.Internal; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage; using Microsoft.EntityFrameworkCore.Storage.Internal; using NHLStats.Data; namespace NHLStats.Data.Migrations { [DbContext(typeof(NHLStatsContext))] [Migration("20180422144312_InitDB_20182204_214306")] partial class InitDB_20182204_214306 { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "2.1.0-preview1-28290") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("NHLStats.Core.Models.League", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("Abbreviation"); b.Property<string>("Name"); b.HasKey("Id"); b.ToTable("Leagues"); }); modelBuilder.Entity("NHLStats.Core.Models.Player", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("BirthDate"); b.Property<string>("BirthPlace"); b.Property<string>("Height"); b.Property<string>("Name"); b.Property<int>("WeightLbs"); b.HasKey("Id"); b.ToTable("Players"); }); modelBuilder.Entity("NHLStats.Core.Models.Season", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("Name"); b.HasKey("Id"); b.ToTable("Seasons"); }); modelBuilder.Entity("NHLStats.Core.Models.SkaterStatistic", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<ushort>("Assists"); b.Property<ushort>("GamesPlayed"); b.Property<ushort>("Goals"); b.Property<int>("LeagueId"); b.Property<ushort>("PenaltyMinutes"); b.Property<int>("PlayerId"); b.Property<short?>("PlusMinus"); b.Property<ushort>("Points"); b.Property<int>("SeasonId"); b.Property<int>("TeamId"); b.HasKey("Id"); b.HasIndex("LeagueId"); b.HasIndex("PlayerId"); b.HasIndex("SeasonId"); b.HasIndex("TeamId"); b.ToTable("SkaterStatistics"); }); modelBuilder.Entity("NHLStats.Core.Models.Team", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("Abbreviation"); b.Property<string>("Name"); b.HasKey("Id"); b.ToTable("Teams"); }); modelBuilder.Entity("NHLStats.Core.Models.SkaterStatistic", b => { b.HasOne("NHLStats.Core.Models.League", "League") .WithMany() .HasForeignKey("LeagueId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("NHLStats.Core.Models.Player") .WithMany("SkaterStatistics") .HasForeignKey("PlayerId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("NHLStats.Core.Models.Season", "Season") .WithMany() .HasForeignKey("SeasonId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("NHLStats.Core.Models.Team", "Team") .WithMany() .HasForeignKey("TeamId") .OnDelete(DeleteBehavior.Cascade); }); #pragma warning restore 612, 618 } } }
30.66443
117
0.481506
[ "Unlicense" ]
Mujtaba-Biyabani/Research
ASP.Net/ASPNetCoreGraphQL/src/backend/NHLStats.Data/Migrations/20180422144312_InitDB_20182204_214306.Designer.cs
4,571
C#
using System; using System.Collections.Generic; using CanvasApi.Client.Assignments.Models; using CanvasApi.Client.Assignments.Models.Concretes; using CanvasApi.Client.Courses.Models; using CanvasApi.Client.Users.Models; using CanvasApi.Client.Users.Models.Concretes; namespace CanvasApi.Client.Submissions.Models.Concretes { internal class Submission : ISubmission { public long AssignmentId { get; set; } public Assignment Assignment { get; set; } IAssignment ISubmission.Assignment => this.Assignment; public ICourse Course { get; set; } ICourse ISubmission.Course => this.Course; public int? Attempt { get; set; } public string Body { get; set; } public string Grade { get; set; } public bool? GradeMatchesCurrentSubmission { get; set; } public string HtmlUrl { get; set; } public string PreviewUrl { get; set; } public decimal? Score { get; set; } public IEnumerable<SubmissionComment> SubmissionComments { get; set; } IEnumerable<ISubmissionComment> ISubmission.SubmissionComments => this.SubmissionComments; public string SubmissionType { get; set; } public DateTime? SubmittedAt { get; set; } public string Url { get; set; } public long? UserId { get; set; } public long? GraderId { get; set; } public DateTime? GradedAt { get; set; } public UserDisplay User { get; set; } IUserDisplay ISubmission.User => this.User; public bool? Late { get; set; } public bool? AssignmentVisible { get; set; } public bool? Excused { get; set; } public bool? Missing { get; set; } public string LatePolicyStatus { get; set; } public decimal? PointsDeducted { get; set; } public long? SecondsLate { get; set; } public string WorkflowState { get; set; } public int? ExtraAttempts { get; set; } public string AnonymousId { get; set; } public DateTime? PostedAt { get; set; } } }
37.290909
98
0.649439
[ "MIT" ]
dbagnoli/CanvasApi
CanvasApi.Client/Submissions/Models/Concretes/Submission.cs
2,053
C#
#region Copyright //======================================================================================= // Microsoft Azure Customer Advisory Team // // This sample is supplemental to the technical guidance published on my personal // blog at http://blogs.msdn.com/b/paolos/. // // Author: Paolo Salvatori //======================================================================================= // Copyright (c) Microsoft Corporation. All rights reserved. // // LICENSED UNDER THE APACHE LICENSE, VERSION 2.0 (THE "LICENSE"); YOU MAY NOT USE THESE // FILES 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. //======================================================================================= #endregion using Microsoft.Azure.ServiceBusExplorer.Controls; namespace Microsoft.Azure.ServiceBusExplorer.Forms { partial class CollectionEditorForm { /// <summary> /// Required designer variable. /// </summary> #region Private Fields private System.ComponentModel.IContainer components = null; #endregion /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(CollectionEditorForm)); this.btnOk = new System.Windows.Forms.Button(); this.btnCancel = new System.Windows.Forms.Button(); this.grouperCaption = new Microsoft.Azure.ServiceBusExplorer.Controls.Grouper(); this.dataGridView = new System.Windows.Forms.DataGridView(); this.bindingSource = new System.Windows.Forms.BindingSource(this.components); this.grouperCaption.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.bindingSource)).BeginInit(); this.SuspendLayout(); // // btnOk // this.btnOk.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.btnOk.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(215)))), ((int)(((byte)(228)))), ((int)(((byte)(242))))); this.btnOk.FlatAppearance.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(153)))), ((int)(((byte)(180)))), ((int)(((byte)(209))))); this.btnOk.FlatAppearance.MouseDownBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(153)))), ((int)(((byte)(180)))), ((int)(((byte)(209))))); this.btnOk.FlatAppearance.MouseOverBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(153)))), ((int)(((byte)(180)))), ((int)(((byte)(209))))); this.btnOk.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.btnOk.Location = new System.Drawing.Point(264, 248); this.btnOk.Name = "btnOk"; this.btnOk.Size = new System.Drawing.Size(72, 24); this.btnOk.TabIndex = 2; this.btnOk.Text = "Ok"; this.btnOk.UseVisualStyleBackColor = false; this.btnOk.Click += new System.EventHandler(this.btnOk_Click); this.btnOk.MouseEnter += new System.EventHandler(this.button_MouseEnter); this.btnOk.MouseLeave += new System.EventHandler(this.button_MouseLeave); // // btnCancel // this.btnCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.btnCancel.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(215)))), ((int)(((byte)(228)))), ((int)(((byte)(242))))); this.btnCancel.FlatAppearance.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(153)))), ((int)(((byte)(180)))), ((int)(((byte)(209))))); this.btnCancel.FlatAppearance.MouseDownBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(153)))), ((int)(((byte)(180)))), ((int)(((byte)(209))))); this.btnCancel.FlatAppearance.MouseOverBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(153)))), ((int)(((byte)(180)))), ((int)(((byte)(209))))); this.btnCancel.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.btnCancel.Location = new System.Drawing.Point(344, 248); this.btnCancel.Name = "btnCancel"; this.btnCancel.Size = new System.Drawing.Size(72, 24); this.btnCancel.TabIndex = 3; this.btnCancel.Text = "Cancel"; this.btnCancel.UseVisualStyleBackColor = false; this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click); this.btnCancel.MouseEnter += new System.EventHandler(this.button_MouseEnter); this.btnCancel.MouseLeave += new System.EventHandler(this.button_MouseLeave); // // grouperCaption // this.grouperCaption.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.grouperCaption.BackgroundColor = System.Drawing.Color.FromArgb(((int)(((byte)(215)))), ((int)(((byte)(228)))), ((int)(((byte)(242))))); this.grouperCaption.BackgroundGradientColor = System.Drawing.Color.White; this.grouperCaption.BackgroundGradientMode = Microsoft.Azure.ServiceBusExplorer.Controls.Grouper.GroupBoxGradientMode.None; this.grouperCaption.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(153)))), ((int)(((byte)(180)))), ((int)(((byte)(209))))); this.grouperCaption.BorderThickness = 1F; this.grouperCaption.Controls.Add(this.dataGridView); this.grouperCaption.CustomGroupBoxColor = System.Drawing.Color.FromArgb(((int)(((byte)(153)))), ((int)(((byte)(180)))), ((int)(((byte)(209))))); this.grouperCaption.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F); this.grouperCaption.ForeColor = System.Drawing.Color.White; this.grouperCaption.GroupImage = null; this.grouperCaption.GroupTitle = "Caption"; this.grouperCaption.Location = new System.Drawing.Point(16, 16); this.grouperCaption.Name = "grouperCaption"; this.grouperCaption.Padding = new System.Windows.Forms.Padding(20); this.grouperCaption.PaintGroupBox = true; this.grouperCaption.RoundCorners = 4; this.grouperCaption.ShadowColor = System.Drawing.Color.DarkGray; this.grouperCaption.ShadowControl = false; this.grouperCaption.ShadowThickness = 1; this.grouperCaption.Size = new System.Drawing.Size(400, 216); this.grouperCaption.TabIndex = 33; this.grouperCaption.CustomPaint += new System.Action<System.Windows.Forms.PaintEventArgs>(this.grouperCaption_CustomPaint); // // dataGridView // this.dataGridView.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.dataGridView.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.Fill; this.dataGridView.BackgroundColor = System.Drawing.Color.FromArgb(((int)(((byte)(153)))), ((int)(((byte)(180)))), ((int)(((byte)(209))))); this.dataGridView.BorderStyle = System.Windows.Forms.BorderStyle.None; this.dataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.dataGridView.GridColor = System.Drawing.Color.FromArgb(((int)(((byte)(153)))), ((int)(((byte)(180)))), ((int)(((byte)(209))))); this.dataGridView.Location = new System.Drawing.Point(16, 32); this.dataGridView.Name = "dataGridView"; this.dataGridView.Size = new System.Drawing.Size(368, 168); this.dataGridView.TabIndex = 1; this.dataGridView.DataError += new System.Windows.Forms.DataGridViewDataErrorEventHandler(this.dataGridView_DataError); this.dataGridView.RowsAdded += new System.Windows.Forms.DataGridViewRowsAddedEventHandler(this.dataGridView_RowsAdded); this.dataGridView.RowsRemoved += new System.Windows.Forms.DataGridViewRowsRemovedEventHandler(this.dataGridView_RowsRemoved); this.dataGridView.Resize += new System.EventHandler(this.dataGridView_Resize); // // CollectionEditorForm // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(215)))), ((int)(((byte)(228)))), ((int)(((byte)(242))))); this.ClientSize = new System.Drawing.Size(432, 281); this.Controls.Add(this.grouperCaption); this.Controls.Add(this.btnCancel); this.Controls.Add(this.btnOk); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.Name = "CollectionEditorForm"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "Enter Expression"; this.grouperCaption.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.dataGridView)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.bindingSource)).EndInit(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.Button btnOk; private System.Windows.Forms.Button btnCancel; private Grouper grouperCaption; private System.Windows.Forms.DataGridView dataGridView; private System.Windows.Forms.BindingSource bindingSource; } }
63.005587
165
0.633534
[ "Apache-2.0" ]
MaximPopov/ServiceBusExplorer
src/ServiceBusExplorer/Forms/CollectionEditorForm.Designer.cs
11,280
C#
using AppDynamics.Dexter.ReportObjects; using CsvHelper.Configuration; namespace AppDynamics.Dexter.ReportObjectMaps { public class HealthCheckRuleResultReportMap : ClassMap<HealthCheckRuleResult> { public HealthCheckRuleResultReportMap() { int i = 0; Map(m => m.Controller).Index(i); i++; Map(m => m.Application).Index(i); i++; Map(m => m.EntityType).Index(i); i++; Map(m => m.EntityName).Index(i); i++; Map(m => m.Category).Index(i); i++; Map(m => m.Code).Index(i); i++; Map(m => m.Name).Index(i); i++; Map(m => m.Grade).Index(i); i++; Map(m => m.Description).Index(i); i++; EPPlusCSVHelper.setISO8601DateFormat(Map(m => m.EvaluationTime), i); i++; Map(m => m.Version).Index(i); i++; Map(m => m.ApplicationID).Index(i); i++; Map(m => m.EntityID).Index(i); i++; Map(m => m.RuleLink).Index(i); i++; } } }
32.84375
85
0.50999
[ "Apache-2.0" ]
Appdynamics/AppDynamics.DEXTER
ReportObjects/HealthCheck/Maps/HealthCheckRuleResultReportMap.cs
1,053
C#
using VerifyTests; partial class InnerVerifier : IDisposable { VerifySettings settings; internal GetFileNames GetFileNames { get; } internal GetIndexedFileNames GetIndexedFileNames { get; } internal List<string> VerifiedFiles { get; } internal List<string> ReceivedFiles { get; } public InnerVerifier(string sourceFile, VerifySettings settings, GetFileConvention fileConvention) { this.settings = settings; var uniqueness = PrefixUnique.GetUniqueness(settings.Namer); var (fileNamePrefix, directory) = fileConvention(uniqueness); var sourceFileDirectory = Path.GetDirectoryName(sourceFile)!; if (directory is null) { directory = sourceFileDirectory; } else { directory = Path.Combine(sourceFileDirectory, directory); Directory.CreateDirectory(directory); } var filePathPrefix = Path.Combine(directory, fileNamePrefix); PrefixUnique.CheckPrefixIsUnique(filePathPrefix); var pattern = $"{fileNamePrefix}.*.*"; var files = Directory.EnumerateFiles(directory, pattern).ToList(); VerifiedFiles = MatchingFileFinder.Find(files, fileNamePrefix, ".verified").ToList(); ReceivedFiles = MatchingFileFinder.Find(files, fileNamePrefix, ".received").ToList(); GetFileNames = extension => new(extension, filePathPrefix); GetIndexedFileNames = (extension, index) => new(extension, $"{filePathPrefix}.{index:D2}"); foreach (var file in ReceivedFiles) { File.Delete(file); } VerifierSettings.RunBeforeCallbacks(); } public void Dispose() { VerifierSettings.RunAfterCallbacks(); } }
34.09434
103
0.645268
[ "MIT" ]
andrewlock/Verify
src/Verify/Verifier/InnerVerifier.cs
1,757
C#
using System.ComponentModel.DataAnnotations; namespace ParkingSystem.Data.Models { public class Car { [Required] public string CarMake { get; set; } [Required] public string PlateNumber { get; set; } } }
17.928571
47
0.621514
[ "MIT" ]
akdimitrov/CSharp-Fundamentals
11.BasicWebProject/ParkingSystem/Data/Models/Car.cs
253
C#
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Threading.Tasks; using Windows.Data.Json; using Windows.Storage; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Media.Imaging; // The data model defined by this file serves as a representative example of a strongly-typed // model. The property names chosen coincide with data bindings in the standard item templates. // // Applications may use this model as a starting point and build on it, or discard it entirely and // replace it with something appropriate to their needs. If using this model, you might improve app // responsiveness by initiating the data loading task in the code behind for App.xaml when the app // is first launched. namespace StarterMobile.WPA81.Data { /// <summary> /// Generic item data model. /// </summary> public class SampleDataItem { public SampleDataItem(String uniqueId, String title, String subtitle, String imagePath, String description, String content) { this.UniqueId = uniqueId; this.Title = title; this.Subtitle = subtitle; this.Description = description; this.ImagePath = imagePath; this.Content = content; } public string UniqueId { get; private set; } public string Title { get; private set; } public string Subtitle { get; private set; } public string Description { get; private set; } public string ImagePath { get; private set; } public string Content { get; private set; } public override string ToString() { return this.Title; } } /// <summary> /// Generic group data model. /// </summary> public class SampleDataGroup { public SampleDataGroup(String uniqueId, String title, String subtitle, String imagePath, String description) { this.UniqueId = uniqueId; this.Title = title; this.Subtitle = subtitle; this.Description = description; this.ImagePath = imagePath; this.Items = new ObservableCollection<SampleDataItem>(); } public string UniqueId { get; private set; } public string Title { get; private set; } public string Subtitle { get; private set; } public string Description { get; private set; } public string ImagePath { get; private set; } public ObservableCollection<SampleDataItem> Items { get; private set; } public override string ToString() { return this.Title; } } /// <summary> /// Creates a collection of groups and items with content read from a static json file. /// /// SampleDataSource initializes with data read from a static json file included in the /// project. This provides sample data at both design-time and run-time. /// </summary> public sealed class SampleDataSource { private static SampleDataSource _sampleDataSource = new SampleDataSource(); private ObservableCollection<SampleDataGroup> _groups = new ObservableCollection<SampleDataGroup>(); public ObservableCollection<SampleDataGroup> Groups { get { return this._groups; } } public static async Task<IEnumerable<SampleDataGroup>> GetGroupsAsync() { await _sampleDataSource.GetSampleDataAsync(); return _sampleDataSource.Groups; } public static async Task<SampleDataGroup> GetGroupAsync(string uniqueId) { await _sampleDataSource.GetSampleDataAsync(); // Simple linear search is acceptable for small data sets var matches = _sampleDataSource.Groups.Where((group) => group.UniqueId.Equals(uniqueId)); if (matches.Count() == 1) return matches.First(); return null; } public static async Task<SampleDataItem> GetItemAsync(string uniqueId) { await _sampleDataSource.GetSampleDataAsync(); // Simple linear search is acceptable for small data sets var matches = _sampleDataSource.Groups.SelectMany(group => group.Items).Where((item) => item.UniqueId.Equals(uniqueId)); if (matches.Count() == 1) return matches.First(); return null; } private async Task GetSampleDataAsync() { if (this._groups.Count != 0) return; Uri dataUri = new Uri("ms-appx:///DataModel/SampleData.json"); StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(dataUri); string jsonText = await FileIO.ReadTextAsync(file); JsonObject jsonObject = JsonObject.Parse(jsonText); JsonArray jsonArray = jsonObject["Groups"].GetArray(); foreach (JsonValue groupValue in jsonArray) { JsonObject groupObject = groupValue.GetObject(); SampleDataGroup group = new SampleDataGroup(groupObject["UniqueId"].GetString(), groupObject["Title"].GetString(), groupObject["Subtitle"].GetString(), groupObject["ImagePath"].GetString(), groupObject["Description"].GetString()); foreach (JsonValue itemValue in groupObject["Items"].GetArray()) { JsonObject itemObject = itemValue.GetObject(); group.Items.Add(new SampleDataItem(itemObject["UniqueId"].GetString(), itemObject["Title"].GetString(), itemObject["Subtitle"].GetString(), itemObject["ImagePath"].GetString(), itemObject["Description"].GetString(), itemObject["Content"].GetString())); } this.Groups.Add(group); } } } }
41.339869
132
0.587984
[ "MIT" ]
ghuntley/starter-mobile
src/StarterMobile.WPA81/DataModel/SampleDataSource.cs
6,327
C#
using System; using System.Collections.Generic; using System.Text; namespace OpenCvSharp.CPlusPlus { #if LANG_JP /// <summary> /// GrabCutの処理フラグ /// </summary> #else /// <summary> /// GrabCut algorithm flags /// </summary> #endif [Flags] public enum GrabCutFlag : int { #if LANG_JP /// <summary> /// 与えられた矩形を用いて,状態とマスクを初期化します. /// その後,アルゴリズムが iterCount 回繰り返されます. /// [GC_INIT_WITH_RECT] /// </summary> #else /// <summary> /// The function initializes the state and the mask using the provided rectangle. /// After that it runs iterCount iterations of the algorithm. /// [GC_INIT_WITH_RECT] /// </summary> #endif InitWithRect = CppConst.GC_INIT_WITH_RECT, #if LANG_JP /// <summary> /// 与えられたマスクを用いて状態を初期化します. /// GC_INIT_WITH_RECT と GC_INIT_WITH_MASK は,一緒に使うことができる /// ことに注意してください.そして,ROIの外側の全ピクセルは自動的に /// GC_BGD として初期化されます. /// [GC_INIT_WITH_MASK] /// </summary> #else /// <summary> /// The function initializes the state using the provided mask. /// Note that GC_INIT_WITH_RECT and GC_INIT_WITH_MASK can be combined. /// Then, all the pixels outside of the ROI are automatically initialized with GC_BGD . /// [GC_INIT_WITH_MASK] /// </summary> #endif InitWithMask = CppConst.GC_INIT_WITH_MASK, #if LANG_JP /// <summary> /// アルゴリズムがすぐに再開することを意味する値. /// [GC_EVAL] /// </summary> #else /// <summary> /// The value means that the algorithm should just resume. /// [GC_EVAL] /// </summary> #endif Rows = CppConst.GC_EVAL, } }
25.720588
95
0.587764
[ "BSD-3-Clause" ]
0sv/opencvsharp
src/OpenCvSharp.CPlusPlus/modules/imgproc/Enum/GrabCutFlag.cs
2,055
C#
// // Copyright 2015 Blu Age Corporation - Plano, Texas // // 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. // This file has been modified. // Original copyright notice : /* * Copyright 2006-2013 the original author or authors. * * 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.Runtime.Serialization; namespace Summer.Batch.Infrastructure.Item { /// <summary> /// Exception representing any errors encountered while processing a stream. /// </summary> [Serializable] public class ItemStreamException : Exception { /// <summary> /// Constructs a new <see cref="ItemStreamException"/> with the specified message. /// </summary> /// <param name="message">The error message.</param> public ItemStreamException(string message) : base(message) { } /// <summary> /// Constructs a new <see cref="ItemStreamException"/> with the specified message and inner exception. /// </summary> /// <param name="message">The error message.</param> /// <param name="cause">The cause of the error.</param> public ItemStreamException(string message, Exception cause) : base(message, cause) { } /// <summary> /// Constructs a new <see cref="ItemStreamException"/> with the specified inner exception. /// </summary> /// <param name="cause">The cause of the error.</param> public ItemStreamException(Exception cause) : base(string.Empty, cause) { } /// <summary> /// Constructor for deserialization. /// </summary> /// <param name="info">the info holding the serialization data</param> /// <param name="context">the serialization context</param> protected ItemStreamException(SerializationInfo info, StreamingContext context) : base(info, context) { } } }
40.915493
113
0.67883
[ "Apache-2.0" ]
SummerBatch/SummerBatchCore
Summer.Batch.Infrastructure/Item/ItemStreamException.cs
2,907
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated from a template. // // Manual changes to this file may cause unexpected behavior in your application. // Manual changes to this file will be overwritten if the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace EmpowerBusiness { using System; public partial class CMS_Man_Select_AdjusterAssignmentAttributes_Result { public int AdjusterID { get; set; } public byte Frequency { get; set; } public bool IsEnglishSpeaking { get; set; } public bool IsSpanishSpeaking { get; set; } public bool BI { get; set; } public bool PD { get; set; } public bool OTC { get; set; } public bool COL { get; set; } public bool PIP { get; set; } public bool MED { get; set; } public bool UBI { get; set; } public bool UPD { get; set; } public bool TOW { get; set; } public bool RNT { get; set; } public bool isActive { get; set; } public Nullable<int> AISID { get; set; } public string AdjusterLic { get; set; } public System.DateTime IssueDate { get; set; } public System.DateTime AdjusterLicExp { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public int MgrUserSysID { get; set; } public string MgrUserID { get; set; } public string PhoneNumber { get; set; } public int AdjusterTeamId { get; set; } public string TeamName { get; set; } } }
38.954545
85
0.549008
[ "Apache-2.0" ]
HaloImageEngine/EmpowerClaim-hotfix-1.25.1
EmpowerBusiness/CMS_Man_Select_AdjusterAssignmentAttributes_Result.cs
1,714
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("Circular PictureBox Example")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Circular PictureBox Example")] [assembly: AssemblyCopyright("Copyright © 2019 - 2020")] [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("fa42f8ee-32f9-4027-84c1-6018f0b641dc")] // 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("5.460.371.0")] [assembly: AssemblyFileVersion("5.460.371.0")]
38.837838
84
0.75087
[ "BSD-3-Clause" ]
Wagnerp/Krypton-Toolkit-Suite-Extended-NET-5.460
Source/Krypton Toolkit Suite Extended Demos/Circular PictureBox Example/Properties/AssemblyInfo.cs
1,440
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Net; using System.Text.RegularExpressions; using AutoRest.Core.Model; using AutoRest.Core.Utilities; namespace AutoRest.Python.Model { public class MethodPy : Method { public MethodPy() { Url.OnGet += value => { foreach (Match m in Regex.Matches(value, @"\{[\w]+:[\w]+\}")) { var formatter = m.Value.Split(':').First() + '}'; value = value.Replace(m.Value, formatter); } return value; }; } public bool AddCustomHeader => true; public string OperationName { get; set; } public IEnumerable<ParameterPy> ParameterTemplateModels => Parameters.Cast<ParameterPy>(); public bool IsStreamResponse => this.ReturnType.Body.IsPrimaryType(KnownPrimaryType.Stream); public bool IsStreamRequestBody => LocalParameters.Any(parameter => parameter.Location == ParameterLocation.Body && parameter.ModelType.IsPrimaryType(KnownPrimaryType.Stream)); public bool IsFormData => LocalParameters.Any(parameter => parameter.Location == ParameterLocation.FormData); /// <summary> /// Get the predicate to determine of the http operation status code indicates success /// </summary> public string FailureStatusCodePredicate { get { if (Responses.Any()) { List<string> predicates = new List<string>(); foreach (var responseStatus in Responses.Keys) { predicates.Add(((int)responseStatus).ToString(CultureInfo.InvariantCulture)); } return string.Format(CultureInfo.InvariantCulture, "response.status_code not in [{0}]", string.Join(", ", predicates)); } return "response.status_code < 200 or response.status_code >= 300"; } } public virtual bool NeedsCallback { get { if (IsStreamResponse || IsStreamRequestBody) { return true; } else { return false; } } } public virtual string ExceptionDocumentation { get { IModelType body = DefaultResponse.Body; if (body == null) { return ":class:`HttpOperationError<msrest.exceptions.HttpOperationError>`"; } else { //TODO: Namespace handling is already done on CodeModelPy var modelNamespace = CodeModel.Name.ToPythonCase(); if (!CodeModel.Namespace.IsNullOrEmpty()) modelNamespace = CodeModel.Namespace; CompositeType compType = body as CompositeType; if (compType != null) { return string.Format(CultureInfo.InvariantCulture, ":class:`{0}<{1}.models.{0}>`", compType.GetExceptionDefineType(), modelNamespace.ToLower()); } else { return ":class:`HttpOperationError<msrest.exceptions.HttpOperationError>`"; } } } } public virtual string RaisedException { get { IModelType body = DefaultResponse.Body; if (body == null) { return "raise HttpOperationError(self._deserialize, response)"; } else { CompositeType compType = body as CompositeType; if (compType != null) { return string.Format(CultureInfo.InvariantCulture, "raise models.{0}(self._deserialize, response)", compType.GetExceptionDefineType()); } else { return string.Format(CultureInfo.InvariantCulture, "raise HttpOperationError(self._deserialize, response, '{0}')", body.ToPythonRuntimeTypeString()); } } } } /// <summary> /// Generate the method parameter declarations for a method /// </summary> /// <param name="addCustomHeaderParameters">If true add the customHeader to the parameters</param> /// <returns>Generated string of parameters</returns> public virtual string MethodParameterDeclaration(bool addCustomHeaderParameters) { List<string> declarations = new List<string>(); List<string> requiredDeclarations = new List<string>(); List<string> combinedDeclarations = new List<string>(); foreach (var parameter in DocumentationParameters) { if (parameter.IsRequired && parameter.DefaultValue.RawValue.IsNullOrEmpty()) { requiredDeclarations.Add(parameter.Name); } else { declarations.Add(string.Format( CultureInfo.InvariantCulture, "{0}={1}", parameter.Name, parameter.DefaultValue)); } } if (addCustomHeaderParameters) { declarations.Add("custom_headers=None"); } declarations.Add("raw=False"); if (this.NeedsCallback) { declarations.Add("callback=None"); } declarations.Add("**operation_config"); if (requiredDeclarations.Any()) { combinedDeclarations.Add(string.Join(", ", requiredDeclarations)); } combinedDeclarations.Add(string.Join(", ", declarations)); return string.Join(", ", combinedDeclarations); } private string BuildSerializeDataCall(Parameter parameter, string functionName) { string divChar = ClientModelExtensions.NeedsFormattedSeparator(parameter); string divParameter = string.Empty; string parameterName = (MethodGroup as MethodGroupPy)?.ConstantProperties?.FirstOrDefault(each => each.Name.RawValue == parameter.Name.RawValue && each.DefaultValue.RawValue == parameter.DefaultValue.RawValue)?.Name.Else(parameter.Name) ?? parameter.Name; if (!string.IsNullOrEmpty(divChar)) { divParameter = string.Format(CultureInfo.InvariantCulture, ", div='{0}'", divChar); } //TODO: This creates a very long line - break it up over multiple lines. return string.Format(CultureInfo.InvariantCulture, "self._serialize.{0}(\"{1}\", {1}, '{2}'{3}{4}{5})", functionName, parameterName, parameter.ModelType.ToPythonRuntimeTypeString(), parameter.SkipUrlEncoding() ? ", skip_quote=True" : string.Empty, divParameter, BuildValidationParameters(parameter.Constraints)); } private static string BuildValidationParameters(Dictionary<Constraint, string> constraints) { List<string> validators = new List<string>(); foreach (var constraint in constraints.Keys) { switch (constraint) { case Constraint.ExclusiveMaximum: validators.Add(string.Format(CultureInfo.InvariantCulture, "maximum_ex={0}", constraints[constraint])); break; case Constraint.ExclusiveMinimum: validators.Add(string.Format(CultureInfo.InvariantCulture, "minimum_ex={0}", constraints[constraint])); break; case Constraint.InclusiveMaximum: validators.Add(string.Format(CultureInfo.InvariantCulture, "maximum={0}", constraints[constraint])); break; case Constraint.InclusiveMinimum: validators.Add(string.Format(CultureInfo.InvariantCulture, "minimum={0}", constraints[constraint])); break; case Constraint.MaxItems: validators.Add(string.Format(CultureInfo.InvariantCulture, "max_items={0}", constraints[constraint])); break; case Constraint.MaxLength: validators.Add(string.Format(CultureInfo.InvariantCulture, "max_length={0}", constraints[constraint])); break; case Constraint.MinItems: validators.Add(string.Format(CultureInfo.InvariantCulture, "min_items={0}", constraints[constraint])); break; case Constraint.MinLength: validators.Add(string.Format(CultureInfo.InvariantCulture, "min_length={0}", constraints[constraint])); break; case Constraint.MultipleOf: validators.Add(string.Format(CultureInfo.InvariantCulture, "multiple={0}", constraints[constraint])); break; case Constraint.Pattern: validators.Add(string.Format(CultureInfo.InvariantCulture, "pattern='{0}'", constraints[constraint])); break; case Constraint.UniqueItems: var pythonBool = Convert.ToBoolean(constraints[constraint], CultureInfo.InvariantCulture) ? "True" : "False"; validators.Add(string.Format(CultureInfo.InvariantCulture, "unique={0}", pythonBool)); break; default: throw new NotSupportedException("Constraint '" + constraint + "' is not supported."); } } if (!validators.Any()) { return string.Empty; } return ", " + string.Join(", ", validators); } /// <summary> /// Generate code to build the URL from a url expression and method parameters /// </summary> /// <param name="variableName">The variable to store the url in.</param> /// <param name="pathParameters">The list of parameters for url construction.</param> /// <returns></returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "Microsoft.Rest.Generator.Utilities.IndentedStringBuilder.AppendLine(System.String)"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "pathformatarguments"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1055:UriReturnValuesShouldNotBeStrings")] public virtual string BuildUrlPath(string variableName, IEnumerable<Parameter> pathParameters) { var builder = new IndentedStringBuilder(" "); if (pathParameters == null) return builder.ToString(); var pathParameterList = pathParameters.Where(p => p.Location == ParameterLocation.Path).ToList(); if (pathParameterList.Any()) { builder.AppendLine("path_format_arguments = {").Indent(); for (int i = 0; i < pathParameterList.Count; i++) { builder.AppendLine("'{0}': {1}{2}{3}", pathParameterList[i].SerializedName, BuildSerializeDataCall(pathParameterList[i], "url"), pathParameterList[i].IsRequired ? string.Empty : string.Format(CultureInfo.InvariantCulture, "if {0} else ''", pathParameterList[i].Name), i == pathParameterList.Count - 1 ? "" : ","); } builder.Outdent().AppendLine("}"); builder.AppendLine("{0} = self._client.format_url({0}, **path_format_arguments)", variableName); } return builder.ToString(); } /// <summary> /// Generate code to build the query of URL from method parameters /// </summary> /// <param name="variableName">The variable to store the query in.</param> /// <param name="queryParameters">The list of parameters for url construction.</param> /// <returns></returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1055:UriReturnValuesShouldNotBeStrings")] public virtual string BuildUrlQuery(string variableName, IEnumerable<Parameter> queryParameters) { var builder = new IndentedStringBuilder(" "); if (queryParameters == null) return builder.ToString(); foreach (var queryParameter in queryParameters.Where(p => p.Location == ParameterLocation.Query)) { if (queryParameter.IsRequired) { builder.AppendLine("{0}['{1}'] = {2}", variableName, queryParameter.SerializedName, BuildSerializeDataCall(queryParameter, "query")); } else { builder.AppendLine("if {0} is not None:", queryParameter.Name) .Indent() .AppendLine("{0}['{1}'] = {2}", variableName, queryParameter.SerializedName, BuildSerializeDataCall(queryParameter, "query")) .Outdent(); } } return builder.ToString(); } /// <summary> /// Generate code to build the headers from method parameters /// </summary> /// <param name="variableName">The variable to store the headers in.</param> /// <returns></returns> public virtual string BuildHeaders(string variableName) { var builder = new IndentedStringBuilder(" "); foreach (var headerParameter in this.LogicalParameters.Where(p => p.Location == ParameterLocation.Header)) { if (headerParameter.IsRequired) { builder.AppendLine("{0}['{1}'] = {2}", variableName, headerParameter.SerializedName, BuildSerializeDataCall(headerParameter, "header")); } else { builder.AppendLine("if {0} is not None:", headerParameter.Name) .Indent() .AppendLine("{0}['{1}'] = {2}", variableName, headerParameter.SerializedName, BuildSerializeDataCall(headerParameter, "header")) .Outdent(); } } return builder.ToString(); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "addheaders"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "ClientRawResponse"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "clientrawresponse"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "AutoRest.Core.Utilities.IndentedStringBuilder.AppendLine(System.String)")] public virtual string ReturnEmptyResponse { get { var builder = new IndentedStringBuilder(" "); builder.AppendLine("if raw:").Indent(). AppendLine("client_raw_response = ClientRawResponse(None, response)"); if (this.ReturnType.Headers != null) { builder.AppendLine("client_raw_response.add_headers({").Indent(); AddHeaderDictionary(builder, (CompositeType)ReturnType.Headers); builder.Outdent().AppendLine("})"); } builder.AppendLine("return client_raw_response"). Outdent(); return builder.ToString(); } } public bool HasResponseHeader { get { if (this.ReturnType.Headers != null || this.Responses.Any(r => r.Value.Headers != null)) { return true; } else { return false; } } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "AutoRest.Core.Utilities.IndentedStringBuilder.AppendLine(System.String)"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "addheaders"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "headerdict"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "clientrawresponse")] public virtual string AddResponseHeader() { if (HasResponseHeader) { var builder = new IndentedStringBuilder(" "); builder.AppendLine("client_raw_response.add_headers(header_dict)"); return builder.ToString(); } else { return string.Empty; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "AutoRest.Core.Utilities.IndentedStringBuilder.AppendLine(System.String)")] protected void AddHeaderDictionary(IndentedStringBuilder builder, CompositeType headersType) { if (builder == null) { throw new ArgumentNullException("builder"); } if (headersType == null) { throw new ArgumentNullException("headersType"); } foreach (var prop in headersType.Properties) { var enumType = prop.ModelType as EnumType; if (CodeModel.EnumTypes.Contains(prop.ModelType) && !enumType.ModelAsString) { builder.AppendLine(String.Format(CultureInfo.InvariantCulture, "'{0}': models.{1},", prop.SerializedName, prop.ModelType.ToPythonRuntimeTypeString())); } else { builder.AppendLine(String.Format(CultureInfo.InvariantCulture, "'{0}': '{1}',", prop.SerializedName, prop.ModelType.ToPythonRuntimeTypeString())); } } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "AutoRest.Core.Utilities.IndentedStringBuilder.AppendLine(System.String)"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "headerdict")] public virtual string AddIndividualResponseHeader(HttpStatusCode? code) { IModelType headersType = null; if (HasResponseHeader) { if (code != null) { headersType = this.ReturnType.Headers; } else { headersType = this.Responses[code.Value].Headers; } } var builder = new IndentedStringBuilder(" "); if (headersType == null) { if (code == null) { builder.AppendLine("header_dict = {}"); } else { return string.Empty; } } else { builder.AppendLine("header_dict = {").Indent(); AddHeaderDictionary(builder, (CompositeType)headersType); builder.Outdent().AppendLine("}"); } return builder.ToString(); } /// <summary> /// Get the parameters that are actually method parameters in the order they appear in the method signature /// exclude global parameters /// </summary> public IEnumerable<ParameterPy> LocalParameters { get { return ParameterTemplateModels.Where( p => p != null && !p.IsClientProperty && !string.IsNullOrWhiteSpace(p.Name)) .OrderBy(item => !item.IsRequired); } } public IEnumerable<ParameterPy> DocumentationParameters { get { return this.LocalParameters.Where(p => !p.IsConstant); } } public IEnumerable<ParameterPy> ConstantParameters { get { var constantParameters = LocalParameters.Where(p => p.IsConstant && !p.Name.StartsWith("self.")); if (!constantParameters.Any()) { return constantParameters; } var m = MethodGroup as MethodGroupPy; if (m?.ConstantProperties != null) { if (!m.ConstantProperties.Any()) { return constantParameters; } return constantParameters.Where(parameter => !m.ConstantProperties.Any(constantProperty => constantProperty.Name.RawValue == parameter.Name.RawValue && constantProperty.DefaultValue.Value == parameter.DefaultValue.Value) ); } return constantParameters; } } /// <summary> /// Provides the parameter documentation string. /// </summary> /// <param name="parameter">Parameter to be documented</param> /// <returns>Parameter documentation string correct notation</returns> public static string GetParameterDocumentationString(Parameter parameter) { if (parameter == null) { throw new ArgumentNullException("parameter"); } string docString = ":param "; docString += parameter.Name + ":"; if (!string.IsNullOrWhiteSpace(parameter.Documentation)) { docString += " " + parameter.Documentation; } return docString; } /// <summary> /// Get the type name for the method's return type /// </summary> public string ReturnTypeString { get { if (ReturnType.Body != null) { return ReturnType.Body.Name; } return "null"; } } public string GetReturnTypeDocumentation(IModelType type) { return (type as IExtendedModelTypePy)?.ReturnTypeDocumentation ?? PythonConstants.None; } public string GetDocumentationType(IModelType type) { return (type as IExtendedModelTypePy)?.TypeDocumentation ?? PythonConstants.None; } /// <summary> /// Get the method's request body (or null if there is no request body) /// </summary> public ParameterPy RequestBody => Body as ParameterPy; public static string GetStatusCodeReference(HttpStatusCode code) { return string.Format(CultureInfo.InvariantCulture, "{0}", (int)code); } private static string BuildNullCheckExpression(ParameterTransformation transformation) { if (transformation == null) { throw new ArgumentNullException("transformation"); } return string.Join(" or ", transformation.ParameterMappings.Select(m => string.Format(CultureInfo.InvariantCulture, "{0} is not None", m.InputParameter.Name))); } /// <summary> /// Generates input mapping code block. /// </summary> /// <returns></returns> public virtual string BuildInputMappings() { var builder = new IndentedStringBuilder(" "); foreach (var transformation in InputParameterTransformation) { if (transformation.ParameterMappings.Any(m => !string.IsNullOrEmpty(m.OutputParameterProperty)) && transformation.OutputParameter.ModelType is CompositeType) { var comps = CodeModel.ModelTypes.Where(x => x.Name == transformation.OutputParameter.ModelTypeName); var composite = comps.First(); List<string> combinedParams = new List<string>(); List<string> paramCheck = new List<string>(); foreach (var mapping in transformation.ParameterMappings) { // var mappedParams = composite.ComposedProperties.Where(x => x.Name.RawValue == mapping.InputParameter.Name.RawValue); var mappedParams = composite.ComposedProperties.Where(x => x.Name == mapping.InputParameter.Name); if (mappedParams.Any()) { var param = mappedParams.First(); combinedParams.Add(string.Format(CultureInfo.InvariantCulture, "{0}={0}", param.Name)); paramCheck.Add(string.Format(CultureInfo.InvariantCulture, "{0} is not None", param.Name)); } } if (!transformation.OutputParameter.IsRequired) { builder.AppendLine("{0} = None", transformation.OutputParameter.Name); builder.AppendLine("if {0}:", string.Join(" or ", paramCheck)).Indent(); } builder.AppendLine("{0} = models.{1}({2})", transformation.OutputParameter.Name, transformation.OutputParameter.ModelType.Name, string.Join(", ", combinedParams)); } else { builder.AppendLine("{0} = None", transformation.OutputParameter.Name); builder.AppendLine("if {0}:", BuildNullCheckExpression(transformation)) .Indent(); foreach (var mapping in transformation.ParameterMappings) { builder.AppendLine("{0}{1}", transformation.OutputParameter.Name, mapping); } builder.Outdent(); } } return builder.ToString(); } /// <summary> /// Gets the expression for default header setting. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "headerparameters"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "AutoRest.Core.Utilities.IndentedStringBuilder.AppendLine(System.String)"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "customheaders")] public virtual string SetDefaultHeaders { get { if (this.AddCustomHeader) { var sb = new IndentedStringBuilder(); sb.AppendLine("if custom_headers:").Indent().AppendLine("header_parameters.update(custom_headers)").Outdent(); return sb.ToString(); } else { return string.Empty; } } } public static string GetHttpFunction(HttpMethod method) { switch (method) { case HttpMethod.Delete: return "delete"; case HttpMethod.Get: return "get"; case HttpMethod.Head: return "head"; case HttpMethod.Patch: return "patch"; case HttpMethod.Post: return "post"; case HttpMethod.Put: return "put"; default: throw new ArgumentException(String.Format(CultureInfo.InvariantCulture, "wrong method {0}", method)); } } public bool HasAnyResponse { get { if (Responses.Where(r => r.Value.Body != null).Any()) { return true; } return false; } } public string ReturnTypeInfo { get { string result = null; IModelType body = ReturnType.Body; EnumType enumType = body as EnumType; if (enumType != null) { string enumValues = ""; for (var i = 0; i < enumType.Values.Count; i++) { if (i == enumType.Values.Count - 1) { enumValues += enumType.Values[i].SerializedName; } else { enumValues += enumType.Values[i].SerializedName + ", "; } } result = string.Format(CultureInfo.InvariantCulture, "Possible values for result are - {0}.", enumValues); } else if (body is CompositeType) { result = string.Format(CultureInfo.InvariantCulture, "See {{@link {0}}} for more information.", ReturnTypeString); } return result; } } public string BuildSummaryAndDescriptionString() { return CodeGeneratorPy.BuildSummaryAndDescriptionString(this.Summary, this.Description); } } }
42.70596
666
0.527277
[ "MIT" ]
yugangw-msft/AutoRest
src/generator/AutoRest.Python/Model/MethodPy.cs
32,245
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace ModelTools.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "14.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.444444
151
0.581221
[ "MIT" ]
paulcalcraft/jms-weight-injector
Properties/Settings.Designer.cs
1,067
C#
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="Game.MenuString.cs"> // Copyright (c) Nathan Bowman. All rights reserved. // Licensed under the MIT License. See LICENSE file in the project root for full license information. // </copyright> // --------------------------------------------------------------------------------------------------------------------
68.428571
121
0.329854
[ "MIT" ]
NateBowman/Blackjack
Blackjack/Game/Game.MenuString.cs
481
C#
using System.IO; using DeltaEngine.Content; using DeltaEngine.Datatypes; using SharpDX; using SharpDX.DXGI; using SharpDX.Direct3D11; using MapFlags = SharpDX.Direct3D11.MapFlags; using Resource = SharpDX.Direct3D11.Resource; namespace DeltaEngine.Graphics.SharpDX { /// <summary> /// Images under SharpDX. /// </summary> public class SharpDXImage : Image { protected SharpDXImage(string contentName, SharpDXDevice device) : base(contentName) { this.device = device; } private SharpDXImage(ImageCreationData data, SharpDXDevice device) : base(data) { this.device = device; } private readonly SharpDXDevice device; protected override void SetSamplerStateAndTryToLoadImage(Stream fileData) { DisposeData(); LoadImage(fileData); SetSamplerState(); } protected override void TryLoadImage(Stream fileData) { NativeTexture = (Texture2D)Resource.FromStream(device.NativeDevice, fileData, (int)fileData.Length); WarnAboutWrongAlphaFormat(NativeTexture.Description.Format == Format.R8G8B8A8_UNorm); var textureSize = new Size(NativeTexture.Description.Width, NativeTexture.Description.Height); CompareActualSizeMetadataSize(textureSize); } public Texture2D NativeTexture { get; protected set; } public override void FillRgbaData(byte[] rgbaColors) { if (PixelSize.Width * PixelSize.Height * 4 != rgbaColors.Length) throw new InvalidNumberOfBytes(PixelSize); if (NativeTexture == null) CreateNewDynamicTexture(); DataStream subResource; device.Context.MapSubresource(NativeTexture, 0, MapMode.WriteDiscard, MapFlags.None, out subResource); subResource.Write(rgbaColors, 0, rgbaColors.Length); device.Context.UnmapSubresource(NativeTexture, 0); } private void CreateNewDynamicTexture() { var description = new Texture2DDescription { Width = (int)PixelSize.Width, Height = (int)PixelSize.Height, ArraySize = 1, MipLevels = 1, Format = Format.R8G8B8A8_UNorm, Usage = ResourceUsage.Dynamic, CpuAccessFlags = CpuAccessFlags.Write, BindFlags = BindFlags.ShaderResource, SampleDescription = new SampleDescription(1, 0), }; NativeTexture = new Texture2D(device.NativeDevice, description); SetSamplerState(); } protected override void SetSamplerState() { NativeResourceView = new ShaderResourceView(device.NativeDevice, NativeTexture); } public ShaderResourceView NativeResourceView { get; protected set; } protected override void DisposeData() { if (NativeResourceView != null) NativeResourceView.Dispose(); if (NativeTexture != null) NativeTexture.Dispose(); } } }
28.926316
98
0.717977
[ "Apache-2.0" ]
DeltaEngine/DeltaEngine.SharpDX
Graphics/SharpDX/SharpDXImage.cs
2,750
C#
/* * Copyright (c) Dominick Baier, Brock Allen. All rights reserved. * see license */ using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Collections.Specialized; using Thinktecture.IdentityServer.Core; using Thinktecture.IdentityServer.Core.Services; using UnitTests.Plumbing; namespace UnitTests { [TestClass] public class Authorize_ProtocolValidation_Valid { ILogger _logger = new DebugLogger(); [TestMethod] [TestCategory("AuthorizeRequest Protocol Validation - Valid")] public void Valid_OpenId_Code_Request() { var parameters = new NameValueCollection(); parameters.Add(Constants.AuthorizeRequest.ClientId, "client"); parameters.Add(Constants.AuthorizeRequest.Scope, "openid"); parameters.Add(Constants.AuthorizeRequest.RedirectUri, "https://server/callback"); parameters.Add(Constants.AuthorizeRequest.ResponseType, Constants.ResponseTypes.Code); var validator = Factory.CreateAuthorizeValidator(); var result = validator.ValidateProtocol(parameters); Assert.AreEqual(false, result.IsError); } [TestMethod] [TestCategory("AuthorizeRequest Protocol Validation - Valid")] public void Valid_Resource_Code_Request() { var parameters = new NameValueCollection(); parameters.Add(Constants.AuthorizeRequest.ClientId, "client"); parameters.Add(Constants.AuthorizeRequest.Scope, "resource"); parameters.Add(Constants.AuthorizeRequest.RedirectUri, "https://server/callback"); parameters.Add(Constants.AuthorizeRequest.ResponseType, Constants.ResponseTypes.Code); var validator = Factory.CreateAuthorizeValidator(); var result = validator.ValidateProtocol(parameters); Assert.IsFalse(result.IsError); } [TestMethod] [TestCategory("AuthorizeRequest Protocol Validation - Valid")] public void Valid_Mixed_Code_Request() { var parameters = new NameValueCollection(); parameters.Add(Constants.AuthorizeRequest.ClientId, "client"); parameters.Add(Constants.AuthorizeRequest.Scope, "openid resource"); parameters.Add(Constants.AuthorizeRequest.RedirectUri, "https://server/callback"); parameters.Add(Constants.AuthorizeRequest.ResponseType, Constants.ResponseTypes.Code); var validator = Factory.CreateAuthorizeValidator(); var result = validator.ValidateProtocol(parameters); Assert.IsFalse(result.IsError); } [TestMethod] [TestCategory("AuthorizeRequest Protocol Validation - Valid")] public void Valid_Resource_Token_Request() { var parameters = new NameValueCollection(); parameters.Add(Constants.AuthorizeRequest.ClientId, "client"); parameters.Add(Constants.AuthorizeRequest.Scope, "resource"); parameters.Add(Constants.AuthorizeRequest.RedirectUri, "https://server/callback"); parameters.Add(Constants.AuthorizeRequest.ResponseType, Constants.ResponseTypes.Token); var validator = Factory.CreateAuthorizeValidator(); var result = validator.ValidateProtocol(parameters); Assert.IsFalse(result.IsError); } [TestMethod] [TestCategory("AuthorizeRequest Protocol Validation - Valid")] public void Valid_OpenId_IdToken_Request() { var parameters = new NameValueCollection(); parameters.Add(Constants.AuthorizeRequest.ClientId, "client"); parameters.Add(Constants.AuthorizeRequest.Scope, "openid"); parameters.Add(Constants.AuthorizeRequest.RedirectUri, "https://server/callback"); parameters.Add(Constants.AuthorizeRequest.ResponseType, Constants.ResponseTypes.IdToken); parameters.Add(Constants.AuthorizeRequest.Nonce, "abc"); var validator = Factory.CreateAuthorizeValidator(); var result = validator.ValidateProtocol(parameters); Assert.IsFalse(result.IsError); } [TestMethod] [TestCategory("AuthorizeRequest Protocol Validation - Valid")] // is valid because protocol validation on its own cannot know about resource scopes public void Valid_Mixed_IdToken_Request() { var parameters = new NameValueCollection(); parameters.Add(Constants.AuthorizeRequest.ClientId, "client"); parameters.Add(Constants.AuthorizeRequest.Scope, "openid resource"); parameters.Add(Constants.AuthorizeRequest.RedirectUri, "https://server/callback"); parameters.Add(Constants.AuthorizeRequest.ResponseType, Constants.ResponseTypes.IdToken); parameters.Add(Constants.AuthorizeRequest.Nonce, "abc"); var validator = Factory.CreateAuthorizeValidator(); var result = validator.ValidateProtocol(parameters); Assert.IsFalse(result.IsError); } [TestMethod] [TestCategory("AuthorizeRequest Protocol Validation - Valid")] public void Valid_OpenId_IdTokenToken_Request() { var parameters = new NameValueCollection(); parameters.Add(Constants.AuthorizeRequest.ClientId, "client"); parameters.Add(Constants.AuthorizeRequest.Scope, Constants.StandardScopes.OpenId); parameters.Add(Constants.AuthorizeRequest.RedirectUri, "https://server/callback"); parameters.Add(Constants.AuthorizeRequest.ResponseType, Constants.ResponseTypes.IdTokenToken); parameters.Add(Constants.AuthorizeRequest.Nonce, "abc"); var validator = Factory.CreateAuthorizeValidator(); var result = validator.ValidateProtocol(parameters); Assert.IsFalse(result.IsError); } [TestMethod] [TestCategory("AuthorizeRequest Protocol Validation - Valid")] public void Valid_Mixed_IdTokenToken_Request() { var parameters = new NameValueCollection(); parameters.Add(Constants.AuthorizeRequest.ClientId, "client"); parameters.Add(Constants.AuthorizeRequest.Scope, "openid resource"); parameters.Add(Constants.AuthorizeRequest.RedirectUri, "https://server/callback"); parameters.Add(Constants.AuthorizeRequest.ResponseType, Constants.ResponseTypes.IdTokenToken); parameters.Add(Constants.AuthorizeRequest.Nonce, "abc"); var validator = Factory.CreateAuthorizeValidator(); var result = validator.ValidateProtocol(parameters); Assert.IsFalse(result.IsError); } [TestMethod] [TestCategory("AuthorizeRequest Protocol Validation - Valid")] public void Valid_OpenId_IdToken_With_FormPost_ResponseMode_Request() { var parameters = new NameValueCollection(); parameters.Add(Constants.AuthorizeRequest.ClientId, "client"); parameters.Add(Constants.AuthorizeRequest.Scope, Constants.StandardScopes.OpenId); parameters.Add(Constants.AuthorizeRequest.RedirectUri, "https://server/callback"); parameters.Add(Constants.AuthorizeRequest.ResponseType, Constants.ResponseTypes.IdToken); parameters.Add(Constants.AuthorizeRequest.ResponseMode, Constants.ResponseModes.FormPost); parameters.Add(Constants.AuthorizeRequest.Nonce, "abc"); var validator = Factory.CreateAuthorizeValidator(); var result = validator.ValidateProtocol(parameters); Assert.IsFalse(result.IsError); } [TestMethod] [TestCategory("AuthorizeRequest Protocol Validation - Valid")] public void Valid_OpenId_IdToken_Token_With_FormPost_ResponseMode_Request() { var parameters = new NameValueCollection(); parameters.Add(Constants.AuthorizeRequest.ClientId, "client"); parameters.Add(Constants.AuthorizeRequest.Scope, "openid resource"); parameters.Add(Constants.AuthorizeRequest.RedirectUri, "https://server/callback"); parameters.Add(Constants.AuthorizeRequest.ResponseType, Constants.ResponseTypes.IdTokenToken); parameters.Add(Constants.AuthorizeRequest.ResponseMode, Constants.ResponseModes.FormPost); parameters.Add(Constants.AuthorizeRequest.Nonce, "abc"); var validator = Factory.CreateAuthorizeValidator(); var result = validator.ValidateProtocol(parameters); Assert.IsFalse(result.IsError); } } }
46.55615
106
0.682977
[ "BSD-3-Clause" ]
dmorosinotto/Thinktecture.IdentityServer.v3
source/Tests/UnitTests/Validation Tests/AuthorizeRequest Validation/Authorize_ProtocolValidation_Valid.cs
8,708
C#
/* * SimScale API * * The version of the OpenAPI document: 0.0.0 * * Generated by: https://github.com/openapitools/openapi-generator.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using OpenAPIDateConverter = SimScale.Sdk.Client.OpenAPIDateConverter; namespace SimScale.Sdk.Model { /// <summary> /// SolidElementTechnology /// </summary> [DataContract] public partial class SolidElementTechnology : IEquatable<SolidElementTechnology> { /// <summary> /// Initializes a new instance of the <see cref="SolidElementTechnology" /> class. /// </summary> /// <param name="elementTechnology3D">elementTechnology3D.</param> public SolidElementTechnology(ElementTechnology elementTechnology3D = default(ElementTechnology)) { this.ElementTechnology3D = elementTechnology3D; } /// <summary> /// Gets or Sets ElementTechnology3D /// </summary> [DataMember(Name="elementTechnology3D", EmitDefaultValue=false)] public ElementTechnology ElementTechnology3D { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class SolidElementTechnology {\n"); sb.Append(" ElementTechnology3D: ").Append(ElementTechnology3D).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public virtual string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as SolidElementTechnology); } /// <summary> /// Returns true if SolidElementTechnology instances are equal /// </summary> /// <param name="input">Instance of SolidElementTechnology to be compared</param> /// <returns>Boolean</returns> public bool Equals(SolidElementTechnology input) { if (input == null) return false; return ( this.ElementTechnology3D == input.ElementTechnology3D || (this.ElementTechnology3D != null && this.ElementTechnology3D.Equals(input.ElementTechnology3D)) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.ElementTechnology3D != null) hashCode = hashCode * 59 + this.ElementTechnology3D.GetHashCode(); return hashCode; } } } }
31.850877
105
0.593225
[ "MIT" ]
SimScaleGmbH/simscale-csharp-sdk
src/SimScale.Sdk/Model/SolidElementTechnology.cs
3,631
C#
using System.Collections.Generic; using Essensoft.Paylink.Alipay.Response; namespace Essensoft.Paylink.Alipay.Request { /// <summary> /// alipay.iservice.ccm.agent.query /// </summary> public class AlipayIserviceCcmAgentQueryRequest : IAlipayRequest<AlipayIserviceCcmAgentQueryResponse> { /// <summary> /// 客服查询接口 /// </summary> public string BizContent { get; set; } #region IAlipayRequest Members private bool needEncrypt = false; private string apiVersion = "1.0"; private string terminalType; private string terminalInfo; private string prodCode; private string notifyUrl; private string returnUrl; private AlipayObject bizModel; private Dictionary<string, string> udfParams; //add user-defined text parameters public void SetNeedEncrypt(bool needEncrypt) { this.needEncrypt = needEncrypt; } public bool GetNeedEncrypt() { return needEncrypt; } public void SetNotifyUrl(string notifyUrl) { this.notifyUrl = notifyUrl; } public string GetNotifyUrl() { return notifyUrl; } public void SetReturnUrl(string returnUrl) { this.returnUrl = returnUrl; } public string GetReturnUrl() { return returnUrl; } public void SetTerminalType(string terminalType) { this.terminalType = terminalType; } public string GetTerminalType() { return terminalType; } public void SetTerminalInfo(string terminalInfo) { this.terminalInfo = terminalInfo; } public string GetTerminalInfo() { return terminalInfo; } public void SetProdCode(string prodCode) { this.prodCode = prodCode; } public string GetProdCode() { return prodCode; } public string GetApiName() { return "alipay.iservice.ccm.agent.query"; } public void SetApiVersion(string apiVersion) { this.apiVersion = apiVersion; } public string GetApiVersion() { return apiVersion; } public void PutOtherTextParam(string key, string value) { if (udfParams == null) { udfParams = new Dictionary<string, string>(); } udfParams.Add(key, value); } public IDictionary<string, string> GetParameters() { var parameters = new AlipayDictionary { { "biz_content", BizContent } }; if (udfParams != null) { parameters.AddAll(udfParams); } return parameters; } public AlipayObject GetBizModel() { return bizModel; } public void SetBizModel(AlipayObject bizModel) { this.bizModel = bizModel; } #endregion } }
23.427536
105
0.537272
[ "MIT" ]
Frunck8206/payment
src/Essensoft.Paylink.Alipay/Request/AlipayIserviceCcmAgentQueryRequest.cs
3,247
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("DotnetWebApiDemo.Infra.CrossCutting")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("DotnetWebApiDemo.Infra.CrossCutting")] [assembly: AssemblyCopyright("Copyright © 2018")] [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("6294ba4a-0f76-4abb-9a79-60ba6d964816")] // 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")]
38.864865
84
0.753129
[ "MIT" ]
rodrigo-campero/DotnetWebApiDemo
src/DotnetWebApiDemo.Infra.CrossCutting/Properties/AssemblyInfo.cs
1,441
C#
using System; using System.Linq; using BenchmarkDotNet.Attributes; using FluentAssertions; using Super.Model.Selection; using Super.Model.Sequences; using Super.Testing.Objects; using Xunit; namespace Super.Testing.Application.Model.Sequences { public sealed class ArraysTests { public class Benchmarks { readonly uint[] _source; readonly ISelect<Store<uint>, uint[]> _sut; public Benchmarks() : this(Near.Default) {} public Benchmarks(Super.Model.Sequences.Selection selection) : this(new Arrays<uint>(selection), FixtureInstance.Default .Many<uint>(10_000) .Get() .ToArray()) {} public Benchmarks(ISelect<Store<uint>, uint[]> sut, uint[] source) { _sut = sut; _source = source; } [Benchmark] public Array Measure() => _sut.Get(_source); } [Fact] void Verify() { var expected = Enumerable.Range(0, 10_000).ToArray(); Arrays<int>.Default.Get(expected) .Should() .Equal(expected); } [Fact] void VerifySelection() { var source = Enumerable.Range(0, 10_000).ToArray(); var expected = source.Skip(1000).Take(250).ToArray(); Arrays<int>.Default.Get(expected) .Should() .Equal(expected); } } }
23.614035
69
0.606984
[ "MIT" ]
SuperDotNet/Super.NET
Super.Testing.Application/Model/Sequences/ArraysTests.cs
1,348
C#
// Copyright (c) MOSA Project. Licensed under the New BSD License. // This code was generated by an automated template. namespace Mosa.Compiler.Framework.IR { /// <summary> /// ConvertR8ToI32 /// </summary> /// <seealso cref="Mosa.Compiler.Framework.IR.BaseIRInstruction" /> public sealed class ConvertR8ToI32 : BaseIRInstruction { public ConvertR8ToI32() : base(1, 1) { } } }
20.789474
68
0.698734
[ "BSD-3-Clause" ]
AnErrupTion/MOSA-Project
Source/Mosa.Compiler.Framework/IR/ConvertR8ToI32.cs
395
C#
using MissingLinq; using NUnit.Framework; namespace MissingLinqTests { [TestFixture] public class ConcatenationExtensionTests { [Test] public void Prepend_single() { Assert.That( new[] {5, 6, 10, 1}.Prepend(500), Is.EquivalentTo(new[] {500, 5, 6, 10, 1})); } [Test] public void Prepend_list() { Assert.That( new[] {1, 3, 17, -1}.Prepend(1, 3, -1), Is.EquivalentTo(new[] {1, 3, -1, 1, 3, 17, -1})); } [Test] public void Append_single() { Assert.That( new[] {-15, 8, 10, -15}.Append(-15), Is.EquivalentTo(new[] {-15, 8, 10, -15, -15})); } [Test] public void Append_list() { Assert.That( new[] {-10, 3, 5}.Append(new[] {1, 5, 5}), Is.EquivalentTo(new[] {-10, 3, 5, 1, 5, 5})); } } }
24.487805
65
0.426295
[ "Apache-2.0" ]
jayotterbein/MissingLinq
MissingLinqTests/ConcatenationExtensionTests.cs
1,006
C#
/**************************************************************************** * Copyright (c) 2020.10 liangxie * * https://qframework.cn * https://github.com/liangxiegame/QFramework * https://gitee.com/liangxiegame/QFramework * * 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 UnityEngine; namespace QFramework { public class OpenRegisterWebsiteCommand : AbstractCommand { protected override void OnExecute() { Application.OpenURL("https://qframework.cn/user/register"); } } }
43.289474
80
0.669909
[ "MIT" ]
JiYangJi/QFramework
Unity2018Main/Assets/QFramework/Framework/Plugins/Editor/PackageKit/Login/Command/OpenRegisterWebsiteCommand.cs
1,647
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by \generate-code.bat. // // Changes to this file will be lost when the code is regenerated. // The build server regenerates the code before each build and a pre-build // step will regenerate the code on each local build. // // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. // Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. // Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. // // </auto-generated> //------------------------------------------------------------------------------ // Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). // https://github.com/angularsen/UnitsNet // // 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.Collections.Generic; using System.Globalization; using System.Text.RegularExpressions; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; // ReSharper disable once CheckNamespace namespace UnitsNet { /// <summary> /// A temperature is a numerical measure of hot or cold. Its measurement is by detection of heat radiation or particle velocity or kinetic energy, or by the bulk behavior of a thermometric material. It may be calibrated in any of various temperature scales, Celsius, Fahrenheit, Kelvin, etc. The fundamental physical definition of temperature is provided by thermodynamics. /// </summary> // ReSharper disable once PartialTypeWithSinglePart public partial struct Temperature : IComparable, IComparable<Temperature> { /// <summary> /// The numeric value this quantity was constructed with. /// </summary> public double Value => _value; #region Nullable From Methods /// <summary> /// Get nullable Temperature from nullable DegreesCelsius. /// </summary> [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] public static Temperature? FromDegreesCelsius(QuantityValue? degreescelsius) { return degreescelsius.HasValue ? FromDegreesCelsius(degreescelsius.Value) : default(Temperature?); } /// <summary> /// Get nullable Temperature from nullable DegreesDelisle. /// </summary> [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] public static Temperature? FromDegreesDelisle(QuantityValue? degreesdelisle) { return degreesdelisle.HasValue ? FromDegreesDelisle(degreesdelisle.Value) : default(Temperature?); } /// <summary> /// Get nullable Temperature from nullable DegreesFahrenheit. /// </summary> [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] public static Temperature? FromDegreesFahrenheit(QuantityValue? degreesfahrenheit) { return degreesfahrenheit.HasValue ? FromDegreesFahrenheit(degreesfahrenheit.Value) : default(Temperature?); } /// <summary> /// Get nullable Temperature from nullable DegreesNewton. /// </summary> [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] public static Temperature? FromDegreesNewton(QuantityValue? degreesnewton) { return degreesnewton.HasValue ? FromDegreesNewton(degreesnewton.Value) : default(Temperature?); } /// <summary> /// Get nullable Temperature from nullable DegreesRankine. /// </summary> [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] public static Temperature? FromDegreesRankine(QuantityValue? degreesrankine) { return degreesrankine.HasValue ? FromDegreesRankine(degreesrankine.Value) : default(Temperature?); } /// <summary> /// Get nullable Temperature from nullable DegreesReaumur. /// </summary> [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] public static Temperature? FromDegreesReaumur(QuantityValue? degreesreaumur) { return degreesreaumur.HasValue ? FromDegreesReaumur(degreesreaumur.Value) : default(Temperature?); } /// <summary> /// Get nullable Temperature from nullable DegreesRoemer. /// </summary> [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] public static Temperature? FromDegreesRoemer(QuantityValue? degreesroemer) { return degreesroemer.HasValue ? FromDegreesRoemer(degreesroemer.Value) : default(Temperature?); } /// <summary> /// Get nullable Temperature from nullable Kelvins. /// </summary> [Obsolete("Nullable type support is obsolete and will be removed in a future release.")] public static Temperature? FromKelvins(QuantityValue? kelvins) { return kelvins.HasValue ? FromKelvins(kelvins.Value) : default(Temperature?); } /// <summary> /// Dynamically convert from value and unit enum <see cref="TemperatureUnit" /> to <see cref="Temperature" />. /// </summary> /// <param name="value">Value to convert from.</param> /// <param name="fromUnit">Unit to convert from.</param> /// <returns>Temperature unit value.</returns> [Obsolete("Nullable type support has been deprecated and will be removed in a future release.")] public static Temperature? From(QuantityValue? value, TemperatureUnit fromUnit) { return value.HasValue ? new Temperature((double)value.Value, fromUnit) : default(Temperature?); } #endregion /// <summary> /// Get unit abbreviation string. /// </summary> /// <param name="unit">Unit to get abbreviation for.</param> /// <param name="provider">Format to use for localization. Defaults to <see cref="UnitSystem.DefaultCulture" />.</param> /// <returns>Unit abbreviation string.</returns> [UsedImplicitly] public static string GetAbbreviation(TemperatureUnit unit, [CanBeNull] IFormatProvider provider) { provider = provider ?? UnitSystem.DefaultCulture; return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); } public static bool operator <=(Temperature left, Temperature right) { return left.Value <= right.AsBaseNumericType(left.Unit); } public static bool operator >=(Temperature left, Temperature right) { return left.Value >= right.AsBaseNumericType(left.Unit); } public static bool operator <(Temperature left, Temperature right) { return left.Value < right.AsBaseNumericType(left.Unit); } public static bool operator >(Temperature left, Temperature right) { return left.Value > right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator ==(Temperature left, Temperature right) { // ReSharper disable once CompareOfFloatsByEqualityOperator return left.Value == right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator !=(Temperature left, Temperature right) { // ReSharper disable once CompareOfFloatsByEqualityOperator return left.Value != right.AsBaseNumericType(left.Unit); } #region Parsing /// <summary> /// Parse a string with one or two quantities of the format "&lt;quantity&gt; &lt;unit&gt;". /// </summary> /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="UnitSystem.DefaultCulture" />.</param> /// <example> /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// </example> /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> /// <exception cref="ArgumentException"> /// Expected string to have one or two pairs of quantity and unit in the format /// "&lt;quantity&gt; &lt;unit&gt;". Eg. "5.5 m" or "1ft 2in" /// </exception> /// <exception cref="AmbiguousUnitParseException"> /// More than one unit is represented by the specified unit abbreviation. /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. /// </exception> /// <exception cref="UnitsNetException"> /// If anything else goes wrong, typically due to a bug or unhandled case. /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish /// Units.NET exceptions from other exceptions. /// </exception> public static Temperature Parse(string str, [CanBeNull] IFormatProvider provider) { if (str == null) throw new ArgumentNullException(nameof(str)); provider = provider ?? UnitSystem.DefaultCulture; return QuantityParser.Parse<Temperature, TemperatureUnit>(str, provider, delegate(string value, string unit, IFormatProvider formatProvider2) { double parsedValue = double.Parse(value, formatProvider2); TemperatureUnit parsedUnit = ParseUnit(unit, formatProvider2); return From(parsedValue, parsedUnit); }, (x, y) => FromKelvins(x.Kelvins + y.Kelvins)); } /// <summary> /// Try to parse a string with one or two quantities of the format "&lt;quantity&gt; &lt;unit&gt;". /// </summary> /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="UnitSystem.DefaultCulture" />.</param> /// <param name="result">Resulting unit quantity if successful.</param> /// <example> /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// </example> public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out Temperature result) { provider = provider ?? UnitSystem.DefaultCulture; try { result = Parse(str, provider); return true; } catch { result = default(Temperature); return false; } } /// <summary> /// Parse a unit string. /// </summary> /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> /// <param name="cultureName">Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to <see cref="UnitSystem" />'s default culture.</param> /// <example> /// Length.ParseUnit("m", new CultureInfo("en-US")); /// </example> /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> /// <exception cref="UnitsNetException">Error parsing string.</exception> [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from .NET Framework targets.")] public static TemperatureUnit ParseUnit(string str, [CanBeNull] string cultureName) { return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); } /// <summary> /// Parse a unit string. /// </summary> /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="UnitSystem.DefaultCulture" />.</param> /// <example> /// Length.ParseUnit("m", new CultureInfo("en-US")); /// </example> /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> /// <exception cref="UnitsNetException">Error parsing string.</exception> public static TemperatureUnit ParseUnit(string str, IFormatProvider provider = null) { if (str == null) throw new ArgumentNullException(nameof(str)); var unitSystem = UnitSystem.GetCached(provider); var unit = unitSystem.Parse<TemperatureUnit>(str.Trim()); if (unit == TemperatureUnit.Undefined) { var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized TemperatureUnit."); newEx.Data["input"] = str; newEx.Data["provider"] = provider?.ToString() ?? "(null)"; throw newEx; } return unit; } #endregion #region ToString Methods /// <summary> /// Get string representation of value and unit. Using two significant digits after radix. /// </summary> /// <param name="unit">Unit representation to use.</param> /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="UnitSystem.DefaultCulture" />.</param> /// <returns>String representation.</returns> public string ToString(TemperatureUnit unit, [CanBeNull] IFormatProvider provider) { return ToString(unit, provider, 2); } /// <summary> /// Get string representation of value and unit. /// </summary> /// <param name="unit">Unit representation to use.</param> /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="UnitSystem.DefaultCulture" />.</param> /// <param name="significantDigitsAfterRadix">The number of significant digits after the radix point.</param> /// <returns>String representation.</returns> [UsedImplicitly] public string ToString(TemperatureUnit unit, [CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix) { double value = As(unit); string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); return ToString(unit, provider, format); } /// <summary> /// Get string representation of value and unit. /// </summary> /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="UnitSystem.DefaultCulture" />.</param> /// <param name="unit">Unit representation to use.</param> /// <param name="format">String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively."</param> /// <param name="args">Arguments for string format. Value and unit are implictly included as arguments 0 and 1.</param> /// <returns>String representation.</returns> [UsedImplicitly] public string ToString(TemperatureUnit unit, [CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); provider = provider ?? UnitSystem.DefaultCulture; double value = As(unit); object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion } }
49.480663
381
0.639292
[ "MIT" ]
ajf2/UnitsNet
UnitsNet/GeneratedCode/Quantities/Temperature.NetFramework.g.cs
17,914
C#
using System.Threading.Tasks; using PlaywrightSharp.Tests.BaseTests; using Xunit; using Xunit.Abstractions; namespace PlaywrightSharp.Tests.BrowserContext { /// <playwright-file>cookies.spec.js</playwright-file> /// <playwright-describe>BrowserContext.setCookies</playwright-describe> public class SetCookiesTests : PlaywrightSharpPageBaseTest { internal SetCookiesTests(ITestOutputHelper output) : base(output) { } /// <playwright-file>cookies.spec.js</playwright-file> /// <playwright-describe>BrowserContext.setCookies</playwright-describe> /// <playwright-it>should work</playwright-it> [Fact] public async Task ShouldWork() { await Page.GoToAsync(TestConstants.EmptyPage); await Context.SetCookiesAsync(new SetNetworkCookieParam { Url = TestConstants.EmptyPage, Name = "password", Value = "123456" }); Assert.Equal("password=123456", await Page.EvaluateAsync<string>("document.cookie")); } /// <playwright-file>cookies.spec.js</playwright-file> /// <playwright-describe>BrowserContext.setCookies</playwright-describe> /// <playwright-it>should isolate cookies in browser contexts</playwright-it> [Fact] public async Task ShouldIsolateCookiesInBrowserContexts() { var anotherContext = await NewContextAsync(); await Context.SetCookiesAsync(new SetNetworkCookieParam { Name = "page1cookie", Value = "page1value", Url = TestConstants.EmptyPage }); await anotherContext.SetCookiesAsync(new SetNetworkCookieParam { Name = "page2cookie", Value = "page2value", Url = TestConstants.EmptyPage }); var cookies1 = await Context.GetCookiesAsync(); var cookies2 = await anotherContext.GetCookiesAsync(); Assert.Single(cookies1); Assert.Single(cookies2); Assert.Equal("page1cookie", cookies1[0].Name); Assert.Equal("page1value", cookies1[0].Value); Assert.Equal("page2cookie", cookies2[0].Name); Assert.Equal("page2value", cookies2[0].Value); } /// <playwright-file>cookies.spec.js</playwright-file> /// <playwright-describe>BrowserContext.setCookies</playwright-describe> /// <playwright-it>should set multiple cookies</playwright-it> [Fact] public async Task ShouldSetMultipleCookies() { await Page.GoToAsync(TestConstants.EmptyPage); await Context.SetCookiesAsync( new SetNetworkCookieParam { Url = TestConstants.EmptyPage, Name = "password", Value = "123456" }, new SetNetworkCookieParam { Url = TestConstants.EmptyPage, Name = "foo", Value = "bar" } ); Assert.Equal( new[] { "foo=bar", "password=123456" }, await Page.EvaluateAsync<string[]>(@"() => { const cookies = document.cookie.split(';'); return cookies.map(cookie => cookie.trim()).sort(); }") ); } /// <playwright-file>cookies.spec.js</playwright-file> /// <playwright-describe>BrowserContext.setCookies</playwright-describe> /// <playwright-it>should have |expires| set to |-1| for session cookies</playwright-it> [Fact] public async Task ShouldHaveExpiresSetToMinus1ForSessionCookies() { await Context.SetCookiesAsync(new SetNetworkCookieParam { Url = TestConstants.EmptyPage, Name = "password", Value = "123456" }); var cookies = await Context.GetCookiesAsync(); Assert.True(cookies[0].Session); Assert.Equal(-1, cookies[0].Expires); } /// <playwright-file>cookies.spec.js</playwright-file> /// <playwright-describe>BrowserContext.setCookies</playwright-describe> /// <playwright-it>should set cookie with reasonable defaults</playwright-it> [Fact] public async Task ShouldSetCookieWithReasonableDefaults() { await Context.SetCookiesAsync(new SetNetworkCookieParam { Url = TestConstants.EmptyPage, Name = "password", Value = "123456" }); var cookie = Assert.Single(await Context.GetCookiesAsync()); Assert.Equal("password", cookie.Name); Assert.Equal("123456", cookie.Value); Assert.Equal("localhost", cookie.Domain); Assert.Equal("/", cookie.Path); Assert.Equal(-1, cookie.Expires); Assert.False(cookie.HttpOnly); Assert.False(cookie.Secure); Assert.True(cookie.Session); Assert.Equal(SameSite.None, cookie.SameSite); } /// <playwright-file>cookies.spec.js</playwright-file> /// <playwright-describe>BrowserContext.setCookies</playwright-describe> /// <playwright-it>should set a cookie with a path</playwright-it> [Fact] public async Task ShouldSetACookieWithAPath() { await Page.GoToAsync(TestConstants.ServerUrl + "/grid.html"); await Context.SetCookiesAsync(new SetNetworkCookieParam { Domain = "localhost", Path = "/grid.html", Name = "gridcookie", Value = "GRID" }); var cookie = Assert.Single(await Context.GetCookiesAsync()); Assert.Equal("gridcookie", cookie.Name); Assert.Equal("GRID", cookie.Value); Assert.Equal("localhost", cookie.Domain); Assert.Equal("/grid.html", cookie.Path); Assert.Equal(cookie.Expires, -1); Assert.False(cookie.HttpOnly); Assert.False(cookie.Secure); Assert.True(cookie.Session); Assert.Equal(SameSite.None, cookie.SameSite); Assert.Equal("gridcookie=GRID", await Page.EvaluateAsync<string>("document.cookie")); await Page.GoToAsync(TestConstants.EmptyPage); Assert.Empty(await Page.EvaluateAsync<string>("document.cookie")); await Page.GoToAsync(TestConstants.ServerUrl + "/grid.html"); Assert.Equal("gridcookie=GRID", await Page.EvaluateAsync<string>("document.cookie")); } /// <playwright-file>cookies.spec.js</playwright-file> /// <playwright-describe>BrowserContext.setCookies</playwright-describe> /// <playwright-it>should not set a cookie with blank page URL</playwright-it> [Fact] public async Task ShouldNotSetACookieWithBlankPageURL() { await Page.GoToAsync(TestConstants.AboutBlank); var exception = await Assert.ThrowsAsync<PlaywrightSharpException>(async () => await Context.SetCookiesAsync( new SetNetworkCookieParam { Url = TestConstants.EmptyPage, Name = "example-cookie", Value = "best" }, new SetNetworkCookieParam { Url = "about:blank", Name = "example-cookie", Value = "best" })); Assert.Equal("Blank page can not have cookie \"example-cookie-blank\"", exception.Message); } /// <playwright-file>cookies.spec.js</playwright-file> /// <playwright-describe>BrowserContext.setCookies</playwright-describe> /// <playwright-it>should not set a cookie on a data URL page</playwright-it> [Fact] public async Task ShouldNotSetACookieOnADataURLPage() { await Page.GoToAsync("data:,Hello%2C%20World!"); var exception = await Assert.ThrowsAnyAsync<PlaywrightSharpException>(async () => await Context.SetCookiesAsync( new SetNetworkCookieParam { Url = "data:,Hello%2C%20World!", Name = "example-cookie", Value = "best" })); Assert.Equal("Data URL page can not have cookie \"example-cookie\"", exception.Message); } /// <playwright-file>cookies.spec.js</playwright-file> /// <playwright-describe>BrowserContext.setCookies</playwright-describe> /// <playwright-it>should default to setting secure cookie for HTTPS websites</playwright-it> [Fact] public async Task ShouldDefaultToSettingSecureCookieForHttpsWebsites() { await Page.GoToAsync(TestConstants.EmptyPage); string SecureUrl = "https://example.com"; await Context.SetCookiesAsync(new SetNetworkCookieParam { Url = SecureUrl, Name = "foo", Value = "bar" }); var cookie = Assert.Single(await Context.GetCookiesAsync(SecureUrl)); Assert.True(cookie.Secure); } /// <playwright-file>cookies.spec.js</playwright-file> /// <playwright-describe>BrowserContext.setCookies</playwright-describe> /// <playwright-it>should be able to set unsecure cookie for HTTP website</playwright-it> [Fact] public async Task ShouldBeAbleToSetUnsecureCookieForHttpWebSite() { await Page.GoToAsync(TestConstants.EmptyPage); string SecureUrl = "http://example.com"; await Context.SetCookiesAsync(new SetNetworkCookieParam { Url = SecureUrl, Name = "foo", Value = "bar" }); var cookie = Assert.Single(await Context.GetCookiesAsync(SecureUrl)); Assert.False(cookie.Secure); } /// <playwright-file>cookies.spec.js</playwright-file> /// <playwright-describe>BrowserContext.setCookies</playwright-describe> /// <playwright-it>should set a cookie on a different domain</playwright-it> [Fact] public async Task ShouldSetACookieOnADifferentDomain() { await Page.GoToAsync(TestConstants.ServerUrl + "/grid.html"); await Context.SetCookiesAsync(new SetNetworkCookieParam { Name = "example-cookie", Value = "best", Url = "https://www.example.com" }); Assert.Equal(string.Empty, await Page.EvaluateAsync<string>("document.cookie")); Assert.Empty(await Context.GetCookiesAsync()); var cookie = Assert.Single(await Context.GetCookiesAsync("https://www.example.com")); Assert.Equal("example-cookie", cookie.Name); Assert.Equal("best", cookie.Value); Assert.Equal("www.example.com", cookie.Domain); Assert.Equal("/", cookie.Path); Assert.Equal(cookie.Expires, -1); Assert.False(cookie.HttpOnly); Assert.True(cookie.Secure); Assert.True(cookie.Session); } /// <playwright-file>cookies.spec.js</playwright-file> /// <playwright-describe>BrowserContext.setCookies</playwright-describe> /// <playwright-it>sshould set cookies from a frame</playwright-it> [Fact] public async Task ShouldSetCookiesFromAFrame() { await Page.GoToAsync(TestConstants.ServerUrl + "/grid.html"); await Context.SetCookiesAsync( new SetNetworkCookieParam { Url = TestConstants.ServerUrl, Name = "localhost-cookie", Value = "best" }, new SetNetworkCookieParam { Url = TestConstants.CrossProcessUrl, Name = "127-cookie", Value = "worst" }); await Page.EvaluateAsync(@"src => { let fulfill; const promise = new Promise(x => fulfill = x); const iframe = document.createElement('iframe'); document.body.appendChild(iframe); iframe.onload = fulfill; iframe.src = src; return promise; }", TestConstants.CrossProcessHttpPrefix); Assert.Equal("localhost-cookie=best", await Page.EvaluateAsync<string>("document.cookie")); Assert.Equal("127-cookie=worst", await Page.FirstChildFrame().EvaluateAsync<string>("document.cookie")); var cookie = Assert.Single(await Context.GetCookiesAsync()); Assert.Equal("localhost-cookie", cookie.Name); Assert.Equal("best", cookie.Value); Assert.Equal("localhost", cookie.Domain); Assert.Equal("/", cookie.Path); Assert.Equal(cookie.Expires, -1); Assert.False(cookie.HttpOnly); Assert.False(cookie.Secure); Assert.True(cookie.Session); Assert.Equal(SameSite.None, cookie.SameSite); cookie = Assert.Single(await Context.GetCookiesAsync(TestConstants.CrossProcessHttpPrefix)); Assert.Equal("127-cookie", cookie.Name); Assert.Equal("worst", cookie.Value); Assert.Equal("127.0.0.1", cookie.Domain); Assert.Equal("/", cookie.Path); Assert.Equal(cookie.Expires, -1); Assert.False(cookie.HttpOnly); Assert.False(cookie.Secure); Assert.True(cookie.Session); Assert.Equal(SameSite.None, cookie.SameSite); } } }
43.094955
147
0.552641
[ "MIT" ]
slang25/playwright-sharp
src/PlaywrightSharp.Tests/BrowserContext/SetCookiesTests.cs
14,523
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Immutable; using System.Diagnostics; using System.Threading; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal sealed class SubstitutedEventSymbol : WrappedEventSymbol { private readonly SubstitutedNamedTypeSymbol _containingType; private TypeSymbolWithAnnotations.Builder _lazyType; internal SubstitutedEventSymbol(SubstitutedNamedTypeSymbol containingType, EventSymbol originalDefinition) : base(originalDefinition) { Debug.Assert(originalDefinition.IsDefinition); _containingType = containingType; } public override TypeSymbolWithAnnotations Type { get { if (_lazyType.IsNull) { _lazyType.InterlockedInitialize(_containingType.TypeSubstitution.SubstituteTypeWithTupleUnification(OriginalDefinition.Type)); } return _lazyType.ToType(); } } public override Symbol ContainingSymbol { get { return _containingType; } } public override EventSymbol OriginalDefinition { get { return _underlyingEvent; } } public override ImmutableArray<CSharpAttributeData> GetAttributes() { return OriginalDefinition.GetAttributes(); } public override MethodSymbol AddMethod { get { MethodSymbol originalAddMethod = OriginalDefinition.AddMethod; return (object)originalAddMethod == null ? null : originalAddMethod.AsMember(_containingType); } } public override MethodSymbol RemoveMethod { get { MethodSymbol originalRemoveMethod = OriginalDefinition.RemoveMethod; return (object)originalRemoveMethod == null ? null : originalRemoveMethod.AsMember(_containingType); } } internal override FieldSymbol AssociatedField { get { FieldSymbol originalAssociatedField = OriginalDefinition.AssociatedField; return (object)originalAssociatedField == null ? null : originalAssociatedField.AsMember(_containingType); } } internal override bool IsExplicitInterfaceImplementation { get { return OriginalDefinition.IsExplicitInterfaceImplementation; } } //we want to compute this lazily since it may be expensive for the underlying symbol private ImmutableArray<EventSymbol> _lazyExplicitInterfaceImplementations; private OverriddenOrHiddenMembersResult _lazyOverriddenOrHiddenMembers; public override ImmutableArray<EventSymbol> ExplicitInterfaceImplementations { get { if (_lazyExplicitInterfaceImplementations.IsDefault) { ImmutableInterlocked.InterlockedCompareExchange( ref _lazyExplicitInterfaceImplementations, ExplicitInterfaceHelpers.SubstituteExplicitInterfaceImplementations(OriginalDefinition.ExplicitInterfaceImplementations, _containingType.TypeSubstitution), default(ImmutableArray<EventSymbol>)); } return _lazyExplicitInterfaceImplementations; } } internal override bool MustCallMethodsDirectly { get { return OriginalDefinition.MustCallMethodsDirectly; } } internal override OverriddenOrHiddenMembersResult OverriddenOrHiddenMembers { get { if (_lazyOverriddenOrHiddenMembers == null) { Interlocked.CompareExchange(ref _lazyOverriddenOrHiddenMembers, this.MakeOverriddenOrHiddenMembers(), null); } return _lazyOverriddenOrHiddenMembers; } } public override bool IsWindowsRuntimeEvent { get { // A substituted event computes overriding and interface implementation separately // from the original definition, in case the type has changed. However, is should // never be the case that providing type arguments changes a WinRT event to a // non-WinRT event or vice versa, so we'll delegate to the original definition. return OriginalDefinition.IsWindowsRuntimeEvent; } } } }
35.246377
179
0.617804
[ "Apache-2.0" ]
Ashera138/roslyn
src/Compilers/CSharp/Portable/Symbols/SubstitutedEventSymbol.cs
4,866
C#
using System; using System.Diagnostics; using System.IO; using System.Linq; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using NUnit.Framework; using QboxNext.Core.Extensions; using QboxNext.Core.Utils; using QboxNext.Logging; using QboxNext.Model.Classes; using QboxNext.Qserver.Core.Statistics; namespace QboxNext.Storage.Qbx { [TestFixture] [NonParallelizable] public class KWhStorageTest { private const string BaseDir = @"./Temp/KWhStorageTest"; private StorageProviderContext _dataStorageContext; private IOptions<kWhStorageOptions> _options; [SetUp] public void SetUp() { // Setup static logger factory QboxNextLogProvider.LoggerFactory = new LoggerFactory(); if (Directory.Exists(BaseDir)) { Directory.Delete(BaseDir, true); } Directory.CreateDirectory(BaseDir); _options = new OptionsWrapper<kWhStorageOptions>(new kWhStorageOptions { DataStorePath = BaseDir }); _dataStorageContext = new StorageProviderContext { SerialNumber = "Serial", CounterId = 15, Precision = Precision.Wh }; } [TearDown] public void TearDown() { Directory.Delete(BaseDir, true); } /// <summary> ///A test for SetValue ///</summary> [Test] public void SetValueShouldCreateAFileInTempTest() { using (var target = new kWhStorage(new LoggerFactory(), _options, _dataStorageContext)) { var measureTime = DateTime.Now; // act target.SetValue(measureTime, 5, 5, 5); } // assert Assert.IsTrue(File.Exists(GetTestPath($"Qbox_Serial/Serial_{_dataStorageContext.CounterId:00000000}.qbx"))); } /// <summary> ///A test for SetValue ///</summary> [Test] public void SetValueShouldCreateAFileWithStorageidFilenameInTempTest() { _dataStorageContext.StorageId = "MyStorageid-counterid"; using (var target = new kWhStorage(new LoggerFactory(), _options, _dataStorageContext)) { var measureTime = DateTime.Now; // act target.SetValue(measureTime, 5, 5, 5); } // assert Assert.IsTrue(File.Exists(GetTestPath("Qbox_Serial/MyStorageid-counterid.qbx"))); } /// <summary> ///A test for SetValue ///</summary> [Test] public void SetValueShouldWriteTheRecordToFileAtOffsetTest() { // arrange string testPath = GetTestPath($"Qbox_Serial/Serial_{_dataStorageContext.CounterId:00000000}.qbx"); var measureTime = DateTime.Now; // act using (var target = new kWhStorage(new LoggerFactory(), _options, _dataStorageContext)) { target.SetValue(measureTime, 25, 50, 15); } // assert Assert.IsTrue(File.Exists(testPath)); const int offset = 32; using (var reader = new BinaryReader(File.OpenRead(testPath))) { reader.BaseStream.Seek(offset, SeekOrigin.Begin); Assert.AreEqual(25, reader.ReadUInt64()); Assert.AreEqual((ulong)(25m / 50m * 1000m), reader.ReadUInt64()); Assert.AreEqual((ulong)(25m / 50m * 1000 * 15), reader.ReadUInt64()); Assert.AreEqual((ulong)0, reader.ReadUInt16()); Assert.AreEqual(ulong.MaxValue, reader.ReadUInt64()); Assert.AreEqual(0, reader.ReadUInt64()); Assert.AreEqual(0, reader.ReadUInt64()); Assert.AreEqual((ulong)0, reader.ReadUInt16()); } } [Test] [Category("Integration")] public void SetValueShouldReturnSecondTimeWithin5MsTest() { var watch = new Stopwatch(); DateTime measureTime = DateTime.Now; using (var target = new kWhStorage(new LoggerFactory(), _options, _dataStorageContext)) { // act first time with initialization target.SetValue(measureTime, 25, 50, 15); watch.Start(); // act target.SetValue(measureTime.AddMinutes(1), 25, 50, 15); // assert watch.Stop(); Console.WriteLine("elapsed: {0}", watch.ElapsedMilliseconds); Assert.IsTrue(watch.ElapsedMilliseconds < 5); } } [Test] public void SetValueShouldIncreaseTheFileSizeWithSevenDaysIfMeasureFallsBeyondTheEndOfTheFileTest() { var measureTime = DateTime.Now.AddDays(-10); var secondMeasureTime = DateTime.Now.AddDays(-1); // act using (var target = new kWhStorage(new LoggerFactory(), _options, _dataStorageContext)) { target.SetValue(measureTime, 25, 50, 15); target.SetValue(secondMeasureTime, 25, 50, 15); } using (var target = new kWhStorage(new LoggerFactory(), _options, _dataStorageContext)) { // assert Assert.That(target.StartOfFile.Equals(RoundDown(measureTime))); Assert.That(target.EndOfFile > secondMeasureTime); Assert.AreEqual((ulong)25, target.GetValue(secondMeasureTime).Raw); Assert.AreEqual(ulong.MaxValue, target.GetValue(secondMeasureTime.AddMinutes(1)).Raw); } } private static DateTime RoundDown(DateTime date) { return new DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, 0); } [Test] public void SetValueShouldIncreaseTheFileSizeWithOneYearIfMeasureIsOneMinuteBeyondTheEndOfTheFileTest() { var measureTime = new DateTime(DateTime.Today.Year - 1, 1, 1); var secondMeasureTime = new DateTime(DateTime.Today.Year, 1, 1); // act using (var target = new kWhStorage(new LoggerFactory(), _options, _dataStorageContext)) { target.SetValue(measureTime, 25, 50, 15); target.SetValue(secondMeasureTime, 25, 50, 15); } using (var target = new kWhStorage(new LoggerFactory(), _options, _dataStorageContext)) { // assert Assert.That(target.StartOfFile.Equals(RoundDown(measureTime))); Assert.AreEqual((ulong)25, target.GetValue(secondMeasureTime).Raw); } } /// <summary> ///A test for GetValue ///</summary> [Test] public void GetValueTest() { var measureTime = DateTime.Now; Record actual; using (var target = new kWhStorage(new LoggerFactory(), _options, _dataStorageContext)) { target.SetValue(measureTime, 50, 2, 3); } // act using (var target = new kWhStorage(new LoggerFactory(), _options, _dataStorageContext)) { actual = target.GetValue(measureTime); } // assert Assert.AreEqual(50, actual.Raw); Assert.AreEqual((ulong)(25), actual.KiloWattHour); // 50 / 2 Assert.AreEqual((ulong)(75), actual.Money); // 50 / 2 * 3 } [Test] public void GetValueShouldReturnNullIfTheTimeFallsOutsideTheCurrentFileRangeTest() { DateTime measureTime = DateTime.Now; Record actual; using (var target = new kWhStorage(new LoggerFactory(), _options, _dataStorageContext)) { target.SetValue(measureTime, 50, 5, 21); } // act using (var target = new kWhStorage(new LoggerFactory(), _options, _dataStorageContext)) { actual = target.GetValue(measureTime.AddMinutes(-1)); } // assert Assert.IsNull(actual); } [Test] public void GetValueShouldReturnNullIfTheTimeFallsBeyondTheCurrentFileRangeTest() { var measureTime = DateTime.Now; Record actual; using (var target = new kWhStorage(new LoggerFactory(), _options, _dataStorageContext)) { target.SetValue(measureTime, 50, 25, 15); } // act using (var target = new kWhStorage(new LoggerFactory(), _options, _dataStorageContext)) { actual = target.GetValue(measureTime.AddYears(1)); } // assert Assert.IsNull(actual); } // testen schrijven voor de gemiddelde uitvulling en de Value / Money formule [Test] public void GetValueShouldReturnTheAverageValueBetweenEmptySlotsTest() { var measureTime = DateTime.Now.AddMinutes(-15); Record actual = null; using (var target = new kWhStorage(new LoggerFactory(), _options, _dataStorageContext)) { target.SetValue(measureTime, 50, 25, 15); Console.WriteLine(target.GetValue(measureTime).Raw); target.SetValue(measureTime.AddMinutes(10), 100, 25, 15); } // act using (var target = new kWhStorage(new LoggerFactory(), _options, _dataStorageContext)) { for (var i = 0; i < 10; i++) { actual = target.GetValue(measureTime.AddMinutes(i)); Console.WriteLine("Raw: {0} | Value: {1} | Quality: {2}", actual.Raw, actual.KiloWattHour, actual.Quality); } } // assert Assert.IsNotNull(actual, "actual != null"); Assert.AreEqual(3.8m, actual.KiloWattHour); Assert.AreEqual((ushort)10000, actual.Quality); } [Test] public void QualityIndexShouldBeACertainValueBasedOnLogDistanceTest() { var intermediate = Math.Log10(5); var quality = Convert.ToUInt16(intermediate * 10000); Assert.AreEqual((ushort)6990, quality); } /// <summary> ///A test for Sum ///</summary> [Test] public void SumTest() { decimal expected; decimal actual; using (var target = new kWhStorage(new LoggerFactory(), _options, _dataStorageContext)) { target.SetValue(DateTime.Today.AddDays(-1), 50, 5, 2); target.SetValue(DateTime.Today.AddDays(-1).AddMinutes(120), 100, 5, 2); var period = PeriodBuilder.Yesterday(); var begin = period.From; var end = period.To; expected = 10000; // ((100 / 5) * 1000) - ((50 / 5) * 1000) actual = target.Sum(begin, end, Unit.kWh); } Assert.AreEqual(expected, actual); } [Test] public void GetValueShouldNotThrowExceptionWhenFileDoesNotExistTest() { // act using (var target = new kWhStorage(new LoggerFactory(), _options, _dataStorageContext)) { Record result = null; try { result = target.GetValue(DateTime.Now); // assert } catch { Assert.Fail("Should not throw"); } Assert.IsNull(result); } } [Test] public void GetRecordsShouldNotThrowWhenFileDoesNotExitTest() { // act using (var target = new kWhStorage(new LoggerFactory(), _options, _dataStorageContext)) { try { var values = SeriesValueListBuilder.BuildSeries(DateTime.Today.AddDays(-7), DateTime.Today, SeriesResolution.Day); var result = target.GetRecords(DateTime.Today.AddDays(-7), DateTime.Today, Unit.kWh, values, false); // assert Assert.IsFalse(result); Assert.AreEqual(7, values.Count); Assert.IsTrue((bool)values.TrueForAll(v => v.Value == null)); } catch { Assert.Fail("Should not throw"); } } } [Test] [Category("Integration")] public void GetRecordsShouldReturnWithinReasonableTimeWhenMeasurementsAreMissingfromTheFileTest() { // Do this twice to miss the overhead of just in time compilation. for (int i = 0; i < 2; i++) { using (var target = new kWhStorage(new LoggerFactory(), _options, _dataStorageContext)) { target.SetValue(DateTime.Now.AddDays(-8), 50, 1, 1); target.SetValue(DateTime.Now.AddDays(-7), 100, 1, 1); // act var watch = new Stopwatch(); watch.Start(); var values = SeriesValueListBuilder.BuildSeries(DateTime.Today.AddDays(-30), DateTime.Today, SeriesResolution.Day); var result = target.GetRecords(DateTime.Today.AddDays(-30), DateTime.Today, Unit.kWh, values, false); watch.Stop(); var time = watch.ElapsedMilliseconds; // assert Assert.IsNotNull(result); const int maxTime = 250; if (time < maxTime) break; if (i > 0) Assert.Less(time, maxTime); //Refactor the find algo because the file is too slow } } } [Test] public void GetSumTest() { using (var target = new kWhStorage(new LoggerFactory(), _options, _dataStorageContext)) { target.SetValue(DateTime.Now.AddDays(-8), 50, 1000, 1); target.SetValue(DateTime.Now.AddDays(-7), 100, 1000, 1); var begin = DateTime.Today.AddDays((DateTime.Today.Day - 1) * -1); var end = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month)); // act var result = target.Sum(begin, end, Unit.kWh); // assert Assert.IsNotNull(result); } } [Test] public void WhenSetValueIsCalledWithAnIntervalItShouldLevelTheValuesWrittenTest() { // arrange _dataStorageContext.SerialNumber = "Interval"; _dataStorageContext.Precision = Precision.mWh; var start = DateTime.Now.AddMinutes(-2); using (var target = new kWhStorage(new LoggerFactory(), _options, _dataStorageContext)) { // act target.SetValue(start.AddMinutes(-10), 50, 300, 1); target.SetValue(start, 99, 300, 1); target.GetValue(start); // assert Assert.AreEqual(216.667m, target.GetValue(start.AddMinutes(-7)).KiloWattHour * 1000m); Assert.AreEqual(200.0m, target.GetValue(start.AddMinutes(-8)).KiloWattHour * 1000m); Assert.AreEqual(183.334m, target.GetValue(start.AddMinutes(-9)).KiloWattHour * 1000m); Assert.AreEqual(UInt64.MaxValue, target.GetValue(start.AddMinutes(-8)).Raw); Assert.AreEqual(UInt64.MaxValue, target.GetValue(start.AddMinutes(-1)).Raw); Assert.AreEqual(UInt64.MaxValue, target.GetValue(start.AddMinutes(-9)).Raw); Assert.AreEqual(99, target.GetValue(start).Raw); Assert.AreEqual(50, target.GetValue(start.AddMinutes(-10)).Raw); } } [Test] public void WhenSetValueIsCalledWith2000AsFormulaAndAPrecisionOf10000IsShouldWriteAHalfTest() { // arrange _dataStorageContext.SerialNumber = "Interval"; _dataStorageContext.Precision = Precision.mWh; var start = DateTime.Now.AddMinutes(-2); using (var target = new kWhStorage(new LoggerFactory(), _options, _dataStorageContext)) { // act target.SetValue(start.AddMinutes(-5), 5, 2000, 1); target.SetValue(start.AddMinutes(-4), 10, 2000, 1); target.SetValue(start.AddMinutes(-3), 15, 2000, 1); target.SetValue(start.AddMinutes(-2), 25, 2000, 1); target.SetValue(start.AddMinutes(-1), 26, 2000, 1); target.SetValue(start, 31, 2000, 1); target.GetValue(start); // assert Assert.AreEqual(25, target.GetValue(start.AddMinutes(-2)).Raw); Assert.AreEqual(26, target.GetValue(start.AddMinutes(-1)).Raw); var series = SeriesValueListBuilder.BuildSeries(start.AddMinutes(-5), start, SeriesResolution.OneMinute); target.GetRecords(start.AddMinutes(-5), start, Unit.kWh, series, false); Assert.AreEqual(300, series[2].Value); Assert.AreEqual(30, series[3].Value); } } [Test] public void WhenSumIsCalledItCalculatesTheSameAsTheIndividualResolutionTest() { // arrange _dataStorageContext.SerialNumber = "Interval"; _dataStorageContext.CounterId = 2421; var start = DateTime.Today.AddDays(-14); using (var target = new kWhStorage(new LoggerFactory(), _options, _dataStorageContext)) { var totalMinutes = (ulong)(DateTime.Now - start).TotalMinutes; for (ulong i = 0; i < totalMinutes; i++) { target.SetValue(start.AddMinutes(i), (5 + (i * 2)), 1000, 10m); } // act target.GetValue(start); // assert var thisWeek = PeriodBuilder.LastWeek(); var thisWeekSeries = SeriesValueListBuilder.BuildSeries(thisWeek.From, thisWeek.To, SeriesResolution.Hour); target.GetRecords(thisWeek.From, thisWeek.To, Unit.M3, thisWeekSeries, false); var thisWeekSeriesSum = Enumerable.Sum<SeriesValue>(thisWeekSeries, s => s.Value); var thisWeekSum = target.Sum(thisWeek.From, thisWeek.To, Unit.M3); Assert.AreEqual(thisWeekSum, thisWeekSeriesSum); } } [Test] public void WhenTheLastFiveMinutesAreRequestedFromTheFileItShouldCaluclateTheWeightForTheActualTimeGapTest() { // arrange _dataStorageContext.SerialNumber = "Interval"; _dataStorageContext.CounterId = 2421; var start = DateTime.Now.AddMinutes(-20); using (var target = new kWhStorage(new LoggerFactory(), _options, _dataStorageContext)) { // act var i = 0; while (start.AddMinutes(i) < DateTime.Now) { target.SetValue(start.AddMinutes(i), (ulong)(5 * i), 1000, 21m); i++; } target.GetValue(start); // assert var series = SeriesValueListBuilder.BuildSeries(DateTime.Today, DateTime.Now, SeriesResolution.FiveMinutes); target.GetRecords(DateTime.Today, DateTime.Now, Unit.kWh, series, false); Assert.AreEqual(300m, series[series.Count - 2].Value); } } [Test] public void SetValueShouldStoreTheRunningTotalsInTheFileTest() { // arrange _dataStorageContext.SerialNumber = "12-13-001-075"; var time = new DateTime(2012, 8, 17, 13, 20, 0); using (var storageProvider = new kWhStorage(new LoggerFactory(), _options, _dataStorageContext)) { // act for (int i = 0; i < 10; i++) { storageProvider.SetValue(time.AddMinutes(i), (ulong)(50 * i), 1000m, 21m); } } using (var storageProvider = new kWhStorage(new LoggerFactory(), _options, _dataStorageContext)) { // assert string fileName = GetTestPath($"Qbox_12-13-001-075/12-13-001-075_{_dataStorageContext.CounterId:00000000}.qbx"); Assert.IsTrue(File.Exists(fileName)); for (int i = 0; i < 10; i++) { var actual = storageProvider.GetValue(time.AddMinutes(i)); Assert.AreEqual((ulong)(50 * i), actual.Raw); Assert.AreEqual((ulong)(50 * i), actual.KiloWattHour * 1000m); } } } [Test] public void WhenLastDayOfStorageContainsPartialDataShouldGiveCorrectSum() { _dataStorageContext.SerialNumber = "12-13-001-076"; var time = new DateTime(2012, 8, 17, 13, 20, 0); using (var storageProvider = new kWhStorage(new LoggerFactory(), _options, _dataStorageContext)) { for (int i = 0; i < 10; i++) { storageProvider.SetValue(time.AddMinutes(i), (ulong)(50 * i), 1000m, 21m); } Assert.IsTrue(storageProvider.Sum(storageProvider.StartOfFile, storageProvider.EndOfFile, Unit.kWh) > 0); } } [Test] public void WhenReadHeaderIsCalledStartTimeShouldBeReturned() { _dataStorageContext.SerialNumber = "00-00-000-002"; using (var storageProvider = new kWhStorage(new LoggerFactory(), _options, _dataStorageContext)) { storageProvider.SetValue(new DateTime(2013, 5, 7, 22, 58, 0), 3000, 300.0m, 0.21m); Assert.IsNotNull(storageProvider); } } [Test] public void WhenValueIsWrittenOneMinuteBeforeStartShouldThrowException() { _dataStorageContext.SerialNumber = "00-00-000-003"; DateTime startOfFile; DateTime endOfFile; Assert.Throws(typeof(InvalidOperationException), delegate { using (var storage = new kWhStorage(new LoggerFactory(), _options, _dataStorageContext)) { // Write first value, this should set the start time of the storage. storage.SetValue(new DateTime(2013, 5, 7, 22, 58, 0), 3000, 300.0m, 0.21m); startOfFile = storage.StartOfFile; endOfFile = storage.EndOfFile; // Try to write a value one minute before the start. var timestamp = startOfFile.AddMinutes(-1); storage.SetValue(timestamp, 3000, 300.0m, 0.21m); } // If it doesn't throw an exception, we should be able to open the file again and the header should be intact. using (var storage = new kWhStorage(new LoggerFactory(), _options, _dataStorageContext)) { storage.GetValue(new DateTime(2013, 5, 7, 22, 58, 0)); Assert.AreEqual(startOfFile, storage.StartOfFile); Assert.AreEqual(endOfFile, storage.EndOfFile); } }); } [Test] public void WhenValueIsWrittenInLastSlotShouldStoreValueAndNotGrowFile() { _dataStorageContext.SerialNumber = "00-00-000-003"; DateTime endOfFile; DateTime timestampAtEnd; using (var storage = new kWhStorage(new LoggerFactory(), _options, _dataStorageContext)) { // Write first value, this should set the start time of the storage. storage.SetValue(new DateTime(2013, 5, 7, 22, 58, 0), 3000, 300.0m, 0.21m); endOfFile = storage.EndOfFile; // Write a value in the last slot. Since the end of file is the end of the slot, we have to subtract one minute. timestampAtEnd = endOfFile.AddMinutes(-1); storage.SetValue(timestampAtEnd, 3000, 300.0m, 0.21m); } using (var storage = new kWhStorage(new LoggerFactory(), _options, _dataStorageContext)) { var record = storage.GetValue(timestampAtEnd); Assert.AreEqual(3000, record.Raw); Assert.AreEqual(endOfFile, storage.EndOfFile); } } [Test] public void WhenValueIsWrittenOneMinuteBeyondEndOfFileShouldGrowFile() { _dataStorageContext.SerialNumber = "00-00-000-004"; using (var storage = new kWhStorage(new LoggerFactory(), _options, _dataStorageContext)) { // Write first value, this should set the start time of the storage. storage.SetValue(new DateTime(2013, 5, 7, 22, 58, 0), 3000, 300.0m, 0.21m); var endOfFile = storage.EndOfFile; // Write a value just beyond the last slot. storage.SetValue(endOfFile, 3000, 300.0m, 0.21m); // This should have expanded the file. Assert.IsTrue(storage.EndOfFile > endOfFile); } } [Test] public void WhenValuesAreWrittenWithRunningTotalGetValueShouldReturnSameValues() { _dataStorageContext.SerialNumber = "00-00-000-005"; using (var storage = new kWhStorage(new LoggerFactory(), _options, _dataStorageContext)) { Record runningTotal = null; for (int i = 0; i < 10; ++i) runningTotal = storage.SetValue(new DateTime(2013, 5, 7, 0, i, 0), (ulong)(3000 + i), 300.0m, 0.21m, runningTotal); } using (var storage = new kWhStorage(new LoggerFactory(), _options, _dataStorageContext)) { for (int i = 0; i < 10; ++i) { var record = storage.GetValue(new DateTime(2013, 5, 7, 0, i, 0)); Assert.IsTrue(record.IsValidMeasurement); Assert.AreEqual((ulong)(3000 + i), record.Raw); } } } [Test] public void WhenReinitializeIsCalledWithTimestampBeyondFileShouldNotThrowException() { _dataStorageContext.SerialNumber = "00-00-000-004"; using (var storage = new kWhStorage(new LoggerFactory(), _options, _dataStorageContext)) { // Write first value, this should set the start time of the storage. storage.SetValue(new DateTime(2013, 5, 7, 22, 58, 0), 3000, 300.0m, 0.21m); var endOfFile = storage.EndOfFile; storage.ReinitializeSlots(endOfFile.AddDays(1)); } } [Test] public void WhenSlotEndsAfterEndOfFileButBeforeReferenceDateGetSeriesShouldReturnValue() { _dataStorageContext.SerialNumber = "00-00-000-005"; _dataStorageContext.StorageId = ""; _dataStorageContext.AllowOverwrite = false; _options.Value.GrowthNrOfDays = 7; using (var storage = new kWhStorage(new LoggerFactory(), _options, _dataStorageContext)) { var baseTimestamp = new DateTime(2013, 1, 1, 0, 0, 0); // Create a file that start and ends before now and that contains valid usage. storage.SetValue(baseTimestamp, 3000, 300.0m, 0.21m); storage.SetValue(baseTimestamp.AddHours(1), 6000, 300.0m, 0.21m); Assert.IsTrue(storage.EndOfFile < DateTime.Now); // If we now ask for a month of data, the slot will fall inside the file, but the end will not. // This should still result in a bit of consumption. var slots = SeriesValueListBuilder.BuildSeries(baseTimestamp, baseTimestamp.AddMonths(1), SeriesResolution.Month); Assert.AreEqual(1, slots.Count); Assert.IsNull(slots[0].Value); storage.GetRecords(baseTimestamp, baseTimestamp.AddMonths(1), Unit.kWh, slots, false); Assert.IsNotNull(slots[0].Value); } } [Test] [Category("Integration")] public void WhenReferenceDateIsBeforeEndOfFileGetSeriesShouldReturnValue() { _dataStorageContext.SerialNumber = "00-00-000-005"; _dataStorageContext.StorageId = ""; // Test a new Qbox that has just started. The storage file starts at the first measurement, and ends after the ReferenceDate (now). using (var storage = new kWhStorage(new LoggerFactory(), _options, _dataStorageContext)) { var baseTimestamp = DateTime.Now.Date; // Create a file that start and ends before now and that contains valid usage on the first day. storage.SetValue(baseTimestamp.AddHours(1), 3000, 300.0m, 0.21m); storage.SetValue(baseTimestamp.AddHours(2), 6000, 300.0m, 0.21m); // If we now ask for a week of day-data, the start of the first slot will be before the actual data, // and the end of the first slot will be after the actual data. // This should still result in a bit of consumption. var slots = SeriesValueListBuilder.BuildSeries(baseTimestamp, baseTimestamp.AddDays(7), SeriesResolution.Day); Assert.AreEqual(7, slots.Count); Assert.IsNull(slots[0].Value); storage.GetRecords(baseTimestamp, baseTimestamp.AddDays(7), Unit.kWh, slots, false); Assert.IsNotNull(slots[0].Value); } } [Test] public void WhenFirstTimestampOfSlotIsInvalidMeasurementPreviousValueShouldBeUsedTest() { _dataStorageContext.SerialNumber = "00-00-000-006"; _dataStorageContext.StorageId = ""; using (var storage = new kWhStorage(new LoggerFactory(), _options, _dataStorageContext)) { var firstZeroTimestamp = new DateTime(2013, 10, 4, 8, 22, 0); // 2013-10-04 08:22 storage.SetValue(firstZeroTimestamp, 0, 1000.0m, 0.21m); var lastZeroTimestamp = new DateTime(2014, 1, 4, 18, 14, 0); // 2014-02-04 18:14 var record = storage.SetValue(lastZeroTimestamp, 0, 1000.0m, 0.21m); var firstActualTimestamp = new DateTime(2014, 1, 5, 16, 46, 0); // 2014-02-05 16:46 // Fake that running total is computed, but not written to file. This should mess up the interpolation which leads to // empty slots between lastZeroTimestamp and firstActualTimestamp. record.Time = firstActualTimestamp.AddMinutes(-1); storage.SetValue(firstActualTimestamp, 90913, 1000.0m, 0.21m, record); var startPeriod = new DateTime(2014, 1, 1); var endPeriod = new DateTime(2014, 2, 1); // Make sure we have data to fill each day in a month. var timestamp = firstActualTimestamp.Date.AddDays(1); ulong value = 100000; while (timestamp <= endPeriod) { storage.SetValue(timestamp, value, 1000.0m, 0.21m); value += 10000; timestamp = timestamp.AddDays(1); } // Now check that we get a full month of data, even if some data is missing. var slots = SeriesValueListBuilder.BuildSeries(startPeriod, endPeriod, SeriesResolution.Day); Assert.IsTrue(storage.GetRecords(startPeriod, endPeriod, Unit.kWh, slots, false)); foreach (var slot in slots) Assert.IsNotNull(slot.Value); } } [Test] public void WhenFirstTimestampOfFirstSlotIsInvalidMeasurementNextValueShouldBeUsedTest() { _dataStorageContext.SerialNumber = "00-00-000-006"; _dataStorageContext.StorageId = ""; using (var storage = new kWhStorage(new LoggerFactory(), _options, _dataStorageContext)) { var firstZeroTimestamp = new DateTime(2013, 12, 31, 0, 0, 0); storage.SetValue(firstZeroTimestamp, 0, 1000.0m, 0.21m); var lastZeroTimestamp = new DateTime(2013, 12, 31, 23, 59, 0); var record = storage.SetValue(lastZeroTimestamp, 0, 1000.0m, 0.21m); var firstActualTimestamp = new DateTime(2014, 1, 1, 12, 0, 0); // Fake that running total is computed, but not written to file. This should mess up the interpolation which leads to // empty slots between lastZeroTimestamp and firstActualTimestamp. record.Time = firstActualTimestamp.AddMinutes(-1); storage.SetValue(firstActualTimestamp, 90913, 1000.0m, 0.21m, record); var startPeriod = new DateTime(2014, 1, 1); var endPeriod = new DateTime(2014, 2, 1); // Make sure we have data to fill each day in a month. var timestamp = firstActualTimestamp.Date.AddDays(1); ulong value = 100000; while (timestamp <= endPeriod) { storage.SetValue(timestamp, value, 1000.0m, 0.21m); value += 10000; timestamp = timestamp.AddDays(1); } // Now check that we get a full month of data, even if some data is missing. var slots = SeriesValueListBuilder.BuildSeries(startPeriod, endPeriod, SeriesResolution.Day); Assert.IsTrue(storage.GetRecords(startPeriod, endPeriod, Unit.kWh, slots, false)); foreach (var slot in slots) Assert.IsNotNull(slot.Value); } } [Test] public void WhenFirstSlotIsInvalidRestOfSlotsShouldBeFilledTest() { _dataStorageContext.SerialNumber = "00-00-000-006"; _dataStorageContext.StorageId = ""; using (var storage = new kWhStorage(new LoggerFactory(), _options, _dataStorageContext)) { var firstZeroTimestamp = new DateTime(2013, 12, 31, 0, 0, 0); storage.SetValue(firstZeroTimestamp, 0, 1000.0m, 0.21m); var lastZeroTimestamp = new DateTime(2013, 12, 31, 23, 59, 0); var record = storage.SetValue(lastZeroTimestamp, 0, 1000.0m, 0.21m); var firstActualTimestamp = new DateTime(2014, 1, 2, 12, 0, 0); // Fake that running total is computed, but not written to file. This should mess up the interpolation which leads to // empty slots between lastZeroTimestamp and firstActualTimestamp. record.Time = firstActualTimestamp.AddMinutes(-1); storage.SetValue(firstActualTimestamp, 90913, 1000.0m, 0.21m, record); var startPeriod = new DateTime(2014, 1, 1); var endPeriod = new DateTime(2014, 2, 1); // Make sure we have data to fill each day in a month. var timestamp = firstActualTimestamp.Date.AddDays(1); ulong value = 100000; while (timestamp <= endPeriod) { storage.SetValue(timestamp, value, 1000.0m, 0.21m); value += 10000; timestamp = timestamp.AddDays(1); } // Now check that we get a full month of data, even if some data is missing. var slots = SeriesValueListBuilder.BuildSeries(startPeriod, endPeriod, SeriesResolution.Day); Assert.IsTrue(storage.GetRecords(startPeriod, endPeriod, Unit.kWh, slots, false)); Assert.IsNull(slots[0].Value); foreach (var slot in Enumerable.Skip<SeriesValue>(slots, 1)) Assert.IsNotNull(slot.Value); } } [Test] public void FindPreviousWorksCorrectlyWithUntruncatedTimeTest() { _dataStorageContext.SerialNumber = "00-00-000-006"; _dataStorageContext.StorageId = ""; using (var storage = new kWhStorage(new LoggerFactory(), _options, _dataStorageContext)) { var baseTimestamp = new DateTime(2016, 2, 28, 18, 17, 16); storage.SetValue(baseTimestamp, 3000, 300.0m, 0.21m); storage.SetValue(baseTimestamp.AddHours(1), 6000, 300.0m, 0.21m); var record = storage.FindPrevious(baseTimestamp.AddMinutes(1)); Assert.AreEqual(baseTimestamp.TruncateToMinute(), record.Time); } } private static string GetTestPath(string relativePath) { return Path.GetFullPath(Path.Combine(BaseDir, relativePath)); } } }
39.357143
143
0.555801
[ "MIT" ]
StefH/QboxNext
dependencies/dotnetcore-minimal/test/QboxNext.Storage.Qbx.Tests/KWhStorageTest.cs
38,021
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; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using BuildXL.Native.IO; using BuildXL.Native.IO.Windows; using BuildXL.Processes; using BuildXL.Utilities; using Test.BuildXL.Executables.TestProcess; using Test.BuildXL.TestUtilities; using Test.BuildXL.TestUtilities.Xunit; using Xunit; using Xunit.Abstractions; using static BuildXL.Utilities.FormattableStringEx; using FileUtilities = BuildXL.Native.IO.FileUtilities; #pragma warning disable AsyncFixer02 namespace Test.BuildXL.Processes { public sealed class SandboxedProcessTest : SandboxedProcessTestBase { public SandboxedProcessTest(ITestOutputHelper output) : base(output) { } private sealed class MyListener : IDetoursEventListener { private ISet<string> m_fileAccesses = new HashSet<string>(); public IEnumerable<string> FileAccesses => m_fileAccesses; public int FileAccessPathCount => m_fileAccesses.Count; public int ProcessMessageCount { get; private set; } public int DebugMessageCount { get; private set; } public int ProcessDataMessageCount { get; private set; } public int ProcessDetouringStatusMessageCount { get; private set; } public override void HandleDebugMessage(long pipId, string pipDescription, string debugMessage) { DebugMessageCount++; } public override void HandleFileAccess(long pipId, string pipDescription, ReportedFileOperation operation, RequestedAccess requestedAccess, FileAccessStatus status, bool explicitlyReported, uint processId, uint error, DesiredAccess desiredAccess, ShareMode shareMode, CreationDisposition creationDisposition, FlagsAndAttributes flagsAndAttributes, string path, string processArgs) { if (operation == ReportedFileOperation.Process) { ProcessMessageCount++; } m_fileAccesses.Add(path); } public override void HandleProcessData(long pipId, string pipDescription, string processName, uint processId, DateTime creationDateTime, DateTime exitDateTime, TimeSpan kernelTime, TimeSpan userTime, uint exitCode, IOCounters ioCounters, uint parentProcessId) { ProcessDataMessageCount++; } public override void HandleProcessDetouringStatus(ulong processId, uint reportStatus, string processName, string startApplicationName, string startCommandLine, bool needsInjection, ulong hJob, bool disableDetours, uint creationFlags, bool detoured, uint error, uint createProcessStatusReturn) { ProcessDetouringStatusMessageCount++; } } private SandboxedProcessInfo GetEchoProcessInfo(string message, IDetoursEventListener detoursListener = null, bool useStdErr = false) => ToProcessInfo(EchoProcess(message, useStdErr), detoursListener: detoursListener); private SandboxedProcessInfo GetInfiniteWaitProcessInfo() => ToProcessInfo(ToProcess(Operation.Block())); private async Task CheckEchoProcessResult(SandboxedProcessResult result, string echoMessage) { var stdout = await result.StandardOutput.ReadValueAsync(); var stderr = await result.StandardError.ReadValueAsync(); XAssert.IsFalse(result.Killed, "Process claims it or a child process was killed; exit code: {0}, stdout: '{1}', stderr: '{2}'.", result.ExitCode, stdout.Trim(), stderr.Trim()); XAssert.AreEqual(0, result.ExitCode, "Unexpected error code; stdout: '{0}', stderr: '{1}'", stdout, stderr); XAssert.AreEqual(string.Empty, stderr.Trim()); XAssert.AreEqual(echoMessage, stdout.Trim()); } [Fact] [Trait("Category", "WindowsOSOnly")] // reported files are not consistent on Mac public async Task CheckDetoursNotifications() { async Task<SandboxedProcessResult> RunEchoProcess(IDetoursEventListener detoursListener = null) { var echoMessage = "Success"; var info = GetEchoProcessInfo(echoMessage, detoursListener); info.FileAccessManifest.LogProcessData = true; info.FileAccessManifest.LogProcessDetouringStatus = true; info.FileAccessManifest.ReportFileAccesses = true; info.FileAccessManifest.ReportProcessArgs = true; var result = await RunProcess(info); await CheckEchoProcessResult(result, echoMessage); return result; } IEnumerable<string> CleanFileAccesses(IEnumerable<string> fileAccesses) { if (!OperatingSystemHelper.IsUnixOS) { var inetCache = SpecialFolderUtilities.GetFolderPath(Environment.SpecialFolder.InternetCache); return fileAccesses.Where(a => !a.StartsWith(inetCache, StringComparison.OrdinalIgnoreCase)).Select(a => a.ToUpperInvariant()).Distinct(); } else { return fileAccesses.Distinct(); } } int ComputeNumAccessedPaths(SandboxedProcessResult result) { return CleanFileAccesses(result.FileAccesses.Select(a => a.GetPath(Context.PathTable))).Count(); } int numFilePathAccesses = 0; int numProcesses = 0; int numProcessDetoursStatuses = 0; // 1st run: no listener --> just record counts { var result = await RunEchoProcess(); numFilePathAccesses = ComputeNumAccessedPaths(result); numProcesses = result.Processes.Count(); numProcessDetoursStatuses = result.DetouringStatuses.Count(); } // 2nd run: empty listener --> assert that the listener counts are 0s, and counts from 'result' didn't change { var myListener = new MyListener(); var result = await RunEchoProcess(myListener); // check the listener didn't receive any messages XAssert.AreEqual(0, myListener.DebugMessageCount); XAssert.AreEqual(0, myListener.FileAccessPathCount); XAssert.AreEqual(0, myListener.ProcessDataMessageCount); XAssert.AreEqual(0, myListener.ProcessDetouringStatusMessageCount); // check that the message counts remained the same XAssert.AreEqual(numFilePathAccesses, ComputeNumAccessedPaths(result)); XAssert.AreEqual(numProcesses, result.Processes.Count()); XAssert.AreEqual(numProcessDetoursStatuses, result.DetouringStatuses.Count()); } // 3rd run: with non-empty listener --> assert that the listener counts are the same as previously recorded ones { var myListener = new MyListener(); myListener.SetMessageHandlingFlags( MessageHandlingFlags.DebugMessageNotify | MessageHandlingFlags.FileAccessNotify | MessageHandlingFlags.ProcessDataNotify | MessageHandlingFlags.ProcessDetoursStatusNotify); var result = await RunEchoProcess(myListener); XAssert.AreEqual(0, myListener.DebugMessageCount); XAssert.AreEqual(numFilePathAccesses, CleanFileAccesses(myListener.FileAccesses).Count()); XAssert.AreEqual(numProcesses, myListener.ProcessMessageCount); XAssert.AreEqual(numProcessDetoursStatuses, myListener.ProcessDetouringStatusMessageCount); } } public static IEnumerable<object[]> CmdExeLocationsData() { yield return new object[] { CmdHelper.CmdX64 }; yield return new object[] { CmdHelper.CmdX86 }; } [Theory] [MemberData(nameof(CmdExeLocationsData))] [Trait("Category", "WindowsOSOnly")] public async Task Start(string cmdExeLocation) { var echoMessage = "Success"; using (var tempFiles = new TempFileStorage(canGetFileNames: false)) { var pt = new PathTable(); var info = new SandboxedProcessInfo(pt, tempFiles, cmdExeLocation, disableConHostSharing: false) { PipSemiStableHash = 0, PipDescription = DiscoverCurrentlyExecutingXunitTestMethodFQN(), Arguments = "/d /c echo " + echoMessage, WorkingDirectory = string.Empty, }; var result = await RunProcess(info); await CheckEchoProcessResult(result, echoMessage); } } [Fact] public async Task StartKill() { var info = GetInfiniteWaitProcessInfo(); using (ISandboxedProcess process = await StartProcessAsync(info)) { // process is running in an infinite loop, let's kill it await process.KillAsync(); SandboxedProcessResult result = await process.GetResultAsync(); XAssert.IsTrue(result.Killed); XAssert.IsFalse(result.TimedOut, "Process claims it was timed out, but instead it was killed."); } } [Fact] public async Task StartTimeout() { if (!JobObject.OSSupportsNestedJobs) { return; } var info = GetInfiniteWaitProcessInfo(); info.Timeout = new TimeSpan(1); // 1 tick == 100 nanoseconds // process is running in an infinite loop, but we have a timeout installed SandboxedProcessResult result = await RunProcess(info); XAssert.IsTrue(result.TimedOut); XAssert.IsTrue(result.Killed); XAssert.AreEqual(ExitCodes.Timeout, result.ExitCode); } [Fact(Skip = "Test is flakey TFS 495531")] public async Task JobCounters() { if (!JobObject.OSSupportsNestedJobs) { return; } using (var tempFiles = new TempFileStorage(canGetFileNames: true)) { string tempFileName = tempFiles.GetUniqueFileName(); var pt = new PathTable(); var info = new SandboxedProcessInfo(pt, tempFiles, CmdHelper.CmdX86, disableConHostSharing: false) { PipSemiStableHash = 0, PipDescription = DiscoverCurrentlyExecutingXunitTestMethodFQN(), Arguments = "/d /c sleep 1s > " + CommandLineEscaping.EscapeAsCommandLineWord(tempFileName), }; info.FileAccessManifest.FailUnexpectedFileAccesses = false; SandboxedProcessResult result = await RunProcess(info); XAssert.IsFalse(result.Killed, "Process claims it or a child process was killed."); XAssert.AreEqual(1, result.ExitCode); XAssert.IsTrue( result.JobAccountingInformation.HasValue, "Job accounting info expected when the OS supports nested jobs"); JobObject.AccountingInformation accounting = result.JobAccountingInformation.Value; if (result.PrimaryProcessTimes.TotalProcessorTime != TimeSpan.Zero) { XAssert.AreNotEqual( TimeSpan.Zero, accounting.UserTime + accounting.KernelTime, "Expected a non-zero user+kernel time."); } XAssert.AreNotEqual<ulong>(0, accounting.PeakMemoryUsage, "Expecting non-zero memory usage"); // Prior to Win10, cmd.exe launched within a job but its associated conhost.exe was exempt from the job. // That changed with Bug #633552 // Unfortunately, the unit test runner isn't manifested to support Win10, so we can't easily check the // version. XAssert.IsTrue( accounting.NumberOfProcesses == 1 || accounting.NumberOfProcesses == 2, "Expected one main process and no child processes (prior to Win10), or one child conhost.exe on Win10"); XAssert.AreNotEqual( accounting.IO.WriteCounters.TransferCount >= 3, "Expected at least three bytes written (echo XXX > file)"); } } [Theory] [InlineData(false)] [InlineData(true)] public async Task Survivors(bool includeAllowedSurvivingChildren) { if (!JobObject.OSSupportsNestedJobs) { return; } var testProcessName = TestProcessExecutable.Path.GetName(Context.PathTable); var info = ToProcessInfo(ToProcess( Operation.Spawn(Context.PathTable, waitToFinish: true, Operation.Echo("hi")), Operation.Spawn(Context.PathTable, waitToFinish: false, Operation.Block()))); // We'll wait for at most 1 seconds for nested processes to terminate, as we know we'll have to wait by design of the test // We'll wait longer to test allowed surviving children. info.NestedProcessTerminationTimeout = includeAllowedSurvivingChildren ? TimeSpan.FromSeconds(10) : TimeSpan.FromSeconds(1); if (includeAllowedSurvivingChildren) { info.AllowedSurvivingChildProcessNames = new[] { testProcessName.ToString(Context.PathTable.StringTable), Path.GetFileName(CmdHelper.Conhost) }; } // Use wall-clock time. var sw = System.Diagnostics.Stopwatch.StartNew(); var result = await RunProcess(info); sw.Stop(); XAssert.AreEqual(0, result.ExitCode); XAssert.IsNotNull(result.SurvivingChildProcesses); ToFileNames(result.SurvivingChildProcesses, out var survivorProcessNames, out var survivorNamesJoined); ToFileNames(result.Processes, out var reportedProcessNames, out var reportedNamesJoined); if (includeAllowedSurvivingChildren) { var allowedSurvivingChildProcessNames = new HashSet<PathAtom>(info.AllowedSurvivingChildProcessNames.Select(n => PathAtom.Create(Context.StringTable, n))); // Note that one of the spawned process is blocked indefinitely. // However, when surviving children are included, then that process should be killed right-away without waiting. if (sw.ElapsedMilliseconds >= info.NestedProcessTerminationTimeout.TotalMilliseconds) { // If process is not killed, then there are surviving children that are not allowed. XAssert.IsTrue( survivorProcessNames.IsProperSupersetOf(allowedSurvivingChildProcessNames), "Survivors: {0}, Allowed survivors: {1}", survivorNamesJoined, string.Join(" ; ", allowedSurvivingChildProcessNames.Select(n => n.ToString(Context.StringTable)))); } } // TestProcess must have survived XAssert.IsTrue( survivorProcessNames.Contains(testProcessName), "expected to find '{0}' in '{1}'", testProcessName.ToString(Context.StringTable), survivorNamesJoined); // conhost.exe may also have been alive. Win10 changed conhost to longer be excluded from job objects. var conhostName = PathAtom.Create(Context.StringTable, Path.GetFileName(CmdHelper.Conhost)); if (survivorProcessNames.Contains(conhostName)) { // With new Win10, there can be multiple surviving conhost. XAssert.IsTrue( result.SurvivingChildProcesses.Count() >= 2, "Unexpected survivors (cmd and conhost were present, but extras were as well): {0}", survivorNamesJoined); } else { XAssert.AreEqual( 1, result.SurvivingChildProcesses.Count(), "Unexpected survivors: {0}", string.Join(", ", survivorProcessNames.Except(new[] { testProcessName }).Select(PathAtomToString))); } // We ignore the Conhost process when checking if all survivors got reported, as Conhost seems very special foreach (var survivor in survivorProcessNames.Except(new[] { conhostName })) { XAssert.IsTrue( reportedProcessNames.Contains(survivor), "Survivor was not reported: {0}, reported: {1}", survivor.ToString(Context.StringTable), reportedNamesJoined); } void ToFileNames(IEnumerable<ReportedProcess> processes, out HashSet<PathAtom> set, out string joined) { set = new HashSet<PathAtom>(processes .Select(p => p.Path) .Select(Path.GetFileName) .Select(a => PathAtom.Create(Context.StringTable, a))); joined = string.Join(" ; ", processes .Select(p => p.Path) .Select(Path.GetFileName)); } string PathAtomToString(PathAtom a) { return a.ToString(Context.StringTable); } } [Theory] [MemberData(nameof(CmdExeLocationsData))] [Trait("Category", "WindowsOSOnly")] // same as Survivors, but using cmd.exe public async Task SurvivorsHaveCommandLines(string cmdExeLocation) { if (!JobObject.OSSupportsNestedJobs) { return; } using (var tempFiles = new TempFileStorage(canGetFileNames: false)) { var pt = new PathTable(); var info = new SandboxedProcessInfo(pt, tempFiles, cmdExeLocation, disableConHostSharing: false) { PipSemiStableHash = 0, PipDescription = DiscoverCurrentlyExecutingXunitTestMethodFQN(), Arguments = "/d /c start /B FOR /L %i IN (0,0,1) DO @rem", // launches another cmd.exe that runs how you do an infinite loop with cmd.exe // we'll wait for at most 1 seconds for nested processes to terminate, as we know we'll have to wait by design of the test NestedProcessTerminationTimeout = TimeSpan.FromSeconds(1) }; var result = await RunProcess(info); // after we detect surviving child processes, we kill them, so this test won't leave around zombie cmd.exe processes XAssert.IsNotNull(result.SurvivingChildProcesses); XAssert.AreNotEqual(0, result.SurvivingChildProcesses.Count()); foreach (var survivorProcess in result.SurvivingChildProcesses) { XAssert.IsTrue(!string.IsNullOrEmpty(survivorProcess.ProcessArgs), "Reported process did not have a command line: {0}", survivorProcess.Path); } } } [Theory] [InlineData(true)] [InlineData(false)] public async Task QuickSurvivors(bool waitToFinish) { if (!JobObject.OSSupportsNestedJobs) { return; } const string echoMessage = "Hello from a child process"; var spawnOperation = Operation.Spawn(Context.PathTable, waitToFinish, Operation.Echo(echoMessage)); var info = ToProcessInfo(ToProcess(spawnOperation)); var result = await RunProcess(info); // no survivors XAssert.IsNull(result.SurvivingChildProcesses); // at least two reported processes (conhost may be there as well on Windows) XAssert.IsNotNull(result.Processes); XAssert.IsTrue(result.Processes.Count >= 2, "Expected to see at least 2 processes, got {0}", result.Processes.Count); // only if waitToFinish is true the console output will contain the echoed message from the child process if (waitToFinish) { await CheckEchoProcessResult(result, echoMessage); } } [Fact] public async Task StandardError() { const string errorMessage = "Error"; var info = GetEchoProcessInfo(errorMessage, useStdErr: true); SandboxedProcessResult result = await RunProcess(info); XAssert.AreEqual(0, result.ExitCode); XAssert.AreEqual("Error", (await result.StandardError.ReadValueAsync()).Trim()); } [Fact] public async Task StandardOutputToFile() { const string Expected = "Success"; var info = GetEchoProcessInfo(Expected); var result = await RunProcess(info); XAssert.AreEqual(0, result.ExitCode); await result.StandardOutput.SaveAsync(); XAssert.AreEqual(Expected, File.ReadAllText(result.StandardOutput.FileName).Trim()); XAssert.AreEqual(Expected, (await result.StandardOutput.ReadValueAsync()).Trim()); } [Fact] public async Task NoStandardInputTerminates() { // Regression test for Bug 51148: BuildXL used to stop responding if process requires console input, but none was supplied. var info = ToProcessInfo(ToProcess(Operation.ReadStdIn())); var result = await RunProcess(info); XAssert.AreEqual(0, result.ExitCode); } // The following test tests only that enabling and disabling the ConHost sharing is not crashing. // There is no validation of process hierarchy.. [Theory] [InlineData(true)] [InlineData(false)] public async Task UseDisabledAndEnabledConHostSharing(bool disableConHostSharing) { var echoMessage = "hi"; var info = ToProcessInfo(EchoProcess(echoMessage), disableConHostSharing: disableConHostSharing); SandboxedProcessResult result = await RunProcess(info); await CheckEchoProcessResult(result, echoMessage); } [Fact] public async Task StandardInput() { string[] inputLines = new[] { "0", "2", "42", "1" }; string input = string.Join(Environment.NewLine, inputLines); using (var reader = new StringReader(input)) { var info = ToProcessInfo(ToProcess(Operation.ReadStdIn())); info.StandardInputReader = reader; var result = await RunProcess(info); XAssert.AreEqual(0, result.ExitCode); string stdout = await result.StandardOutput.ReadValueAsync(); XAssert.ArrayEqual(inputLines, ToLines(stdout)); } } [Fact] public async Task UnicodeArguments() { var outFile = CreateOutputFileArtifact(prefix: "\u2605"); var content = "∂ßœ∑∫µπø"; var info = ToProcessInfo(ToProcess(Operation.WriteFile(outFile, content))); var result = await RunProcess(info); XAssert.AreEqual(0, result.ExitCode); var outFilePath = outFile.Path.ToString(Context.PathTable); XAssert.AreEqual(content, File.ReadAllText(outFilePath).Trim()); } [Fact] public async Task LargeStandardOutputToFile() { var s = new string('S', 100); var info = ToProcessInfo(ToProcess( Operation.Echo(s), Operation.Echo(s))); info.MaxLengthInMemory = s.Length - 1; var result = await RunProcess(info); XAssert.AreEqual(0, result.ExitCode); XAssert.IsFalse(result.Killed); XAssert.IsFalse(result.StandardOutput.HasException); XAssert.IsTrue(result.StandardOutput.HasLength); XAssert.AreEqual(result.StandardOutput.Length, (s.Length + Environment.NewLine.Length) * 2); await result.StandardOutput.SaveAsync(); var expectedLines = new[] { s, s }; string fileName = result.StandardOutput.FileName; XAssert.ArrayEqual(expectedLines, File.ReadAllLines(fileName)); string stdout = await result.StandardOutput.ReadValueAsync(); XAssert.AreEqual(expectedLines, ToLines(stdout)); } [Fact] public async Task ExitCode() { var exitCode = 42; var info = ToProcessInfo(ToProcess(Operation.Fail(exitCode))); var result = await RunProcess(info); XAssert.AreEqual(exitCode, result.ExitCode); } [Fact] public async Task EnvironmentVariables() { var envVarName = "ENV" + Guid.NewGuid().ToString().Replace("-", string.Empty); var envVarValue = "Success"; var info = ToProcessInfo( ToProcess(Operation.ReadEnvVar(envVarName)), overrideEnvVars: new Dictionary<string, string> { [envVarName] = envVarValue }); SandboxedProcessResult result = await RunProcess(info); await CheckEchoProcessResult(result, echoMessage: envVarValue); } [Fact] public async Task WorkingDirectory() { var workingDir = CreateUniqueDirectory(prefix: "pwd-test").ToString(Context.PathTable); var info = ToProcessInfo(ToProcess(Operation.EchoCurrentDirectory())); info.WorkingDirectory = workingDir; var result = await RunProcess(info); var stdout = await result.StandardOutput.ReadValueAsync(); XAssert.AreEqual(0, result.ExitCode); XAssert.AreEqual(workingDir, stdout.Trim()); } [Fact] [Trait("Category", "WindowsOSOnly")] public async Task ProcessId() { using (var tempFiles = new TempFileStorage(canGetFileNames: false)) { var pt = new PathTable(); var info = new SandboxedProcessInfo(pt, tempFiles, CmdHelper.CmdX64, disableConHostSharing: false) { PipSemiStableHash = 0, PipDescription = DiscoverCurrentlyExecutingXunitTestMethodFQN(), Arguments = "/d /c wmic process get parentprocessid,name|find \"WMIC\"", }; info.FileAccessManifest.FailUnexpectedFileAccesses = false; using (ISandboxedProcess process = await StartProcessAsync(info)) { SandboxedProcessResult result = await process.GetResultAsync(); string output = (await result.StandardOutput.ReadValueAsync()).Trim(); // there can be multiple instance of WMIC running concurrently, // so we can only check that one of them has this process as the parent var possibleProcessIds = new List<int>(); foreach (string s in output.Split('\n').Select(s => s.Trim()).Where(s => !string.IsNullOrEmpty(s))) { string t = s.StartsWith("WMIC.exe", StringComparison.Ordinal) ? s.Substring("WMIC.exe".Length).Trim() : s; int i; if (int.TryParse(t, out i)) { possibleProcessIds.Add(i); } else { XAssert.Fail("Not an integer: {0}", t); } } XAssert.IsTrue(possibleProcessIds.Contains(process.ProcessId)); } } } [Fact] [Trait("Category", "WindowsOSOnly")] public async Task ReportNoBuildExeTraceLog() { using (var tempFiles = new TempFileStorage(canGetFileNames: true)) { string matchingFileName = "_buildc_dep_out.pass1"; var pt = new PathTable(); var info = new SandboxedProcessInfo(pt, tempFiles, CmdHelper.CmdX64, disableConHostSharing: false) { PipSemiStableHash = 0, PipDescription = DiscoverCurrentlyExecutingXunitTestMethodFQN(), Arguments = "/d /c echo >" + CommandLineEscaping.EscapeAsCommandLineWord(matchingFileName) }; AddCmdDependencies(pt, info); var result = await RunProcess(info); XAssert.AreEqual(0, result.ExitCode); XAssert.AreEqual(0, result.AllUnexpectedFileAccesses.Count); } } [Fact] [Trait("Category", "WindowsOSOnly")] public async Task ReportNoNul() { using (var tempFiles = new TempFileStorage(canGetFileNames: true)) { string nulFileName = "NUL"; var pt = new PathTable(); var info = new SandboxedProcessInfo(pt, tempFiles, CmdHelper.CmdX64, disableConHostSharing: false) { PipSemiStableHash = 0, PipDescription = DiscoverCurrentlyExecutingXunitTestMethodFQN(), Arguments = "/d /c echo >" + CommandLineEscaping.EscapeAsCommandLineWord(nulFileName), }; AddCmdDependencies(pt, info); var result = await RunProcess(info); XAssert.AreEqual(0, result.ExitCode); XAssert.AreEqual(0, result.AllUnexpectedFileAccesses.Count); } } [Fact] [Trait("Category", "WindowsOSOnly")] public async Task ReportNoNulColon() { using (var tempFiles = new TempFileStorage(canGetFileNames: true)) { string nulFileName = "NUL:"; var pt = new PathTable(); var info = new SandboxedProcessInfo(pt, tempFiles, CmdHelper.CmdX64, disableConHostSharing: false) { PipSemiStableHash = 0, PipDescription = DiscoverCurrentlyExecutingXunitTestMethodFQN(), Arguments = "/d /c echo >" + CommandLineEscaping.EscapeAsCommandLineWord(nulFileName), }; AddCmdDependencies(pt, info); var result = await RunProcess(info); XAssert.AreEqual(0, result.ExitCode); XAssert.AreEqual(0, result.AllUnexpectedFileAccesses.Count); } } [Fact] [Trait("Category", "WindowsOSOnly")] public async Task ReportNoFolderNul() { using (var tempFiles = new TempFileStorage(canGetFileNames: true)) { string windowsDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Windows); string nulFileName = Path.Combine(windowsDirectory, "nul"); var pt = new PathTable(); var info = new SandboxedProcessInfo(pt, tempFiles, CmdHelper.CmdX64, disableConHostSharing: false) { PipSemiStableHash = 0, PipDescription = DiscoverCurrentlyExecutingXunitTestMethodFQN(), Arguments = "/d /c echo >" + CommandLineEscaping.EscapeAsCommandLineWord(nulFileName), }; AddCmdDependencies(pt, info); var result = await RunProcess(info); XAssert.AreEqual(0, result.ExitCode); XAssert.AreEqual(0, result.AllUnexpectedFileAccesses.Count); } } [Fact] [Trait("Category", "WindowsOSOnly")] public async Task ReportNoDriveNul() { using (var tempFiles = new TempFileStorage(canGetFileNames: true)) { string windowsDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Windows); string nulFileName = windowsDirectory[0] + ":nul"; var pt = new PathTable(); var info = new SandboxedProcessInfo(pt, tempFiles, CmdHelper.CmdX64, disableConHostSharing: false) { PipSemiStableHash = 0, PipDescription = DiscoverCurrentlyExecutingXunitTestMethodFQN(), Arguments = "/d /c echo >" + CommandLineEscaping.EscapeAsCommandLineWord(nulFileName), }; AddCmdDependencies(pt, info); var result = await RunProcess(info); XAssert.AreEqual(0, result.ExitCode); XAssert.AreEqual(0, result.AllUnexpectedFileAccesses.Count); } } private static void AddCmdDependencies(PathTable pt, SandboxedProcessInfo info) { foreach (AbsolutePath path in CmdHelper.GetCmdDependencies(pt)) { info.FileAccessManifest.AddPath(path, values: FileAccessPolicy.AllowRead, mask: FileAccessPolicy.MaskNothing); } foreach (AbsolutePath path in CmdHelper.GetCmdDependencyScopes(pt)) { info.FileAccessManifest.AddScope(path, FileAccessPolicy.MaskNothing, FileAccessPolicy.AllowRead); } } [Theory] [InlineData(true, true)] [InlineData(true, false)] [InlineData(false, true)] [InlineData(false, false)] [Trait("Category", "WindowsOSOnly")] public async Task ReportSingleAccess(bool expectUsn, bool reportUsn) { using (var tempFiles = new TempFileStorage(canGetFileNames: true)) { var pt = new PathTable(); string tempFileName = tempFiles.GetUniqueFileName(); File.WriteAllText(tempFileName, "Success"); Usn usn; using (FileStream fs = File.OpenRead(tempFileName)) { MiniUsnRecord? maybeUsn = FileUtilities.ReadFileUsnByHandle(fs.SafeFileHandle); XAssert.IsTrue(maybeUsn.HasValue, "USN journal is either disabled or not supported by the volume"); usn = maybeUsn.Value.Usn; } AbsolutePath tempFilePath = AbsolutePath.Create(pt, tempFileName); var info = new SandboxedProcessInfo(pt, tempFiles, CmdHelper.CmdX64, disableConHostSharing: false) { PipSemiStableHash = 0, PipDescription = DiscoverCurrentlyExecutingXunitTestMethodFQN(), Arguments = "/d /c type " + CommandLineEscaping.EscapeAsCommandLineWord(tempFileName), }; info.FileAccessManifest.ReportFileAccesses = true; // We expect all accesses reported (we use result.FileAccesses below). info.FileAccessManifest.AddPath( tempFilePath, values: FileAccessPolicy.AllowRead | (reportUsn ? FileAccessPolicy.ReportUsnAfterOpen : 0), mask: FileAccessPolicy.MaskNothing, expectedUsn: expectUsn ? usn : ReportedFileAccess.NoUsn); // We explicitly do not set ReportAccess (testing catchall reporting) SandboxedProcessResult result = await RunProcess(info); XAssert.AreEqual(0, result.ExitCode); XAssert.AreEqual("Success", (await result.StandardOutput.ReadValueAsync()).Trim()); XAssert.AreEqual(string.Empty, (await result.StandardError.ReadValueAsync()).Trim()); XAssert.IsNotNull(result.FileAccesses); ReportedProcess reportedProcess = result.FileAccesses.FirstOrDefault().Process; ReportedFileAccess rfa = ReportedFileAccess.Create( ReportedFileOperation.CreateFile, reportedProcess, RequestedAccess.Read, FileAccessStatus.Allowed, reportUsn, // Explicit flag 0, (reportUsn || expectUsn) ? usn : ReportedFileAccess.NoUsn, DesiredAccess.GENERIC_READ, ShareMode.FILE_SHARE_READ | ShareMode.FILE_SHARE_WRITE, CreationDisposition.CREATE_NEW | CreationDisposition.CREATE_ALWAYS, FlagsAndAttributes.FILE_ATTRIBUTE_NORMAL, tempFilePath); AssertReportedAccessesContains(pt, result.FileAccesses, rfa); } } [Fact] public async Task ReportSingleReadAccessXPlat() { var srcFile = CreateSourceFile(); var fam = new FileAccessManifest(Context.PathTable); fam.ReportFileAccesses = true; // We explicitly do not set ReportAccess (testing catchall reporting) fam.FailUnexpectedFileAccesses = false; fam.AddPath(srcFile.Path, values: FileAccessPolicy.AllowRead, mask: FileAccessPolicy.MaskNothing); var info = ToProcessInfo( ToProcess(Operation.ReadFile(srcFile)), fileAccessManifest: fam); var result = await RunProcess(info); XAssert.AreEqual(0, result.ExitCode); XAssert.IsNotNull(result.FileAccesses); AssertReportedAccessesContains( Context.PathTable, result.FileAccesses, GetFileAccessForReadFileOperation( srcFile.Path, result.FileAccesses.FirstOrDefault().Process, denied: false, explicitlyReported: false)); } [Fact] public async Task ReportSingleUnexpectedAccess() { var srcFile = CreateSourceFile(); var fam = new FileAccessManifest(Context.PathTable); fam.ReportFileAccesses = false; fam.FailUnexpectedFileAccesses = false; fam.AddPath(srcFile.Path, values: FileAccessPolicy.Deny | FileAccessPolicy.ReportAccess, mask: FileAccessPolicy.MaskNothing); var info = ToProcessInfo( ToProcess(Operation.ReadFile(srcFile)), fileAccessManifest: fam); var result = await RunProcess(info); XAssert.AreEqual(0, result.ExitCode); // Only because FailUnexpectedFileAccesses = false XAssert.IsNull(result.FileAccesses); // We aren't reporting file accesses (just violations) XAssert.IsNotNull(result.AllUnexpectedFileAccesses); XAssert.IsTrue(result.AllUnexpectedFileAccesses.Count > 0); AssertReportedAccessesContains( Context.PathTable, result.AllUnexpectedFileAccesses, GetFileAccessForReadFileOperation( srcFile.Path, result.AllUnexpectedFileAccesses.FirstOrDefault().Process, denied: true, explicitlyReported: true)); } [Fact] [Trait("Category", "WindowsOSOnly")] public async Task ReportSingleUnexpectedUsnAccess() { using (var tempFiles = new TempFileStorage(canGetFileNames: true)) { var pt = new PathTable(); string tempFileName = tempFiles.GetUniqueFileName(); File.WriteAllText(tempFileName, "Success"); Usn usn; using (FileStream fs = File.OpenRead(tempFileName)) { MiniUsnRecord? maybeUsn = FileUtilities.ReadFileUsnByHandle(fs.SafeFileHandle); XAssert.IsTrue(maybeUsn.HasValue, "USN journal is either disabled or not supported by the volume"); usn = maybeUsn.Value.Usn; } AbsolutePath tempFilePath = AbsolutePath.Create(pt, tempFileName); var info = new SandboxedProcessInfo(pt, tempFiles, CmdHelper.CmdX64, disableConHostSharing: false) { PipSemiStableHash = 0, PipDescription = DiscoverCurrentlyExecutingXunitTestMethodFQN(), Arguments = "/d /c type " + CommandLineEscaping.EscapeAsCommandLineWord(tempFileName), }; info.FileAccessManifest.ReportFileAccesses = false; info.FileAccessManifest.FailUnexpectedFileAccesses = false; info.FileAccessManifest.AddPath(tempFilePath, values: FileAccessPolicy.AllowRead, mask: FileAccessPolicy.MaskNothing, expectedUsn: new Usn(usn.Value - 1)); SandboxedProcessResult result = await RunProcess(info); XAssert.AreEqual(0, result.ExitCode); // Only because FailUnexpectedFileAccesses = false XAssert.AreEqual(string.Empty, (await result.StandardError.ReadValueAsync()).Trim()); XAssert.IsNull(result.FileAccesses); // We aren't reporting file accesses (just violations) ReportedProcess reportedProcess = result.AllUnexpectedFileAccesses.FirstOrDefault().Process; ReportedFileAccess rfa = ReportedFileAccess.Create( ReportedFileOperation.CreateFile, reportedProcess, RequestedAccess.Read, FileAccessStatus.Allowed, true, 0, usn, DesiredAccess.GENERIC_READ, ShareMode.FILE_SHARE_READ | ShareMode.FILE_SHARE_WRITE, CreationDisposition.CREATE_NEW | CreationDisposition.CREATE_ALWAYS, FlagsAndAttributes.FILE_ATTRIBUTE_NORMAL, tempFilePath); AssertReportedAccessesContains(pt, result.ExplicitlyReportedFileAccesses, rfa); } } [Fact] public async Task ReportGeneralUnexpectedAccess() { var srcFile = CreateSourceFile(); var fam = new FileAccessManifest(Context.PathTable); fam.ReportFileAccesses = true; fam.ReportUnexpectedFileAccesses = true; fam.FailUnexpectedFileAccesses = false; var info = ToProcessInfo( ToProcess(Operation.ReadFile(srcFile)), fileAccessManifest: fam); var result = await RunProcess(info); XAssert.AreEqual(0, result.ExitCode); XAssert.IsNotNull(result.FileAccesses); XAssert.IsNotNull(result.AllUnexpectedFileAccesses); ReportedFileAccess rfa = GetFileAccessForReadFileOperation( srcFile.Path, result.FileAccesses.First().Process, denied: true, explicitlyReported: false); AssertReportedAccessesContains(Context.PathTable, result.FileAccesses, rfa); AssertReportedAccessesContains(Context.PathTable, result.AllUnexpectedFileAccesses, rfa); } [Fact] public async Task ReportGeneralUnexpectedAccessWithRequestedWriteAccess() { var outFile = CreateOutputFileArtifact(); var fam = new FileAccessManifest(Context.PathTable); fam.ReportFileAccesses = true; fam.ReportUnexpectedFileAccesses = true; fam.FailUnexpectedFileAccesses = false; var info = ToProcessInfo( ToProcess(Operation.WriteFile(outFile, doNotInfer: true)), fileAccessManifest: fam); var result = await RunProcess(info); XAssert.AreEqual(0, result.ExitCode); XAssert.IsNotNull(result.FileAccesses); ReportedFileAccess rfa = GetFileAccessForWriteFileOperation( outFile.Path, result.FileAccesses.FirstOrDefault().Process, denied: true, explicitlyReported: false); AssertReportedAccessesContains(Context.PathTable, result.FileAccesses, rfa); AssertReportedAccessesContains(Context.PathTable, result.AllUnexpectedFileAccesses, rfa); } [Fact] [Trait("Category", "WindowsOSOnly")] public async Task IgnoreInvalidPathRead() { using (var tempFiles = new TempFileStorage(canGetFileNames: true)) { var pt = new PathTable(); string tempDirName = tempFiles.RootDirectory; AbsolutePath tempDirPath = AbsolutePath.Create(pt, tempDirName); var info = new SandboxedProcessInfo(pt, tempFiles, CmdHelper.CmdX64, disableConHostSharing: false) { // Adding \|Bad bit| to the end should result in ERROR_INVALID_NAME. The ^ hats are for cmd escaping. Note that type eats quotes, so we can't try those. PipSemiStableHash = 0, PipDescription = DiscoverCurrentlyExecutingXunitTestMethodFQN(), Arguments = "/d /c type " + CommandLineEscaping.EscapeAsCommandLineWord(tempDirName) + "\\^|Bad bit^| 2>nul || (echo Nope & exit /b 0)", }; info.FileAccessManifest.AddScope( AbsolutePath.Invalid, FileAccessPolicy.MaskNothing, FileAccessPolicy.AllowAll); // Ignore everything outside of the temp directory info.FileAccessManifest.AddScope( tempDirPath, FileAccessPolicy.MaskAll, FileAccessPolicy.AllowReadIfNonexistent | FileAccessPolicy.ReportAccess); // A real access would be reported, but a bad path should be ignored. var result = await RunProcess(info); XAssert.AreEqual(0, result.ExitCode); XAssert.AreEqual("Nope", (await result.StandardOutput.ReadValueAsync()).Trim()); XAssert.AreEqual(string.Empty, (await result.StandardError.ReadValueAsync()).Trim()); AssertReportedAccessesIsEmpty(pt, result.AllUnexpectedFileAccesses); // Note we filter this set, since cmd likes to probe all over the place. AssertReportedAccessesIsEmpty(pt, result.ExplicitlyReportedFileAccesses.Where(access => access.GetPath(pt).Contains("Bad"))); } } [Fact] public async Task StartFileDoesNotExist() { var pt = new PathTable(); var info = new SandboxedProcessInfo(pt, this, "DoesNotExistIHope", disableConHostSharing: false) { PipSemiStableHash = 0, PipDescription = DiscoverCurrentlyExecutingXunitTestMethodFQN(), SandboxedKextConnection = GetSandboxedKextConnection() }; try { await StartProcessAsync(info); } catch (BuildXLException ex) { string logMessage = ex.LogEventMessage; int errorCode = ex.LogEventErrorCode; XAssert.IsTrue(logMessage.Contains("Process creation failed"), "Missing substring in {0}", logMessage); XAssert.IsTrue(errorCode == 0x2 || errorCode == 0x3, "Expected ERROR_FILE_NOT_FOUND or ERROR_PATH_NOT_FOUND: {0}", errorCode); return; } XAssert.Fail("Expected BuildXLException due to process creation failure"); } [Fact] public async Task TempAccessesAreUnexpectedByDefault() { var outFile = CreateOutputFileArtifact(root: TemporaryDirectory, prefix: "not.allowed"); var info = ToProcessInfo(ToProcess(Operation.WriteFile(outFile))); var result = await RunProcess(info); XAssert.IsNotNull(result.AllUnexpectedFileAccesses); XAssert.IsTrue( result.AllUnexpectedFileAccesses.Any(a => a.GetPath(Context.PathTable) == outFile.Path.ToString(Context.PathTable)), "Expected to see unexpected file access into restricted temp folder ({0}), got: {1}", outFile.Path.ToString(Context.PathTable), string.Join(Environment.NewLine, result.AllUnexpectedFileAccesses.Select(p => p.GetPath(Context.PathTable)))); } /// <summary> /// Tests that FileAccessManifest.ReportProcessArgs option controls whether the /// command line arguments of all launched processes will be captured and reported /// </summary> [TheoryIfSupported(requiresWindowsBasedOperatingSystem: true)] // Sandbox Kext on macOS doesn't capture process cmdline [InlineData(true)] [InlineData(false)] public async Task ReportProcessCommandLineArgs(bool reportProcessArgs) { const string echoMessage = "test"; var echoOp = Operation.Echo(echoMessage); var info = GetEchoProcessInfo(echoMessage); info.FileAccessManifest.ReportProcessArgs = reportProcessArgs; var result = await RunProcess(info); await CheckEchoProcessResult(result, echoMessage); // validate the results: we are expecting 1 process with command line args XAssert.AreEqual(1, result.Processes.Count, "The number of processes launched is not correct"); var expectedReportedArgs = reportProcessArgs ? TestProcessExecutable.Path.ToString(Context.PathTable) + " " + echoOp.ToCommandLine(Context.PathTable) : string.Empty; XAssert.AreEqual( expectedReportedArgs, result.Processes[0].ProcessArgs, "The captured processes arguments are incorrect"); } private void AssertReportedAccessesIsEmpty(PathTable pathTable, IEnumerable<ReportedFileAccess> result) { if (result == null || !result.Any()) { return; } var message = new StringBuilder(); message.AppendLine("Expected an empty set of reported accesses."); message.AppendLine("These were actually reported:"); foreach (ReportedFileAccess actual in result) { message.AppendFormat("\t{0} : {1}\n", actual.GetPath(pathTable), actual.Describe()); } XAssert.Fail(message.ToString()); } private void AssertReportedAccessesContains(PathTable pathTable, ISet<ReportedFileAccess> result, ReportedFileAccess rfa) { IEqualityComparer<ReportedFileAccess> comparer = OperatingSystemHelper.IsUnixOS ? new RelaxedReportedFileAccessComparer(Context.PathTable) : EqualityComparer<ReportedFileAccess>.Default; if (result.Contains(rfa, comparer)) { return; } var rfaPath = rfa.GetPath(pathTable); var rfaDescribe = rfa.Describe(); var message = new StringBuilder(); message.AppendFormat("Expected the following access: {0}: {1}\n", rfaPath, rfaDescribe); message.AppendLine("These were actually reported (same manifest path):"); foreach (ReportedFileAccess actual in result) { var actualPath = actual.GetPath(pathTable); var actualDescribe = actual.Describe(); if (actualPath == rfaPath) { if (actualDescribe == rfaDescribe) { return; } message.AppendFormat("\t{0} : {1}\n", actualPath, actualDescribe); } } message.AppendLine("(others; different manifest path):"); foreach (ReportedFileAccess actual in result) { var actualPath = actual.GetPath(pathTable); if (actualPath != rfaPath) { message.AppendFormat("\t{0} : {1}\n", actualPath, actual.Describe()); } } XAssert.Fail(message.ToString()); } [Fact] [Trait("Category", "WindowsOSOnly")] public async Task CheckPreloadedDll() { using (var tempFiles = new TempFileStorage(canGetFileNames: true)) { string windowsDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Windows); string nulFileName = Path.Combine(windowsDirectory, "nul"); var pt = new PathTable(); var info = new SandboxedProcessInfo(pt, tempFiles, CmdHelper.CmdX64, disableConHostSharing: false) { PipSemiStableHash = 0, PipDescription = DiscoverCurrentlyExecutingXunitTestMethodFQN(), Arguments = "/d /c echo >" + CommandLineEscaping.EscapeAsCommandLineWord(nulFileName), }; info.FileAccessManifest.IgnorePreloadedDlls = false; AddCmdDependencies(pt, info); var result = await RunProcess(info); XAssert.AreEqual(0, result.ExitCode); XAssert.AreEqual(0, result.AllUnexpectedFileAccesses.Count); // In our tests we use the shared conhost, so for this test nothing extra was loaded in the reused test. } } private static ReportedFileAccess GetFileAccessForReadFileOperation( AbsolutePath path, ReportedProcess process, bool denied, bool explicitlyReported) { return ReportedFileAccess.Create( ReportedFileOperation.CreateFile, process, RequestedAccess.Read, denied ? FileAccessStatus.Denied : FileAccessStatus.Allowed, explicitlyReported, 0, ReportedFileAccess.NoUsn, DesiredAccess.GENERIC_READ, ShareMode.FILE_SHARE_READ, CreationDisposition.OPEN_EXISTING, FlagsAndAttributes.FILE_FLAG_OPEN_NO_RECALL | FlagsAndAttributes.FILE_FLAG_SEQUENTIAL_SCAN, path); } private static ReportedFileAccess GetFileAccessForWriteFileOperation( AbsolutePath path, ReportedProcess process, bool denied, bool explicitlyReported) { return ReportedFileAccess.Create( ReportedFileOperation.CreateFile, process, RequestedAccess.Write, denied ? FileAccessStatus.Denied : FileAccessStatus.Allowed, explicitlyReported, 0, ReportedFileAccess.NoUsn, DesiredAccess.GENERIC_WRITE, ShareMode.FILE_SHARE_READ, CreationDisposition.OPEN_ALWAYS, FlagsAndAttributes.FILE_FLAG_OPEN_NO_RECALL | FlagsAndAttributes.FILE_FLAG_SEQUENTIAL_SCAN, path); } private static string[] ToLines(string str) => str.Trim().Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries); } internal class RelaxedReportedFileAccessComparer : EqualityComparer<ReportedFileAccess> { private readonly PathTable m_pathTable; internal RelaxedReportedFileAccessComparer(PathTable pathTable) { m_pathTable = pathTable; } public override bool Equals(ReportedFileAccess x, ReportedFileAccess y) { if (x == null || y == null) return x == y; return RelevantFieldsToString(x).Equals(RelevantFieldsToString(y)); } public override int GetHashCode(ReportedFileAccess obj) { return RelevantFieldsToString(obj).GetHashCode(); } private string RelevantFieldsToString(ReportedFileAccess rfa) { return I($"{rfa.GetPath(m_pathTable)}|{rfa.Status}|{rfa.RequestedAccess}|{rfa.ExplicitlyReported}|{rfa.Error}"); } } }
46.028884
392
0.574665
[ "MIT" ]
kant/BuildXL
Public/Src/Engine/UnitTests/Processes/SandboxedProcessTest.cs
58,974
C#
using Nop.Web.Areas.Admin.Models.Catalog; using Nop.Web.Framework.Models; namespace Nop.Plugin.Widgets.UserManuals.Models { #if !NOP_ASYNC public partial class #else public partial record #endif AddProductToUserManualListModel : BasePagedListModel<ProductModel> { } }
19.4
70
0.756014
[ "MIT" ]
biggik/Nop.Plugin.Widgets.UserManuals
Common/Models/AddProductToUserManualListModel.cs
293
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.AzureNextGen.ApiManagement.Latest.Inputs { /// <summary> /// Properties controlling TLS Certificate Validation. /// </summary> public sealed class BackendTlsPropertiesArgs : Pulumi.ResourceArgs { /// <summary> /// Flag indicating whether SSL certificate chain validation should be done when using self-signed certificates for this backend host. /// </summary> [Input("validateCertificateChain")] public Input<bool>? ValidateCertificateChain { get; set; } /// <summary> /// Flag indicating whether SSL certificate name validation should be done when using self-signed certificates for this backend host. /// </summary> [Input("validateCertificateName")] public Input<bool>? ValidateCertificateName { get; set; } public BackendTlsPropertiesArgs() { } } }
34.285714
142
0.683333
[ "Apache-2.0" ]
test-wiz-sec/pulumi-azure-nextgen
sdk/dotnet/ApiManagement/Latest/Inputs/BackendTlsPropertiesArgs.cs
1,200
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace AtCoder.Temp.Lib { public static class StringAlgorithm { public class StringComparator : IComparer<string> { int IComparer<string>.Compare(string a, string b) { int length = Math.Min(a.Length, b.Length); for (int i = 0; i < length; i++) { if (a[i] < b[i]) { return -1; } else if (a[i] > b[i]) { return 1; } } if (a.Length < b.Length) { return -1; } if (a.Length > b.Length) { return 1; } return 0; } } public static int[] ZAlogorithm(string s, int start) { int n = s.Length - start; int[] a = new int[n]; int c = 0; for (int i = 1; i < n; i++) { if (i + a[i - c] < c + a[c]) { a[i] = a[i - c]; } else { int j = Math.Max(0, c + a[c] - i); while (i + j < n && s[j + start] == s[i + j + start]) { ++j; } a[i] = j; c = i; } } a[0] = n; return a; } //original: ttps://github.com/key-moon/ac-library-cs public static int[] ZAlgorithm(string s) => ZAlgorithm(s.AsSpan()); public static int[] ZAlgorithm<T>(T[] s) => ZAlgorithm((ReadOnlySpan<T>)s); public static int[] ZAlgorithm<T>(ReadOnlySpan<T> s) { int n = s.Length; if (n == 0) { return new int[] { }; } int[] z = new int[n]; z[0] = 0; for (int i = 1, j = 0; i < n; ++i) { ref int k = ref z[i]; k = (j + z[j] <= i) ? 0 : Math.Min(j + z[j] - i, z[i - j]); while (i + k < n && EqualityComparer<T>.Default.Equals(s[k], s[i + k])) { ++k; } if (j + z[j] < i + z[i]) { j = i; } } z[0] = n; return z; } //original: ttps://github.com/key-moon/ac-library-cs public static int[] SuffixArray(string s) => SAIS(s.Select(c => (int)c).ToArray(), char.MaxValue); public static int[] SAIS(ReadOnlyMemory<int> memory, int upper) => SAIS(memory, upper, 10, 40); public static int[] SAIS(ReadOnlyMemory<int> memory, int upper, int thresholdNaive, int thresholdDouling) { var s = memory.Span; var n = s.Length; if (n == 0) { return Array.Empty<int>(); } else if (n == 1) { return new int[] { 0 }; } else if (n == 2) { if (s[0] < s[1]) { return new int[] { 0, 1 }; } else { return new int[] { 1, 0 }; } } else if (n < thresholdNaive) { return SANaive(memory); } else if (n < thresholdDouling) { return SADoubling(memory); } var sa = new int[n]; var isTypeS = new bool[n]; for (int i = sa.Length - 2; i >= 0; --i) { isTypeS[i] = (s[i] == s[i + 1]) ? isTypeS[i + 1] : (s[i] < s[i + 1]); } var sumL = new int[upper + 1]; var sumS = new int[upper + 1]; for (int i = 0; i < s.Length; ++i) { if (!isTypeS[i]) { ++sumS[s[i]]; } else { ++sumL[s[i] + 1]; } } for (int i = 0; i < sumL.Length; ++i) { sumS[i] += sumL[i]; if (i < upper) { sumL[i + 1] += sumS[i]; } } var lmsMap = new int[n + 1]; lmsMap.AsSpan().Fill(-1); int m = 0; for (int i = 1; i < isTypeS.Length; ++i) { if (!isTypeS[i - 1] && isTypeS[i]) { lmsMap[i] = m; ++m; } } var lms = new List<int>(m); for (int i = 1; i < isTypeS.Length; ++i) { if (!isTypeS[i - 1] && isTypeS[i]) { lms.Add(i); } } void Induce(List<int> lms) { var s = memory.Span; sa.AsSpan().Fill(-1); var buf = new int[sumS.Length]; sumS.AsSpan().CopyTo(buf); foreach (var d in lms) { if (d == n) { continue; } sa[buf[s[d]]] = d; ++buf[s[d]]; } sumL.AsSpan().CopyTo(buf); sa[buf[s[n - 1]]] = n - 1; ++buf[s[n - 1]]; for (int i = 0; i < sa.Length; ++i) { int v = sa[i]; if (v >= 1 && !isTypeS[v - 1]) { sa[buf[s[v - 1]]] = v - 1; ++buf[s[v - 1]]; } } sumL.AsSpan().CopyTo(buf); for (int i = sa.Length - 1; i >= 0; --i) { int v = sa[i]; if (v >= 1 && isTypeS[v - 1]) { --buf[s[v - 1] + 1]; sa[buf[s[v - 1] + 1]] = v - 1; } } } Induce(lms); if (m > 0) { var sortedLms = new List<int>(m); foreach (var v in sa) { if (lmsMap[v] != -1) { sortedLms.Add(v); } } var recS = new int[m]; var recUpper = 0; recS[lmsMap[sortedLms[0]]] = 0; for (int i = 1; i < sortedLms.Count; i++) { var l = sortedLms[i - 1]; var r = sortedLms[i]; var endL = (lmsMap[l] + 1 < m) ? lms[lmsMap[l] + 1] : n; var endR = (lmsMap[r] + 1 < m) ? lms[lmsMap[r] + 1] : n; var same = true; if (endL - l != endR - r) { same = false; } else { while (l < endL) { if (s[l] != s[r]) { break; } ++l; ++r; } if (l == n || s[l] != s[r]) { same = false; } } if (!same) { ++recUpper; } recS[lmsMap[sortedLms[i]]] = recUpper; } var recSA = SAIS(recS, recUpper, thresholdNaive, thresholdDouling); for (int i = 0; i < sortedLms.Count; ++i) { sortedLms[i] = lms[recSA[i]]; } Induce(sortedLms); } return sa; } private static int[] SANaive(ReadOnlyMemory<int> memory) { var n = memory.Length; var sa = Enumerable.Range(0, n).ToArray(); int Compare(int l, int r) { var s = memory.Span; while (l < s.Length && r < s.Length) { if (s[l] != s[r]) { return s[l] - s[r]; } ++l; ++r; } return r - l; } Array.Sort(sa, Compare); return sa; } private static int[] SADoubling(ReadOnlyMemory<int> memory) { var s = memory.Span; var n = s.Length; var sa = Enumerable.Range(0, n).ToArray(); var rnk = new int[n]; var tmp = new int[n]; s.CopyTo(rnk); for (int k = 1; k < n; k <<= 1) { int Compare(int x, int y) { if (rnk[x] != rnk[y]) { return rnk[x] - rnk[y]; } int rx = x + k < n ? rnk[x + k] : -1; int ry = y + k < n ? rnk[y + k] : -1; return rx - ry; } Array.Sort(sa, Compare); tmp[sa[0]] = 0; for (int i = 1; i < sa.Length; ++i) { tmp[sa[i]] = tmp[sa[i - 1]] + (Compare(sa[i - 1], sa[i]) < 0 ? 1 : 0); } (tmp, rnk) = (rnk, tmp); } return sa; } //original: ttps://github.com/key-moon/ac-library-cs public static int[] LcpArray(string s, int[] saffixArray) => LcpArray(s.AsSpan(), saffixArray); public static int[] LcpArray<T>(T[] s, int[] saffixArray) => LcpArray((ReadOnlySpan<T>)s, saffixArray); public static int[] LcpArray<T>(ReadOnlySpan<T> s, int[] saffixArray) { int[] rnk = new int[s.Length]; for (int i = 0; i < s.Length; ++i) { rnk[saffixArray[i]] = i; } int[] lcp = new int[s.Length - 1]; int h = 0; for (int i = 0; i < s.Length; ++i) { if (h > 0) { --h; } if (rnk[i] == 0) { continue; } int j = saffixArray[rnk[i] - 1]; for (; j + h < s.Length && i + h < s.Length; ++h) { if (!EqualityComparer<T>.Default.Equals(s[j + h], s[i + h])) { break; } } lcp[rnk[i] - 1] = h; } return lcp; } } }
22.185075
108
0.45479
[ "MIT" ]
takytank/KyoPro
projects/AtCoder.Temp/Lib/StringAlgorithm.cs
7,434
C#
using System.Collections.Generic; using System.IO; using Xe.BinaryMapper; namespace OpenKh.Kh2.Battle { public class Enmp { [Data] public ushort Id { get; set; } [Data] public ushort Level { get; set; } [Data(Count = 32)] public short[] Health { get; set; } [Data] public ushort MaxDamage { get; set; } [Data] public ushort MinDamage { get; set; } [Data] public ushort PhysicalWeakness { get; set; } [Data] public ushort FireWeakness { get; set; } [Data] public ushort IceWeakness { get; set; } [Data] public ushort ThunderWeakness { get; set; } [Data] public ushort DarkWeakness { get; set; } [Data] public ushort LightWeakness { get; set; } [Data] public ushort GeneralWeakness { get; set; } [Data] public ushort Experience { get; set; } [Data] public ushort Prize { get; set; } [Data] public ushort BonusLevel { get; set; } public static List<Enmp> Read(Stream stream) => BaseTable<Enmp>.Read(stream); public static void Write(Stream stream, IEnumerable<Enmp> items) => BaseTable<Enmp>.Write(stream, 2, items); } }
38.096774
85
0.616427
[ "Apache-2.0" ]
1234567890num/OpenKh
OpenKh.Kh2/Battle/Enmp.cs
1,181
C#
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // 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.Collections.Generic; namespace Microsoft.AzureStack.Commands { using System; using System.Management.Automation; using Microsoft.WindowsAzure.Commands.Common; using Microsoft.AzureStack.Management; using Microsoft.AzureStack.Management.Models; /// <summary> /// New Subscription Cmdlet /// </summary> [Cmdlet(VerbsCommon.New, Nouns.ManagedSubscription)] [OutputType(typeof(SubscriptionDefinition))] public class NewManagedSubscription : AdminApiCmdlet { /// <summary> /// Gets or sets the subscription id. /// </summary> [Parameter(ValueFromPipelineByPropertyName = true, Mandatory = false)] [ValidateGuidNotEmpty] public Guid SubscriptionId { get; set; } /// <summary> /// Gets or sets the owner. /// </summary> [Parameter(Mandatory = true)] [ValidateLength(1, 128)] [ValidateNotNull] public string Owner { get; set; } /// <summary> /// Gets or sets the identifier of the offer. /// </summary> [Parameter(Mandatory = true)] [ValidateLength(1, 128)] [ValidateNotNull] public string OfferId { get; set; } /// <summary> /// Gets or sets the display name. /// </summary> [Parameter] [ValidateLength(1, 128)] [ValidateNotNull] public string DisplayName { get; set; } /// <summary> /// This queue is used by the tests to assign fixed SubscritionIds /// every time the test runs /// </summary> public static Queue<Guid> SubscriptionIds { get; set; } static NewManagedSubscription() { SubscriptionIds = new Queue<Guid>(); } /// <summary> /// Gets the subscription definition. /// </summary> protected SubscriptionDefinition GetSubscriptionDefinition() { return new SubscriptionDefinition() { SubscriptionId = (NewManagedSubscription.SubscriptionIds.Count == 0 ? Guid.NewGuid() : NewManagedSubscription.SubscriptionIds.Dequeue()).ToString(), DisplayName = this.DisplayName, OfferId = this.OfferId, OfferName = GetAndValidateOfferName(this.OfferId), Owner = this.Owner, State = SubscriptionState.Enabled, }; } /// <summary> /// Performs the API operation(s) against managed subscriptions. /// </summary> protected override object ExecuteCore() { using (var client = this.GetAzureStackClient(this.SubscriptionId)) { this.WriteVerbose(Resources.CreatingNewSubscription.FormatArgs(this.Owner, this.OfferId, this.DisplayName)); var parameters = new ManagedSubscriptionCreateOrUpdateParameters(this.GetSubscriptionDefinition()); return client.ManagedSubscriptions.CreateOrUpdate(parameters).Subscription; } } /// <summary> /// Gets and validates the name of the offer. /// </summary> /// <param name="offerId">The offer identifier.</param> private static string GetAndValidateOfferName(string offerId) { ArgumentValidator.ValidateNotNull("offerId", offerId); var parts = offerId.Trim('/').Split('/'); if (parts.Length != 4 || !"delegatedProviders".EqualsInsensitively(parts[0]) || !"offers".EqualsInsensitively(parts[2]) || string.IsNullOrWhiteSpace(parts[1]) || string.IsNullOrWhiteSpace(parts[3])) { throw new ArgumentException( message: "Invalid offer identifier; must be of the form '/delegatedProviders/{providerId}/offers/{offerName}'", paramName: "offerId"); } return parts[3]; } } }
38.492308
132
0.557554
[ "MIT" ]
Peter-Schneider/azure-powershell
src/ResourceManager/AzureStackAdmin/Commands.AzureStackAdmin/Microsoft.Subscriptions/Subscriptions/NewManagedSubscription.cs
4,877
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConnectedComponents { internal class SubObjectConnComps { private ClosestPatches cp = null; internal SubObjectConnComps(ClosestPatches cp) { this.cp = cp; } internal Dictionary<int, List<Position>> Find(List<Position> positions, Position[,] board, int patchSize) { int labelCount = 1; var allLabels = new Dictionary<int, Label>(); Dictionary<Position, bool> processedPositions = new Dictionary<Position, bool>(); for (int i = 0; i < positions.Count; i++) { Position currPosition = positions[i]; IEnumerable<int> neighbouringLabels = GetNeighbouringLabelsOfSameCluster(currPosition, board, patchSize); int currentLabel = -1; if (!neighbouringLabels.Any()) { currentLabel = labelCount; allLabels.Add(currentLabel, new Label(currentLabel)); labelCount++; } else { currentLabel = neighbouringLabels.Min(n => allLabels[n].GetRoot().Name); Label root = allLabels[currentLabel].GetRoot(); foreach (var neighbor in neighbouringLabels) { if (root.Name != allLabels[neighbor].GetRoot().Name) { allLabels[neighbor].Join(allLabels[currentLabel]); } } } //board[currPosition.Y, currPosition.X].Label = currentLabel; currPosition.Label = currentLabel; if (i % 10000 == 0) Console.WriteLine("{0}", i); } // split patches into separate lists based on the label Dictionary<int, List<Position>> patterns = AggregatePatterns(allLabels, positions); return patterns; } private IEnumerable<int> GetNeighbouringLabelsOfSameCluster(Position position, Position[,] board, int patchSize) { Dictionary<int, Position> overlappingPatches = cp.GetOverlappingPatches(position, patchSize); var neighboringLabels = new List<int>(); Dictionary<int, Position>.ValueCollection values = overlappingPatches.Values; foreach (Position pos in values) { if (pos.Label != -1 && pos.HACCluster == position.HACCluster) neighboringLabels.Add(pos.Label); } return neighboringLabels; } private Dictionary<int, List<Position>> AggregatePatterns(Dictionary<int, Label> allLabels, List<Position> allPositions) { var objects = new Dictionary<int, List<Position>>(); for (int i = 0; i < allPositions.Count; i++) { Position pos = allPositions[i]; int objectNumber = pos.Label; if (objectNumber == -1) throw new Exception(String.Format("unlabelled position: {0}", pos.ToString())); if (objectNumber != -1) { objectNumber = allLabels[objectNumber].GetRoot().Name; pos.ObjectId = objectNumber; if (!objects.ContainsKey(objectNumber)) objects[objectNumber] = new List<Position>(); //patterns[patternNumber].Add(new Position(new Point(j, i), Color.Black)); objects[objectNumber].Add(allPositions[i]); } } return objects; } } }
35.63964
129
0.520222
[ "MIT" ]
garrethmartin/HSC_UML
graph_clustering/code/dotnetcore/ConnComponents/ConnectedComponents/SubObjectConnComps.cs
3,958
C#
using System.CodeDom; using System.Collections.Generic; using System.Linq; using BoDi; using TechTalk.SpecFlow.Generator.CodeDom; namespace TechTalk.SpecFlow.Generator.UnitTestProvider { public class NUnit3TestGeneratorProvider : IUnitTestGeneratorProvider { protected internal const string TESTFIXTURESETUP_ATTR_NUNIT3 = "NUnit.Framework.OneTimeSetUpAttribute"; protected internal const string TESTFIXTURETEARDOWN_ATTR_NUNIT3 = "NUnit.Framework.OneTimeTearDownAttribute"; protected internal const string PARALLELIZABLE_ATTR = "NUnit.Framework.ParallelizableAttribute"; protected internal const string TESTFIXTURE_ATTR = "NUnit.Framework.TestFixtureAttribute"; protected internal const string TESTFIXTURENAME_PROPERTY_NAME = "TestName"; protected internal const string TEST_ATTR = "NUnit.Framework.TestAttribute"; protected internal const string ROW_ATTR = "NUnit.Framework.TestCaseAttribute"; protected internal const string TESTCASENAME_PROPERTY_NAME = "TestName"; protected internal const string CATEGORY_ATTR = "NUnit.Framework.CategoryAttribute"; protected internal const string TESTSETUP_ATTR = "NUnit.Framework.SetUpAttribute"; protected internal const string TESTTEARDOWN_ATTR = "NUnit.Framework.TearDownAttribute"; protected internal const string IGNORE_ATTR = "NUnit.Framework.IgnoreAttribute"; protected internal const string DESCRIPTION_ATTR = "NUnit.Framework.DescriptionAttribute"; protected internal const string TESTCONTEXT_TYPE = "NUnit.Framework.TestContext"; protected internal const string TESTCONTEXT_INSTANCE = "NUnit.Framework.TestContext.CurrentContext"; public NUnit3TestGeneratorProvider(CodeDomHelper codeDomHelper) { CodeDomHelper = codeDomHelper; } protected CodeDomHelper CodeDomHelper { get; set; } public bool GenerateParallelCodeForFeature { get; set; } public virtual UnitTestGeneratorTraits GetTraits() { return UnitTestGeneratorTraits.RowTests | UnitTestGeneratorTraits.ParallelExecution; } public virtual void SetTestClassIgnore(TestClassGenerationContext generationContext) { CodeDomHelper.AddAttribute(generationContext.TestClass, IGNORE_ATTR, "Ignored feature"); } public virtual void SetTestMethodIgnore(TestClassGenerationContext generationContext, CodeMemberMethod testMethod) { CodeDomHelper.AddAttribute(testMethod, IGNORE_ATTR, "Ignored scenario"); } public virtual void SetTestClassInitializeMethod(TestClassGenerationContext generationContext) { CodeDomHelper.AddAttribute(generationContext.TestClassInitializeMethod, TESTFIXTURESETUP_ATTR_NUNIT3); } public virtual void SetTestClassCleanupMethod(TestClassGenerationContext generationContext) { CodeDomHelper.AddAttribute(generationContext.TestClassCleanupMethod, TESTFIXTURETEARDOWN_ATTR_NUNIT3); } public virtual void SetTestClassParallelize(TestClassGenerationContext generationContext) { CodeDomHelper.AddAttribute(generationContext.TestClass, PARALLELIZABLE_ATTR, new CodeAttributeArgument(new CodePrimitiveExpression(generationContext.TestClass.Name))); } public void SetTestClass(TestClassGenerationContext generationContext, string featureTitle, string featureDescription) { featureDescription = string.IsNullOrEmpty(featureDescription) ? featureTitle : featureDescription; CodeDomHelper.AddAttribute(generationContext.TestClass, TESTFIXTURE_ATTR, new CodeAttributeArgument(TESTFIXTURENAME_PROPERTY_NAME, new CodePrimitiveExpression(featureTitle))); CodeDomHelper.AddAttribute(generationContext.TestClass, DESCRIPTION_ATTR, featureDescription); } public void SetTestClassCategories(TestClassGenerationContext generationContext, IEnumerable<string> featureCategories) { CodeDomHelper.AddAttributeForEachValue(generationContext.TestClass, CATEGORY_ATTR, featureCategories); } public virtual void FinalizeTestClass(TestClassGenerationContext generationContext) { // testRunner.ScenarioContext.ScenarioContainer.RegisterInstanceAs<NUnit.Framework.TestContext>(NUnit.Framework.TestContext.CurrentContext); generationContext.ScenarioInitializeMethod.Statements.Add( new CodeMethodInvokeExpression( new CodeMethodReferenceExpression( new CodePropertyReferenceExpression( new CodePropertyReferenceExpression( new CodeFieldReferenceExpression(null, generationContext.TestRunnerField.Name), nameof(ScenarioContext)), nameof(ScenarioContext.ScenarioContainer)), nameof(IObjectContainer.RegisterInstanceAs), new CodeTypeReference(TESTCONTEXT_TYPE)), new CodeVariableReferenceExpression(TESTCONTEXT_INSTANCE))); } public void SetTestInitializeMethod(TestClassGenerationContext generationContext) { CodeDomHelper.AddAttribute(generationContext.TestInitializeMethod, TESTSETUP_ATTR); } public void SetTestCleanupMethod(TestClassGenerationContext generationContext) { CodeDomHelper.AddAttribute(generationContext.TestCleanupMethod, TESTTEARDOWN_ATTR); } private void SetTestDescription(CodeMemberMethod testMethod, string description) { CodeDomHelper.AddAttribute(testMethod, DESCRIPTION_ATTR, description); } public void SetTestMethod(TestClassGenerationContext generationContext, CodeMemberMethod testMethod, string friendlyTestName, string testDescription = null) { testDescription = string.IsNullOrEmpty(testDescription) ? friendlyTestName : testDescription; CodeDomHelper.AddAttribute(testMethod, ROW_ATTR, new CodeAttributeArgument(TESTCASENAME_PROPERTY_NAME, new CodePrimitiveExpression(friendlyTestName))); SetTestDescription(testMethod, testDescription); } public void SetTestMethodCategories(TestClassGenerationContext generationContext, CodeMemberMethod testMethod, IEnumerable<string> scenarioCategories) { CodeDomHelper.AddAttributeForEachValue(testMethod, CATEGORY_ATTR, scenarioCategories); } public void SetRowTest(TestClassGenerationContext generationContext, CodeMemberMethod testMethod, string scenarioTitle, string scenarioDescription = null) { scenarioDescription = string.IsNullOrEmpty(scenarioDescription) ? scenarioTitle : scenarioDescription; SetTestDescription(testMethod, scenarioDescription); } public void SetRow(TestClassGenerationContext generationContext, CodeMemberMethod testMethod, string scenarioTitle, IEnumerable<string> arguments, IEnumerable<string> tags, bool isIgnored) { var args = arguments.Select( arg => new CodeAttributeArgument(new CodePrimitiveExpression(arg))).ToList(); // addressing ReSharper bug: TestCase attribute with empty string[] param causes inconclusive result - https://github.com/techtalk/SpecFlow/issues/116 bool hasExampleTags = tags.Any(); var exampleTagExpressionList = tags.Select(t => new CodePrimitiveExpression(t)); var exampleTagsExpression = hasExampleTags ? new CodeArrayCreateExpression(typeof(string[]), exampleTagExpressionList.ToArray()) : (CodeExpression) new CodePrimitiveExpression(null); args.Add(new CodeAttributeArgument(exampleTagsExpression)); // adds 'Category' named parameter so that NUnit also understands that this test case belongs to the given categories if (hasExampleTags) { CodeExpression exampleTagsStringExpr = new CodePrimitiveExpression(string.Join(",", tags.ToArray())); args.Add(new CodeAttributeArgument("Category", exampleTagsStringExpr)); } if (isIgnored) args.Add(new CodeAttributeArgument("Ignored", new CodePrimitiveExpression(true))); var outlineScenarioTitle = arguments.Any() ? $"{scenarioTitle}({string.Join(",", arguments)})" : scenarioTitle; args.Add(new CodeAttributeArgument(TESTCASENAME_PROPERTY_NAME, new CodePrimitiveExpression(outlineScenarioTitle))); CodeDomHelper.AddAttribute(testMethod, ROW_ATTR, args.ToArray()); } public void SetTestMethodAsRow(TestClassGenerationContext generationContext, CodeMemberMethod testMethod, string scenarioTitle, string exampleSetName, string variantName, IEnumerable<KeyValuePair<string, string>> arguments) { // doing nothing since we support RowTest } } }
56.151515
232
0.715057
[ "BSD-3-Clause", "Apache-2.0", "MIT" ]
dannyBies/SpecFlow
TechTalk.SpecFlow.Generator/UnitTestProvider/NUnit3TestGeneratorProvider.cs
9,265
C#
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** 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.Aws.WafV2.Inputs { public sealed class RuleGroupRuleStatementAndStatementStatementNotStatementStatementByteMatchStatementFieldToMatchUriPathArgs : Pulumi.ResourceArgs { public RuleGroupRuleStatementAndStatementStatementNotStatementStatementByteMatchStatementFieldToMatchUriPathArgs() { } } }
33.05
151
0.782148
[ "ECL-2.0", "Apache-2.0" ]
Otanikotani/pulumi-aws
sdk/dotnet/WafV2/Inputs/RuleGroupRuleStatementAndStatementStatementNotStatementStatementByteMatchStatementFieldToMatchUriPathArgs.cs
661
C#