content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
//------------------------------------------------------------------------------ // <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 DownloaderTest.Properties { /// <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", "4.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 ((resourceMan == null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("DownloaderTest.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; } } } }
38.680556
180
0.60395
[ "MIT" ]
daelsepara/FastDownloaderAsync
DownloaderTest/Properties/Resources.Designer.cs
2,787
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Linq; using System.Threading.Tasks; using Microsoft.Data.DataView; using Microsoft.ML; using Microsoft.ML.CommandLine; using Microsoft.ML.Data; using Microsoft.ML.EntryPoints; using Microsoft.ML.Internal.CpuMath; using Microsoft.ML.Internal.Internallearn; using Microsoft.ML.Internal.Utilities; using Microsoft.ML.Numeric; using Microsoft.ML.Runtime; using Microsoft.ML.Trainers; [assembly: LoadableClass(KMeansPlusPlusTrainer.Summary, typeof(KMeansPlusPlusTrainer), typeof(KMeansPlusPlusTrainer.Options), new[] { typeof(SignatureClusteringTrainer), typeof(SignatureTrainer) }, KMeansPlusPlusTrainer.UserNameValue, KMeansPlusPlusTrainer.LoadNameValue, KMeansPlusPlusTrainer.ShortName, "KMeans")] [assembly: LoadableClass(typeof(void), typeof(KMeansPlusPlusTrainer), null, typeof(SignatureEntryPointModule), "KMeans")] namespace Microsoft.ML.Trainers { /// <include file='./doc.xml' path='doc/members/member[@name="KMeans++"]/*' /> public class KMeansPlusPlusTrainer : TrainerEstimatorBase<ClusteringPredictionTransformer<KMeansModelParameters>, KMeansModelParameters> { internal const string LoadNameValue = "KMeansPlusPlus"; internal const string UserNameValue = "KMeans++ Clustering"; internal const string ShortName = "KM"; internal const string Summary = "K-means is a popular clustering algorithm. With K-means, the data is clustered into a specified " + "number of clusters in order to minimize the within-cluster sum of squares. K-means++ improves upon K-means by using a better " + "method for choosing the initial cluster centers."; public enum InitializationAlgorithm { KMeansPlusPlus = 0, Random = 1, KMeansYinyang = 2 } [BestFriend] internal static class Defaults { /// <value>The number of clusters.</value> public const int NumberOfClusters = 5; } public sealed class Options : UnsupervisedTrainerInputBaseWithWeight { /// <summary> /// The number of clusters. /// </summary> [Argument(ArgumentType.AtMostOnce, HelpText = "The number of clusters", SortOrder = 50, Name = "K")] [TGUI(SuggestedSweeps = "5,10,20,40")] [TlcModule.SweepableDiscreteParam("K", new object[] { 5, 10, 20, 40 })] public int NumberOfClusters = Defaults.NumberOfClusters; /// <summary> /// Cluster initialization algorithm. /// </summary> [Argument(ArgumentType.AtMostOnce, HelpText = "Cluster initialization algorithm", ShortName = "init")] public InitializationAlgorithm InitializationAlgorithm = InitializationAlgorithm.KMeansYinyang; /// <summary> /// Tolerance parameter for trainer convergence. Low = slower, more accurate. /// </summary> [Argument(ArgumentType.AtMostOnce, HelpText = "Tolerance parameter for trainer convergence. Low = slower, more accurate", Name = "OptTol", ShortName = "ot")] [TGUI(Label = "Optimization Tolerance", Description = "Threshold for trainer convergence")] public float OptimizationTolerance = (float)1e-7; /// <summary> /// Maximum number of iterations. /// </summary> [Argument(ArgumentType.AtMostOnce, HelpText = "Maximum number of iterations.", ShortName = "maxiter")] [TGUI(Label = "Max Number of Iterations")] public int MaximumNumberOfIterations = 1000; /// <summary> /// Memory budget (in MBs) to use for KMeans acceleration. /// </summary> [Argument(ArgumentType.AtMostOnce, HelpText = "Memory budget (in MBs) to use for KMeans acceleration", Name = "AccelMemBudgetMb", ShortName = "accelMemBudgetMb")] [TGUI(Label = "Memory Budget (in MBs) for KMeans Acceleration")] public int AccelerationMemoryBudgetMb = 4 * 1024; // by default, use at most 4 GB /// <summary> /// Degree of lock-free parallelism. Defaults to automatic. Determinism not guaranteed. /// </summary> [Argument(ArgumentType.AtMostOnce, HelpText = "Degree of lock-free parallelism. Defaults to automatic. Determinism not guaranteed.", ShortName = "nt,t,threads", SortOrder = 50)] [TGUI(Label = "Number of threads")] public int? NumberOfThreads; } private readonly int _k; private readonly int _maxIterations; // max number of iterations to train private readonly float _convergenceThreshold; // convergence thresholds private readonly long _accelMemBudgetMb; private readonly InitializationAlgorithm _initAlgorithm; private readonly int _numThreads; private readonly string _featureColumn; public override TrainerInfo Info { get; } private protected override PredictionKind PredictionKind => PredictionKind.Clustering; /// <summary> /// Initializes a new instance of <see cref="KMeansPlusPlusTrainer"/> /// </summary> /// <param name="env">The <see cref="IHostEnvironment"/> to use.</param> /// <param name="options">The advanced options of the algorithm.</param> internal KMeansPlusPlusTrainer(IHostEnvironment env, Options options) : base(Contracts.CheckRef(env, nameof(env)).Register(LoadNameValue), TrainerUtils.MakeR4VecFeature(options.FeatureColumnName), default, TrainerUtils.MakeR4ScalarWeightColumn(options.ExampleWeightColumnName)) { Host.CheckValue(options, nameof(options)); Host.CheckUserArg(options.NumberOfClusters > 0, nameof(options.NumberOfClusters), "Must be positive"); _featureColumn = options.FeatureColumnName; _k = options.NumberOfClusters; Host.CheckUserArg(options.MaximumNumberOfIterations > 0, nameof(options.MaximumNumberOfIterations), "Must be positive"); _maxIterations = options.MaximumNumberOfIterations; Host.CheckUserArg(options.OptimizationTolerance > 0, nameof(options.OptimizationTolerance), "Tolerance must be positive"); _convergenceThreshold = options.OptimizationTolerance; Host.CheckUserArg(options.AccelerationMemoryBudgetMb > 0, nameof(options.AccelerationMemoryBudgetMb), "Must be positive"); _accelMemBudgetMb = options.AccelerationMemoryBudgetMb; _initAlgorithm = options.InitializationAlgorithm; Host.CheckUserArg(!options.NumberOfThreads.HasValue || options.NumberOfThreads > 0, nameof(options.NumberOfThreads), "Must be either null or a positive integer."); _numThreads = ComputeNumThreads(options.NumberOfThreads); Info = new TrainerInfo(); } private protected override KMeansModelParameters TrainModelCore(TrainContext context) { Host.CheckValue(context, nameof(context)); var data = context.TrainingSet; data.CheckFeatureFloatVector(out int dimensionality); Contracts.Assert(dimensionality > 0); using (var ch = Host.Start("Training")) { return TrainCore(ch, data, dimensionality); } } private KMeansModelParameters TrainCore(IChannel ch, RoleMappedData data, int dimensionality) { Host.AssertValue(ch); ch.AssertValue(data); // REVIEW: In high-dimensionality cases this is less than ideal and we should consider // using sparse buffers for the centroids. // The coordinates of the final centroids at the end of the training. During training // it holds the centroids of the previous iteration. var centroids = new VBuffer<float>[_k]; for (int i = 0; i < _k; i++) centroids[i] = VBufferUtils.CreateDense<float>(dimensionality); ch.Info("Initializing centroids"); long missingFeatureCount; long totalTrainingInstances; CursOpt cursorOpt = CursOpt.Id | CursOpt.Features; if (data.Schema.Weight.HasValue) cursorOpt |= CursOpt.Weight; var cursorFactory = new FeatureFloatVectorCursor.Factory(data, cursorOpt); // REVIEW: It would be nice to extract these out into subcomponents in the future. We should // revisit and even consider breaking these all into individual KMeans-flavored trainers, they // all produce a valid set of output centroids with various trade-offs in runtime (with perhaps // random initialization creating a set that's not terribly useful.) They could also be extended to // pay attention to their incoming set of centroids and incrementally train. if (_initAlgorithm == InitializationAlgorithm.KMeansPlusPlus) { KMeansPlusPlusInit.Initialize(Host, _numThreads, ch, cursorFactory, _k, dimensionality, centroids, out missingFeatureCount, out totalTrainingInstances); } else if (_initAlgorithm == InitializationAlgorithm.Random) { KMeansRandomInit.Initialize(Host, _numThreads, ch, cursorFactory, _k, centroids, out missingFeatureCount, out totalTrainingInstances); } else { // Defaulting to KMeans|| initialization. KMeansBarBarInitialization.Initialize(Host, _numThreads, ch, cursorFactory, _k, dimensionality, centroids, _accelMemBudgetMb, out missingFeatureCount, out totalTrainingInstances); } KMeansUtils.VerifyModelConsistency(centroids); ch.Info("Centroids initialized, starting main trainer"); KMeansLloydsYinYangTrain.Train( Host, _numThreads, ch, cursorFactory, totalTrainingInstances, _k, dimensionality, _maxIterations, _accelMemBudgetMb, _convergenceThreshold, centroids); KMeansUtils.VerifyModelConsistency(centroids); ch.Info("Model trained successfully on {0} instances", totalTrainingInstances); if (missingFeatureCount > 0) { ch.Warning( "{0} instances with missing features detected and ignored. Consider using MissingHandler.", missingFeatureCount); } return new KMeansModelParameters(Host, _k, centroids, copyIn: true); } private static int ComputeNumThreads(int? argNumThreads) { // REVIEW: For small data sets it would be nice to clamp down on concurrency, it // isn't going to get us a performance improvement. int maxThreads = Environment.ProcessorCount / 2; // If we specified a number of threads that's fine, but it must be below maxThreads. if (argNumThreads.HasValue) maxThreads = Math.Min(maxThreads, argNumThreads.Value); return Math.Max(1, maxThreads); } [TlcModule.EntryPoint(Name = "Trainers.KMeansPlusPlusClusterer", Desc = Summary, UserName = UserNameValue, ShortName = ShortName)] internal static CommonOutputs.ClusteringOutput TrainKMeans(IHostEnvironment env, Options input) { Contracts.CheckValue(env, nameof(env)); var host = env.Register("TrainKMeans"); host.CheckValue(input, nameof(input)); EntryPointUtils.CheckInputArgs(host, input); return TrainerEntryPointsUtils.Train<Options, CommonOutputs.ClusteringOutput>(host, input, () => new KMeansPlusPlusTrainer(host, input), getWeight: () => TrainerEntryPointsUtils.FindColumn(host, input.TrainingData.Schema, input.ExampleWeightColumnName)); } private protected override SchemaShape.Column[] GetOutputColumnsCore(SchemaShape inputSchema) { return new[] { new SchemaShape.Column(DefaultColumnNames.Score, SchemaShape.Column.VectorKind.Vector, NumberDataViewType.Single, false, new SchemaShape(AnnotationUtils.GetTrainerOutputAnnotation())), new SchemaShape.Column(DefaultColumnNames.PredictedLabel, SchemaShape.Column.VectorKind.Scalar, NumberDataViewType.UInt32, true, new SchemaShape(AnnotationUtils.GetTrainerOutputAnnotation())) }; } private protected override ClusteringPredictionTransformer<KMeansModelParameters> MakeTransformer(KMeansModelParameters model, DataViewSchema trainSchema) => new ClusteringPredictionTransformer<KMeansModelParameters>(Host, model, trainSchema, _featureColumn); } internal static class KMeansPlusPlusInit { private const float Epsilon = (float)1e-15; /// <summary> /// Initialize starting centroids via KMeans++ algorithm. This algorithm will always run single-threaded, /// regardless of the value of <paramref name="numThreads" />. /// </summary> public static void Initialize( IHost host, int numThreads, IChannel ch, FeatureFloatVectorCursor.Factory cursorFactory, int k, int dimensionality, VBuffer<float>[] centroids, out long missingFeatureCount, out long totalTrainingInstances, bool showWarning = true) { missingFeatureCount = 0; totalTrainingInstances = 0; var stopWatch = new System.Diagnostics.Stopwatch(); stopWatch.Start(); const int checkIterations = 5; float[] centroidL2s = new float[k]; // Need two vbuffers - one for the features of the current row, and one for the features of // the "candidate row". var candidate = default(VBuffer<float>); using (var pCh = host.StartProgressChannel("KMeansPlusPlusInitialize")) { int i = 0; pCh.SetHeader(new ProgressHeader("centroids"), (e) => e.SetProgress(0, i, k)); for (i = 0; i < k; i++) { // Print a message to user if the anticipated time for initializing is more than an hour. if (i == checkIterations) { stopWatch.Stop(); var elapsedHours = stopWatch.Elapsed.TotalHours; var expectedHours = elapsedHours * k * (k - 1) / (checkIterations * (checkIterations - 1)); if (expectedHours > 1 && showWarning) { ch.Warning("Expected time to initialize all {0} clusters is {1:0} minutes. " + "You can use init=KMeansParallel to switch to faster initialization.", k, expectedHours * 60); } } // initializing i-th centroid Double cumulativeWeight = 0; // sum of weights accumulated so far float? cachedCandidateL2 = null; bool haveCandidate = false; // on all iterations except 0's, we calculate L2 norm of every instance and cache the current candidate's using (var cursor = cursorFactory.Create()) { while (cursor.MoveNext()) { float probabilityWeight; float l2 = 0; if (i == 0) { // This check is only performed once, at the first pass of initialization if (dimensionality != cursor.Features.Length) { throw ch.Except( "Dimensionality doesn't match, expected {0}, got {1}", dimensionality, cursor.Features.Length); } probabilityWeight = 1; } else { l2 = VectorUtils.NormSquared(cursor.Features); probabilityWeight = float.PositiveInfinity; for (int j = 0; j < i; j++) { var distance = -2 * VectorUtils.DotProduct(in cursor.Features, in centroids[j]) + l2 + centroidL2s[j]; probabilityWeight = Math.Min(probabilityWeight, distance); } ch.Assert(FloatUtils.IsFinite(probabilityWeight)); } if (probabilityWeight > 0) { probabilityWeight *= cursor.Weight; // as a result of numerical error, we could get negative distance, do not decrease the sum cumulativeWeight += probabilityWeight; if (probabilityWeight > Epsilon && host.Rand.NextSingle() < probabilityWeight / cumulativeWeight) { // again, numerical error may cause selection of the same candidate twice, so ensure that the distance is non-trivially positive Utils.Swap(ref cursor.Features, ref candidate); haveCandidate = true; if (i > 0) cachedCandidateL2 = l2; } } } if (i == 0) { totalTrainingInstances = cursor.KeptRowCount; missingFeatureCount = cursor.BadFeaturesRowCount; } } // persist the candidate as a new centroid if (!haveCandidate) { throw ch.Except( "Not enough distinct instances to populate {0} clusters (only found {1} distinct instances)", k, i); } candidate.CopyToDense(ref centroids[i]); centroidL2s[i] = cachedCandidateL2 ?? VectorUtils.NormSquared(candidate); } } } } /// <summary> /// An instance of this class is used by SharedStates in YinYangTrainer /// and KMeansBarBarInitialization. It effectively bounds MaxInstancesToAccelerate and /// initializes RowIndexGetter. /// </summary> internal sealed class KMeansAcceleratedRowMap { // Retrieves the row's index for per-instance data. If the // row is not assigned an index (it occurred after 'maxInstancesToAccelerate') // or we are not accelerating then this returns -1. public readonly KMeansUtils.RowIndexGetter RowIndexGetter; public readonly bool IsAccelerated; public readonly int MaxInstancesToAccelerate; // When using parallel row cursors, there is no fixed, stable index for // each row. Instead the RowCursor provides a stable ID across multiple // cursorings. We map those IDs into an index to poke into the per instance // structures. private readonly HashArray<DataViewRowId> _parallelIndexLookup; public KMeansAcceleratedRowMap(FeatureFloatVectorCursor.Factory factory, IChannel ch, long baseMaxInstancesToAccelerate, long totalTrainingInstances, bool isParallel) { Contracts.AssertValue(factory); Contracts.AssertValue(ch); Contracts.Assert(totalTrainingInstances > 0); Contracts.Assert(baseMaxInstancesToAccelerate >= 0); // MaxInstancesToAccelerate is bound by the .Net array size limitation for now. if (baseMaxInstancesToAccelerate > Utils.ArrayMaxSize) baseMaxInstancesToAccelerate = Utils.ArrayMaxSize; if (baseMaxInstancesToAccelerate > totalTrainingInstances) baseMaxInstancesToAccelerate = totalTrainingInstances; else if (baseMaxInstancesToAccelerate > 0) ch.Info("Accelerating the first {0} instances", baseMaxInstancesToAccelerate); if (baseMaxInstancesToAccelerate == 0) RowIndexGetter = (FeatureFloatVectorCursor cur) => -1; else { MaxInstancesToAccelerate = (int)baseMaxInstancesToAccelerate; IsAccelerated = true; if (!isParallel) RowIndexGetter = (FeatureFloatVectorCursor cur) => cur.Row.Position < baseMaxInstancesToAccelerate ? (int)cur.Row.Position : -1; else { _parallelIndexLookup = BuildParallelIndexLookup(factory); RowIndexGetter = (FeatureFloatVectorCursor cur) => { int idx; // Sets idx to -1 on failure to find. _parallelIndexLookup.TryGetIndex(cur.Id, out idx); return idx; }; } } } /// <summary> /// Initializes the parallel index lookup HashArray using a sequential RowCursor. We /// preinitialize the HashArray so we can perform lock-free lookup operations during /// the primary KMeans pass. /// </summary> private HashArray<DataViewRowId> BuildParallelIndexLookup(FeatureFloatVectorCursor.Factory factory) { Contracts.AssertValue(factory); HashArray<DataViewRowId> lookup = new HashArray<DataViewRowId>(); int n = 0; using (var cursor = factory.Create()) { while (cursor.MoveNext() && n < MaxInstancesToAccelerate) { lookup.Add(cursor.Id); n++; } } Contracts.Check(lookup.Count == n); return lookup; } } internal static class KMeansBarBarInitialization { /// <summary> /// Data for optimizing KMeans|| initialization. Very similar to SharedState class /// For every instance, there is a space for the best weight and best cluster computed. /// /// In this class, new clusters mean the clusters that were added to the cluster set /// in the previous round of KMeans|| and old clusters are the rest of them (the ones /// that were added in the rounds before the previous one). /// /// In every round of KMeans||, numSamplesPerRound new clusters are added to the set of clusters. /// There are 'numRounds' number of rounds. We compute and store the distance of each new /// cluster from every round to all of the previous clusters and use it /// to avoid unnecessary computation by applying the triangle inequality. /// </summary> private sealed class SharedState { private readonly KMeansAcceleratedRowMap _acceleratedRowMap; public KMeansUtils.RowIndexGetter RowIndexGetter { get { return _acceleratedRowMap.RowIndexGetter; } } // _bestCluster holds the index of the closest cluster for an instance. // Note that this array is only allocated for MaxInstancesToAccelerate elements. private readonly int[] _bestCluster; // _bestWeight holds the weight of instance x to _bestCluster[x] where weight(x) = dist(x, _bestCluster[x])^2 - norm(x)^2. // Note that this array is only allocated for MaxInstancesToAccelerate elements. private readonly float[] _bestWeight; // The distance of each newly added cluster from the previous round to every old cluster // the first dimension of this array is the size of numSamplesPerRound // and the second dimension is the size of numRounds * numSamplesPerRound. // _clusterDistances[i][j] = dist(cluster[i+clusterPrevCount], cluster[j]) // where clusterPrevCount-1 is the last index of the old clusters // and new clusters are stored in cluster[cPrevIdx..clusterCount-1] where // clusterCount-1 is the last index of the clusters. private readonly float[,] _clusterDistances; public SharedState(FeatureFloatVectorCursor.Factory factory, IChannel ch, long baseMaxInstancesToAccelerate, long clusterBytes, bool isParallel, int numRounds, int numSamplesPerRound, long totalTrainingInstances) { Contracts.AssertValue(factory); Contracts.AssertValue(ch); Contracts.Assert(numRounds > 0); Contracts.Assert(numSamplesPerRound > 0); Contracts.Assert(totalTrainingInstances > 0); _acceleratedRowMap = new KMeansAcceleratedRowMap(factory, ch, baseMaxInstancesToAccelerate, totalTrainingInstances, isParallel); Contracts.Assert(_acceleratedRowMap.MaxInstancesToAccelerate >= 0, "MaxInstancesToAccelerate cannot be negative as KMeansAcceleratedRowMap sets it to 0 when baseMaxInstancesToAccelerate is negative"); // If maxInstanceToAccelerate is positive, it means that there was enough room to fully allocate clusterDistances // and allocate _bestCluster and _bestWeight as much as possible. if (_acceleratedRowMap.MaxInstancesToAccelerate > 0) { _clusterDistances = new float[numSamplesPerRound, numRounds * numSamplesPerRound]; _bestCluster = new int[_acceleratedRowMap.MaxInstancesToAccelerate]; _bestWeight = new float[_acceleratedRowMap.MaxInstancesToAccelerate]; for (int i = 0; i < _acceleratedRowMap.MaxInstancesToAccelerate; i++) { _bestCluster[i] = -1; _bestWeight[i] = float.MaxValue; } } else ch.Info("There was not enough room to store distances of clusters from each other for acceleration of KMeans|| initialization. A memory efficient approach is used instead."); } public int GetBestCluster(int idx) { return _bestCluster[idx]; } public float GetBestWeight(int idx) { return _bestWeight[idx]; } /// <summary> /// When assigning an accelerated row to a cluster, we store away the weight /// to its closest cluster, as well as the identity of the new /// closest cluster. Note that bestWeight can be negative since it is /// corresponding to the weight of a distance which does not have /// the L2 norm of the point itself. /// </summary> public void SetInstanceCluster(int n, float bestWeight, int bestCluster) { Contracts.Assert(0 <= n && n < _acceleratedRowMap.MaxInstancesToAccelerate); Contracts.AssertValue(_clusterDistances); Contracts.Assert(0 <= bestCluster && bestCluster < _clusterDistances.GetLength(1), "bestCluster must be between 0..clusterCount-1"); // Update best cluster and best weight accordingly. _bestCluster[n] = bestCluster; _bestWeight[n] = bestWeight; } /// <summary> /// Computes and stores the distance of a new cluster to an old cluster /// <paramref name="newClusterFeatures"/> must be between 0..numSamplesPerRound-1. /// </summary> public void SetClusterDistance(int newClusterIdxWithinSample, in VBuffer<float> newClusterFeatures, float newClusterL2, int oldClusterIdx, in VBuffer<float> oldClusterFeatures, float oldClusterL2) { if (_clusterDistances != null) { Contracts.Assert(newClusterL2 >= 0); Contracts.Assert(0 <= newClusterIdxWithinSample && newClusterIdxWithinSample < _clusterDistances.GetLength(0), "newClusterIdxWithinSample must be between 0..numSamplesPerRound-1"); Contracts.Assert(0 <= oldClusterIdx && oldClusterIdx < _clusterDistances.GetLength(1)); _clusterDistances[newClusterIdxWithinSample, oldClusterIdx] = MathUtils.Sqrt(newClusterL2 - 2 * VectorUtils.DotProduct(in newClusterFeatures, in oldClusterFeatures) + oldClusterL2); } } /// <summary> /// This function is the key to use triangle inequality. Given an instance x distance to the best /// old cluster, cOld, and distance of a new cluster, cNew, to cOld, this function evaluates whether /// the distance computation of dist(x,cNew) can be avoided. /// </summary> public bool CanWeightComputationBeAvoided(float instanceDistanceToBestOldCluster, int bestOldCluster, int newClusterIdxWithinSample) { Contracts.Assert(instanceDistanceToBestOldCluster >= 0); Contracts.Assert(0 <= newClusterIdxWithinSample && newClusterIdxWithinSample < _clusterDistances.GetLength(0), "newClusterIdxWithinSample must be between 0..numSamplesPerRound-1"); Contracts.Assert((_clusterDistances == null) || (bestOldCluster == -1 || (0 <= bestOldCluster && bestOldCluster < _clusterDistances.GetLength(1))), "bestOldCluster must be -1 (not set/not enought room) or between 0..clusterCount-1"); // Only use this if the memory was allocated for _clusterDistances and bestOldCluster index is valid. if (_clusterDistances != null && bestOldCluster != -1) { // This is dist(cNew,cOld). float distanceBetweenOldAndNewClusters = _clusterDistances[newClusterIdxWithinSample, bestOldCluster]; // Use triangle inequality to evaluate whether weight computation can be avoided // dist(x,cNew) + dist(x,cOld) > dist(cOld,cNew) => // dist(x,cNew) > dist(cOld,cNew) - dist(x,cOld) => // If dist(cOld,cNew) - dist(x,cOld) > dist(x,cOld), then dist(x,cNew) > dist(x,cOld). Therefore it is // not necessary to compute dist(x,cNew). if (distanceBetweenOldAndNewClusters - instanceDistanceToBestOldCluster > instanceDistanceToBestOldCluster) return true; } return false; } } /// <summary> /// This function finds the best cluster and the best weight for an instance using /// smart triangle inequality to avoid unnecessary weight computations. /// /// Note that <paramref name="needToStoreWeight"/> is used to avoid the storing the new cluster in /// final round. After the final round, best cluster information will be ignored. /// </summary> private static void FindBestCluster(in VBuffer<float> point, int pointRowIndex, SharedState initializationState, int clusterCount, int clusterPrevCount, VBuffer<float>[] clusters, float[] clustersL2s, bool needRealDistanceSquared, bool needToStoreWeight, out float minDistanceSquared, out int bestCluster) { Contracts.AssertValue(initializationState); Contracts.Assert(clusterCount > 0); Contracts.Assert(0 <= clusterPrevCount && clusterPrevCount < clusterCount); Contracts.AssertValue(clusters); Contracts.AssertValue(clustersL2s); bestCluster = -1; if (pointRowIndex != -1) // if the space was available for cur in initializationState. { // pointNorm is necessary for using triangle inequality. float pointNorm = VectorUtils.NormSquared(in point); // We have cached distance information for this point. bestCluster = initializationState.GetBestCluster(pointRowIndex); float bestWeight = initializationState.GetBestWeight(pointRowIndex); // This is used by CanWeightComputationBeAvoided function in order to shortcut weight computation. int bestOldCluster = bestCluster; float pointDistanceSquared = pointNorm + bestWeight; // Make pointDistanceSquared zero if it is negative, which it can be due to floating point instability. // Do this before taking the square root. pointDistanceSquared = (pointDistanceSquared >= 0.0f) ? pointDistanceSquared : 0.0f; float pointDistance = MathUtils.Sqrt(pointDistanceSquared); // bestCluster is the best cluster from 0 to cPrevIdx-1 and bestWeight is the corresponding weight. // So, this loop only needs to process clusters from cPrevIdx. for (int j = clusterPrevCount; j < clusterCount; j++) { if (initializationState.CanWeightComputationBeAvoided(pointDistance, bestOldCluster, j - clusterPrevCount)) { #if DEBUG // Lets check if our invariant actually holds Contracts.Assert(-2 * VectorUtils.DotProduct(in point, in clusters[j]) + clustersL2s[j] > bestWeight); #endif continue; } float weight = -2 * VectorUtils.DotProduct(in point, in clusters[j]) + clustersL2s[j]; if (bestWeight >= weight) { bestWeight = weight; bestCluster = j; } } if (needToStoreWeight && bestCluster != bestOldCluster) initializationState.SetInstanceCluster(pointRowIndex, bestWeight, bestCluster); if (needRealDistanceSquared) minDistanceSquared = bestWeight + pointNorm; else minDistanceSquared = bestWeight; } else { // We did not cache any information about this point. // So, we need to go over all clusters to find the best cluster. int discardSecondBestCluster; float discardSecondBestWeight; KMeansUtils.FindBestCluster(in point, clusters, clustersL2s, clusterCount, needRealDistanceSquared, out minDistanceSquared, out bestCluster, out discardSecondBestWeight, out discardSecondBestCluster); } } /// <summary> /// This method computes the memory requirement for _clusterDistances in SharedState (clusterBytes) and /// the maximum number of instances whose weight to the closest cluster can be memorized in order to avoid /// recomputation later. /// </summary> private static void ComputeAccelerationMemoryRequirement(long accelMemBudgetMb, int numSamplesPerRound, int numRounds, bool isParallel, out long maxInstancesToAccelerate, out long clusterBytes) { // Compute the memory requirement for _clusterDistances. clusterBytes = sizeof(float) * numSamplesPerRound // for each newly added cluster * numRounds * numSamplesPerRound; // for older cluster // Second, figure out how many instances can be accelerated. int bytesPerInstance = sizeof(int) // for bestCluster + sizeof(float) // for bestWeight + (isParallel ? sizeof(int) + 16 : 0); // for parallel rowCursor index lookup HashArray storage (16 bytes for RowId, 4 bytes for internal 'next' index) maxInstancesToAccelerate = Math.Max(0, (accelMemBudgetMb * 1024 * 1024 - clusterBytes) / bytesPerInstance); } /// <summary> /// KMeans|| Implementation, see https://theory.stanford.edu/~sergei/papers/vldb12-kmpar.pdf /// This algorithm will require: /// - (k * overSampleFactor * rounds * diminsionality * 4) bytes for the final sampled clusters. /// - (k * overSampleFactor * numThreads * diminsionality * 4) bytes for the per-round sampling. /// /// Uses memory in initializationState to cache distances and avoids unnecessary distance computations /// akin to YinYang-KMeans paper. /// /// Everywhere in this function, weight of an instance x from a cluster c means weight(x,c) = dist(x,c)^2-norm(x)^2. /// We store weight in most cases to avoid unnecessary computation of norm(x). /// </summary> public static void Initialize(IHost host, int numThreads, IChannel ch, FeatureFloatVectorCursor.Factory cursorFactory, int k, int dimensionality, VBuffer<float>[] centroids, long accelMemBudgetMb, out long missingFeatureCount, out long totalTrainingInstances) { Contracts.CheckValue(host, nameof(host)); host.CheckValue(ch, nameof(ch)); ch.CheckValue(cursorFactory, nameof(cursorFactory)); ch.CheckValue(centroids, nameof(centroids)); ch.CheckUserArg(numThreads > 0, nameof(KMeansPlusPlusTrainer.Options.NumberOfThreads), "Must be positive"); ch.CheckUserArg(k > 0, nameof(KMeansPlusPlusTrainer.Options.NumberOfClusters), "Must be positive"); ch.CheckParam(dimensionality > 0, nameof(dimensionality), "Must be positive"); ch.CheckUserArg(accelMemBudgetMb >= 0, nameof(KMeansPlusPlusTrainer.Options.AccelerationMemoryBudgetMb), "Must be non-negative"); int numRounds; int numSamplesPerRound; // If k is less than 60, we haven't reached the threshold where the coefficients in // the time complexity between KM|| and KM++ balance out to favor KM||. In this case // we push the number of rounds to k - 1 (we choose a single point before beginning // any round), and only take a single point per round. This effectively reduces KM|| to // KM++. This implementation is sill however advantageous as it uses parallel reservoir sampling // to parallelize each step. if (k < 60) { numRounds = k - 1; numSamplesPerRound = 1; } // From the paper, 5 rounds and l=2k is shown to achieve good results for real-world datasets // with large k values. else { numRounds = 5; int overSampleFactor = 2; numSamplesPerRound = overSampleFactor * k; } int totalSamples = numSamplesPerRound * numRounds + 1; using (var pCh = host.StartProgressChannel(" KMeansBarBarInitialization.Initialize")) { // KMeansParallel performs 'rounds' iterations through the dataset, an initialization // round to choose the first centroid, and a final iteration to weight the chosen centroids. // From a time-to-completion POV all these rounds take about the same amount of time. int logicalExternalRounds = 0; pCh.SetHeader(new ProgressHeader("rounds"), (e) => e.SetProgress(0, logicalExternalRounds, numRounds + 2)); // The final chosen points, to be approximately clustered to determine starting // centroids. VBuffer<float>[] clusters = new VBuffer<float>[totalSamples]; // L2s, kept for distance trick. float[] clustersL2s = new float[totalSamples]; int clusterCount = 0; int clusterPrevCount = -1; SharedState initializationState; { // First choose a single point to form the first cluster block using a random // sample. Heap<KMeansUtils.WeightedPoint>[] buffer = null; var rowStats = KMeansUtils.ParallelWeightedReservoirSample(host, numThreads, 1, cursorFactory, (in VBuffer<float> point, int pointIndex) => (float)1.0, (FeatureFloatVectorCursor cur) => -1, ref clusters, ref buffer); totalTrainingInstances = rowStats.TotalTrainingInstances; missingFeatureCount = rowStats.MissingFeatureCount; bool isParallel = numThreads > 1; long maxInstancesToAccelerate; long clusterBytes; ComputeAccelerationMemoryRequirement(accelMemBudgetMb, numSamplesPerRound, numRounds, isParallel, out maxInstancesToAccelerate, out clusterBytes); initializationState = new SharedState(cursorFactory, ch, maxInstancesToAccelerate, clusterBytes, isParallel, numRounds, numSamplesPerRound, totalTrainingInstances); VBufferUtils.Densify(ref clusters[clusterCount]); clustersL2s[clusterCount] = VectorUtils.NormSquared(clusters[clusterCount]); clusterPrevCount = clusterCount; ch.Assert(clusterCount - clusterPrevCount <= numSamplesPerRound); clusterCount++; logicalExternalRounds++; pCh.Checkpoint(logicalExternalRounds, numRounds + 2); // Next we iterate through the dataset 'rounds' times, each time we choose // instances probabilistically, weighting them with a likelihood proportional // to their distance from their best cluster. For each round, this gives us // a new set of 'numSamplesPerRound' instances which are very likely to be as // far from our current total running set of instances as possible. VBuffer<float>[] roundSamples = new VBuffer<float>[numSamplesPerRound]; KMeansUtils.WeightFunc weightFn = (in VBuffer<float> point, int pointRowIndex) => { float distanceSquared; int discardBestCluster; FindBestCluster(in point, pointRowIndex, initializationState, clusterCount, clusterPrevCount, clusters, clustersL2s, true, true, out distanceSquared, out discardBestCluster); return (distanceSquared >= 0.0f) ? distanceSquared : 0.0f; }; for (int r = 0; r < numRounds; r++) { // Iterate through the dataset, sampling 'numSamplesPerFound' data rows using // the weighted probability distribution. KMeansUtils.ParallelWeightedReservoirSample(host, numThreads, numSamplesPerRound, cursorFactory, weightFn, (FeatureFloatVectorCursor cur) => initializationState.RowIndexGetter(cur), ref roundSamples, ref buffer); clusterPrevCount = clusterCount; for (int i = 0; i < numSamplesPerRound; i++) { Utils.Swap(ref roundSamples[i], ref clusters[clusterCount]); VBufferUtils.Densify(ref clusters[clusterCount]); clustersL2s[clusterCount] = VectorUtils.NormSquared(clusters[clusterCount]); for (int j = 0; j < clusterPrevCount; j++) initializationState.SetClusterDistance(i, in clusters[clusterCount], clustersL2s[clusterCount], j, in clusters[j], clustersL2s[j]); clusterCount++; } ch.Assert(clusterCount - clusterPrevCount <= numSamplesPerRound); logicalExternalRounds++; pCh.Checkpoint(logicalExternalRounds, numRounds + 2); } ch.Assert(clusterCount == clusters.Length); } // Finally, we do one last pass through the dataset, finding for // each instance the closest chosen cluster instance and summing these into buckets to be used // to weight each one of our candidate chosen clusters. float[][] weightBuffer = null; float[] totalWeights = null; KMeansUtils.ParallelMapReduce<float[], float[]>( numThreads, host, cursorFactory, initializationState.RowIndexGetter, (ref float[] weights) => weights = new float[totalSamples], (ref VBuffer<float> point, int pointRowIndex, float[] weights, Random rand) => { int bestCluster; float discardBestWeight; FindBestCluster(in point, pointRowIndex, initializationState, clusterCount, clusterPrevCount, clusters, clustersL2s, false, false, out discardBestWeight, out bestCluster); #if DEBUG int debugBestCluster = KMeansUtils.FindBestCluster(in point, clusters, clustersL2s); ch.Assert(bestCluster == debugBestCluster); #endif weights[bestCluster]++; }, (float[][] workStateWeights, Random rand, ref float[] weights) => { weights = new float[totalSamples]; for (int i = 0; i < workStateWeights.Length; i++) CpuMathUtils.Add(workStateWeights[i], weights, totalSamples); }, ref weightBuffer, ref totalWeights); #if DEBUG // This is running the original code to make sure that the new code matches the semantic of the original code. float[] debugTotalWeights = null; float[][] debugWeightBuffer = null; KMeansUtils.ParallelMapReduce<float[], float[]>( numThreads, host, cursorFactory, (FeatureFloatVectorCursor cur) => -1, (ref float[] weights) => weights = new float[totalSamples], (ref VBuffer<float> point, int discard, float[] weights, Random rand) => weights[KMeansUtils.FindBestCluster(in point, clusters, clustersL2s)]++, (float[][] workStateWeights, Random rand, ref float[] weights) => { weights = new float[totalSamples]; for (int i = 0; i < workStateWeights.Length; i++) for (int j = 0; j < workStateWeights[i].Length; j++) weights[j] += workStateWeights[i][j]; }, ref debugWeightBuffer, ref debugTotalWeights); for (int i = 0; i < totalWeights.Length; i++) ch.Assert(totalWeights[i] == debugTotalWeights[i]); #endif ch.Assert(totalWeights.Length == clusters.Length); logicalExternalRounds++; // If we sampled exactly the right number of points then we can // copy them directly to the output centroids. if (clusters.Length == k) { for (int i = 0; i < k; i++) clusters[i].CopyTo(ref centroids[i]); } // Otherwise, using our much smaller set of possible cluster centroids, go ahead // and invoke the standard PlusPlus initialization routine to reduce this // set down into k clusters. else { ArrayDataViewBuilder arrDv = new ArrayDataViewBuilder(host); arrDv.AddColumn(DefaultColumnNames.Features, NumberDataViewType.Single, clusters); arrDv.AddColumn(DefaultColumnNames.Weight, NumberDataViewType.Single, totalWeights); var subDataViewCursorFactory = new FeatureFloatVectorCursor.Factory( new RoleMappedData(arrDv.GetDataView(), null, DefaultColumnNames.Features, weight: DefaultColumnNames.Weight), CursOpt.Weight | CursOpt.Features); long discard1; long discard2; KMeansPlusPlusInit.Initialize(host, numThreads, ch, subDataViewCursorFactory, k, dimensionality, centroids, out discard1, out discard2, false); } } } } internal static class KMeansRandomInit { /// <summary> /// Initialize starting centroids via reservoir sampling. /// </summary> public static void Initialize( IHost host, int numThreads, IChannel ch, FeatureFloatVectorCursor.Factory cursorFactory, int k, VBuffer<float>[] centroids, out long missingFeatureCount, out long totalTrainingInstances) { using (var pCh = host.StartProgressChannel("KMeansRandomInitialize")) { Heap<KMeansUtils.WeightedPoint>[] buffer = null; VBuffer<float>[] outCentroids = null; var rowStats = KMeansUtils.ParallelWeightedReservoirSample(host, numThreads, k, cursorFactory, (in VBuffer<float> point, int pointRowIndex) => 1f, (FeatureFloatVectorCursor cur) => -1, ref outCentroids, ref buffer); missingFeatureCount = rowStats.MissingFeatureCount; totalTrainingInstances = rowStats.TotalTrainingInstances; for (int i = 0; i < k; i++) Utils.Swap(ref centroids[i], ref outCentroids[i]); } } } internal static class KMeansLloydsYinYangTrain { private abstract class WorkChunkStateBase { protected readonly int K; protected readonly long MaxInstancesToAccelerate; // Standard KMeans per-cluster data. protected readonly VBuffer<float>[] Centroids; protected readonly long[] ClusterSizes; // YinYang per-cluster data. // cached sum of the first maxInstancesToAccelerate instances assigned to cluster i for 0 <= i < _k protected readonly VBuffer<float>[] CachedSum; #if DEBUG public VBuffer<float>[] CachedSumDebug { get { return CachedSum; } } #endif protected double PreviousAverageScore; protected double AverageScore; // Number of entries in AverageScore calculation. private long _n; // Debug/Progress stats. protected long GloballyFiltered; protected long NumChanged; protected long NumUnchangedMissed; public static void Initialize( long maxInstancesToAccelerate, int k, int dimensionality, int numThreads, out ReducedWorkChunkState reducedState, out WorkChunkState[] workChunkArr) { if (numThreads == 1) workChunkArr = new WorkChunkState[0]; else { workChunkArr = new WorkChunkState[numThreads]; for (int i = 0; i < numThreads; i++) workChunkArr[i] = new WorkChunkState(maxInstancesToAccelerate, k, dimensionality); } reducedState = new ReducedWorkChunkState(maxInstancesToAccelerate, k, dimensionality); } protected WorkChunkStateBase(long maxInstancesToAccelerate, int k, int dimensionality) { Centroids = new VBuffer<float>[k]; for (int j = 0; j < k; j++) Centroids[j] = VBufferUtils.CreateDense<float>(dimensionality); ClusterSizes = new long[k]; if (maxInstancesToAccelerate > 0) { CachedSum = new VBuffer<float>[k]; for (int j = 0; j < k; j++) CachedSum[j] = VBufferUtils.CreateDense<float>(dimensionality); } K = k; MaxInstancesToAccelerate = maxInstancesToAccelerate; } public void Clear(bool keepCachedSums = false) { for (int i = 0; i < K; i++) VBufferUtils.Clear(ref Centroids[i]); NumChanged = 0; NumUnchangedMissed = 0; GloballyFiltered = 0; _n = 0; PreviousAverageScore = AverageScore; AverageScore = 0; Array.Clear(ClusterSizes, 0, K); if (!keepCachedSums) { for (int i = 0; i < K; i++) VBufferUtils.Clear(ref CachedSum[i]); } } public void KeepYinYangAssignment(int bestCluster) { // this instance does not change clusters in this iteration // also, this instance does not account for average score calculation // REVIEW: This seems wrong. We're accumulating the globally-filtered rows into // the count that we use to find the average score for this iteration, yet we don't // accumulate their distance. Removing this will lead to the case where N will be // zero (all points filtered) and will cause a div-zero NaN score. It seems that we // should remove this line, and special case N = 0 when we average the distance score, // otherwise we'll continue to report a smaller epsilon and terminate earlier than we // otherwise would have. ClusterSizes[bestCluster]++; _n++; GloballyFiltered++; } public void UpdateClusterAssignment(bool firstIteration, in VBuffer<float> features, int cluster, int previousCluster, float distance) { if (firstIteration) { VectorUtils.Add(in features, ref CachedSum[cluster]); NumChanged++; } else if (previousCluster != cluster) { // update the cachedSum as the instance moves from (previous) bestCluster[n] to cluster VectorUtils.Add(in features, ref CachedSum[cluster]); // There doesnt seem to be a Subtract function that does a -= b, so doing a += (-1 * b) VectorUtils.AddMult(in features, -1, ref CachedSum[previousCluster]); NumChanged++; } else NumUnchangedMissed++; UpdateClusterAssignmentMetrics(cluster, distance); } public void UpdateClusterAssignment(in VBuffer<float> features, int cluster, float distance) { VectorUtils.Add(in features, ref Centroids[cluster]); UpdateClusterAssignmentMetrics(cluster, distance); } private void UpdateClusterAssignmentMetrics(int cluster, float distance) { _n++; ClusterSizes[cluster]++; AverageScore += distance; } /// <summary> /// Reduces the array of work chunks into this chunk, coalescing the /// results from multiple worker threads partitioned over a parallel cursor set and /// clearing their values to prepare them for the next iteration. /// </summary> public static void Reduce(WorkChunkState[] workChunkArr, ReducedWorkChunkState reducedState) { for (int i = 0; i < workChunkArr.Length; i++) { reducedState.AverageScore += workChunkArr[i].AverageScore; reducedState._n += workChunkArr[i]._n; reducedState.GloballyFiltered += workChunkArr[i].GloballyFiltered; reducedState.NumChanged += workChunkArr[i].NumChanged; reducedState.NumUnchangedMissed += workChunkArr[i].NumUnchangedMissed; for (int j = 0; j < reducedState.ClusterSizes.Length; j++) { reducedState.ClusterSizes[j] += workChunkArr[i].ClusterSizes[j]; VectorUtils.Add(in workChunkArr[i].CachedSum[j], ref reducedState.CachedSum[j]); VectorUtils.Add(in workChunkArr[i].Centroids[j], ref reducedState.Centroids[j]); } workChunkArr[i].Clear(keepCachedSums: false); } Contracts.Assert(FloatUtils.IsFinite(reducedState.AverageScore)); reducedState.AverageScore /= reducedState._n; } protected virtual int Foo { get; } } private sealed class WorkChunkState : WorkChunkStateBase { public WorkChunkState(long maxInstancesToAccelerate, int k, int dimensionality) : base(maxInstancesToAccelerate, k, dimensionality) { } } private sealed class ReducedWorkChunkState : WorkChunkStateBase { public double AverageScoreDelta => Math.Abs(PreviousAverageScore - AverageScore); public ReducedWorkChunkState(long maxInstancesToAccelerate, int k, int dimensionality) : base(maxInstancesToAccelerate, k, dimensionality) { AverageScore = double.PositiveInfinity; } /// <summary> /// Updates all the passed in variables with the results of the most recent iteration /// of cluster assignment. It is assumed that centroids will contain the previous results /// of this call. /// </summary> public void UpdateClusters(VBuffer<float>[] centroids, float[] centroidL2s, float[] deltas, ref float deltaMax) { bool isAccelerated = MaxInstancesToAccelerate > 0; deltaMax = 0; // calculate new centroids for (int i = 0; i < K; i++) { if (isAccelerated) VectorUtils.Add(in CachedSum[i], ref Centroids[i]); if (ClusterSizes[i] > 1) VectorUtils.ScaleBy(ref Centroids[i], (float)(1.0 / ClusterSizes[i])); if (isAccelerated) { float clusterDelta = MathUtils.Sqrt(VectorUtils.L2DistSquared(in Centroids[i], in centroids[i])); deltas[i] = clusterDelta; if (deltaMax < clusterDelta) deltaMax = clusterDelta; } centroidL2s[i] = VectorUtils.NormSquared(Centroids[i]); } for (int i = 0; i < K; i++) Utils.Swap(ref centroids[i], ref Centroids[i]); } public void ReportProgress(IProgressChannel pch, int iteration, int maxIterations) { pch.Checkpoint(AverageScore, NumChanged, NumUnchangedMissed + GloballyFiltered, GloballyFiltered, iteration, maxIterations); } } private sealed class SharedState { private readonly KMeansAcceleratedRowMap _acceleratedRowMap; public int MaxInstancesToAccelerate => _acceleratedRowMap.MaxInstancesToAccelerate; public bool IsAccelerated => _acceleratedRowMap.IsAccelerated; public KMeansUtils.RowIndexGetter RowIndexGetter => _acceleratedRowMap.RowIndexGetter; public int Iteration; // YinYang data. // the distance between the old and the new center for each cluster public readonly float[] Delta; // max value of delta[i] for 0 <= i < _k public float DeltaMax; // Per instance structures public int GetBestCluster(int idx) { return _bestCluster[idx]; } // closest cluster for an instance private readonly int[] _bestCluster; // upper bound on the distance of an instance to its bestCluster private readonly float[] _upperBound; // lower bound on the distance of an instance to every cluster other than its bestCluster private readonly float[] _lowerBound; public SharedState(FeatureFloatVectorCursor.Factory factory, IChannel ch, long baseMaxInstancesToAccelerate, int k, bool isParallel, long totalTrainingInstances) { Contracts.AssertValue(ch); ch.AssertValue(factory); ch.Assert(k > 0); ch.Assert(totalTrainingInstances > 0); _acceleratedRowMap = new KMeansAcceleratedRowMap(factory, ch, baseMaxInstancesToAccelerate, totalTrainingInstances, isParallel); ch.Assert(MaxInstancesToAccelerate >= 0, "MaxInstancesToAccelerate cannot be negative as KMeansAcceleratedRowMap sets it to 0 when baseMaxInstancesToAccelerate is negative"); if (MaxInstancesToAccelerate > 0) { // allocate data structures Delta = new float[k]; _bestCluster = new int[MaxInstancesToAccelerate]; _upperBound = new float[MaxInstancesToAccelerate]; _lowerBound = new float[MaxInstancesToAccelerate]; } } /// <summary> /// When assigning an accelerated row to a cluster, we store away the distance /// to its closer and second closed cluster, as well as the identity of the new /// closest cluster. This method returns the last known closest cluster. /// </summary> public int SetYinYangCluster(int n, in VBuffer<float> features, float minDistance, int minCluster, float secMinDistance) { if (n == -1) return -1; // update upper and lower bound // updates have to be true distances to use triangular inequality float instanceNormSquared = VectorUtils.NormSquared(in features); _upperBound[n] = MathUtils.Sqrt(instanceNormSquared + minDistance); _lowerBound[n] = MathUtils.Sqrt(instanceNormSquared + secMinDistance); int previousCluster = _bestCluster[n]; _bestCluster[n] = minCluster; return previousCluster; } /// <summary> /// Updates the known YinYang bounds for the given row using the centroid position /// deltas from the previous iteration. /// </summary> public void UpdateYinYangBounds(int n) { Contracts.Assert(n != -1); _upperBound[n] += Delta[_bestCluster[n]]; _lowerBound[n] -= DeltaMax; } /// <summary> /// Determines if the triangle distance inequality still applies to the given row, /// allowing us to avoid per-cluster distance computation. /// </summary> public bool IsYinYangGloballyBound(int n) { return _upperBound[n] < _lowerBound[n]; } #if DEBUG public void AssertValidYinYangBounds(int n, in VBuffer<float> features, VBuffer<float>[] centroids) { // Assert that the global filter is indeed doing the right thing float bestDistance = MathUtils.Sqrt(VectorUtils.L2DistSquared(in features, in centroids[_bestCluster[n]])); Contracts.Assert(KMeansLloydsYinYangTrain.AlmostLeq(bestDistance, _upperBound[n])); for (int j = 0; j < centroids.Length; j++) { if (j == _bestCluster[n]) continue; float distance = MathUtils.Sqrt(VectorUtils.L2DistSquared(in features, in centroids[j])); Contracts.Assert(AlmostLeq(_lowerBound[n], distance)); } } #endif } public static void Train(IHost host, int numThreads, IChannel ch, FeatureFloatVectorCursor.Factory cursorFactory, long totalTrainingInstances, int k, int dimensionality, int maxIterations, long accelMemBudgetInMb, float convergenceThreshold, VBuffer<float>[] centroids) { SharedState state; WorkChunkState[] workState; ReducedWorkChunkState reducedState; Initialize(ch, cursorFactory, totalTrainingInstances, numThreads, k, dimensionality, accelMemBudgetInMb, out state, out workState, out reducedState); float[] centroidL2s = new float[k]; for (int i = 0; i < k; i++) centroidL2s[i] = VectorUtils.NormSquared(in centroids[i]); using (var pch = host.StartProgressChannel("KMeansTrain")) { pch.SetHeader(new ProgressHeader( new[] { "Average Score", "# of Examples with Reassigned Cluster", "# of Examples with Same Cluster", "Globally Filtered" }, new[] { "iterations" }), (e) => e.SetProgress(0, state.Iteration, maxIterations)); bool isConverged = false; while (!isConverged && state.Iteration < maxIterations) { // assign instances to clusters and calculate total score reducedState.Clear(keepCachedSums: true); if (numThreads > 1) { // Build parallel cursor set and run.... var set = cursorFactory.CreateSet(numThreads); Action[] ops = new Action[set.Length]; for (int i = 0; i < ops.Length; i++) { int chunkId = i; ops[i] = new Action(() => { using (var cursor = set[chunkId]) ProcessChunk(cursor, state, workState[chunkId], k, centroids, centroidL2s); }); } Parallel.Invoke(new ParallelOptions() { MaxDegreeOfParallelism = numThreads }, ops); } else { using (var cursor = cursorFactory.Create()) ProcessChunk(cursor, state, reducedState, k, centroids, centroidL2s); } WorkChunkState.Reduce(workState, reducedState); reducedState.ReportProgress(pch, state.Iteration, maxIterations); #if DEBUG if (state.IsAccelerated) { // Assert that cachedSum[i] is equal to the sum of the first maxInstancesToAccelerate instances assigned to cluster i var cachedSumCopy = new VBuffer<float>[k]; for (int i = 0; i < k; i++) cachedSumCopy[i] = VBufferUtils.CreateDense<float>(dimensionality); using (var cursor = cursorFactory.Create()) { int numCounted = 0; while (cursor.MoveNext() && numCounted < state.MaxInstancesToAccelerate) { int id = state.RowIndexGetter(cursor); if (id != -1) { VectorUtils.Add(in cursor.Features, ref cachedSumCopy[state.GetBestCluster(id)]); numCounted++; } } } for (int i = 0; i < k; i++) { var reducedStateCacheValues = reducedState.CachedSumDebug[i].GetValues(); var cachedSumCopyValues = cachedSumCopy[i].GetValues(); for (int j = 0; j < dimensionality; j++) Contracts.Assert(AlmostEq(reducedStateCacheValues[j], cachedSumCopyValues[j])); } } #endif reducedState.UpdateClusters(centroids, centroidL2s, state.Delta, ref state.DeltaMax); isConverged = reducedState.AverageScoreDelta < convergenceThreshold; state.Iteration++; if (state.Iteration % 100 == 0) KMeansUtils.VerifyModelConsistency(centroids); } } } private static void Initialize( IChannel ch, FeatureFloatVectorCursor.Factory factory, long totalTrainingInstances, int numThreads, int k, int dimensionality, long accelMemBudgetMb, out SharedState state, out WorkChunkState[] perThreadWorkState, out ReducedWorkChunkState reducedWorkState) { // In the case of a single thread, we use a single WorkChunkState instance // and skip the reduce step, in the case of a parallel implementation we use // the last WorkChunkState to reduce the per-thread chunks into a single // result prior to the KMeans update step. int neededPerThreadWorkStates = numThreads == 1 ? 0 : numThreads; // Accelerating KMeans requires the following data structures. // The algorithm is based on the YinYang KMeans algorithm [ICML'15], https://research.microsoft.com/apps/pubs/default.aspx?id=252149 // These data structures are allocated only as allowed by the _accelMemBudgetMb parameter // if _accelMemBudgetMb is zero, then the algorithm below reduces to the original KMeans++ implementation int bytesPerCluster = sizeof(float) + // for delta sizeof(float) * dimensionality * (neededPerThreadWorkStates + 1); // for cachedSum int bytesPerInstance = sizeof(int) + // for bestCluster sizeof(float) + // for upperBound sizeof(float) + // for lowerBound (numThreads > 1 ? sizeof(int) + 16 : 0); // for parallel rowCursor index lookup HashArray storage (16 bytes for RowId, 4 bytes for internal 'next' index) long maxInstancesToAccelerate = Math.Max(0, (accelMemBudgetMb * 1024 * 1024 - bytesPerCluster * k) / bytesPerInstance); state = new SharedState(factory, ch, maxInstancesToAccelerate, k, numThreads > 1, totalTrainingInstances); WorkChunkState.Initialize(maxInstancesToAccelerate, k, dimensionality, numThreads, out reducedWorkState, out perThreadWorkState); } /// <summary> /// Performs the 'update' step of KMeans. This method is passed a WorkChunkState. In the parallel version /// this chunk will be one of _numThreads chunks and the RowCursor will be part of a RowCursorSet. In the /// unthreaded version, this chunk will be the final chunk and hold state for the entire data set. /// </summary> private static void ProcessChunk(FeatureFloatVectorCursor cursor, SharedState state, WorkChunkStateBase chunkState, int k, VBuffer<float>[] centroids, float[] centroidL2s) { while (cursor.MoveNext()) { int n = state.RowIndexGetter(cursor); bool firstIteration = state.Iteration == 0; // We cannot accelerate the first iteration. In other iterations, we can only accelerate the first maxInstancesToAccelerate if (!firstIteration && n != -1) { state.UpdateYinYangBounds(n); if (state.IsYinYangGloballyBound(n)) { chunkState.KeepYinYangAssignment(state.GetBestCluster(n)); #if DEBUG state.AssertValidYinYangBounds(n, in cursor.Features, centroids); #endif continue; } } float minDistance; float secMinDistance; int cluster; int secCluster; KMeansUtils.FindBestCluster(in cursor.Features, centroids, centroidL2s, k, false, out minDistance, out cluster, out secMinDistance, out secCluster); if (n == -1) chunkState.UpdateClusterAssignment(in cursor.Features, cluster, minDistance); else { int prevCluster = state.SetYinYangCluster(n, in cursor.Features, minDistance, cluster, secMinDistance); chunkState.UpdateClusterAssignment(firstIteration, in cursor.Features, cluster, prevCluster, minDistance); } } } #if DEBUG private const Double FloatingPointErrorThreshold = 0.1F; private static bool AlmostEq(float af, float bf) { Double a = (Double)af; Double b = (Double)bf; // First check if a and b are close together if (Math.Abs(a - b) < FloatingPointErrorThreshold) return true; // Else, it could simply mean that a and b are large, so check for relative error // Note: a and b being large means that we are not dividing by a small number below // Also, dividing by the larger number ensures that there is no division by zero problem Double relativeError; if (Math.Abs(a) > Math.Abs(b)) relativeError = Math.Abs((a - b) / a); else relativeError = Math.Abs((a - b) / b); if (relativeError < FloatingPointErrorThreshold) return true; return false; } private static bool AlmostLeq(float a, float b) { if (AlmostEq(a, b)) return true; return ((Double)a - (Double)b) < 0; } #endif } internal static class KMeansUtils { public struct WeightedPoint { public double Weight; public VBuffer<float> Point; } public struct RowStats { public long MissingFeatureCount; public long TotalTrainingInstances; } public delegate float WeightFunc(in VBuffer<float> point, int pointRowIndex); /// <summary> /// Performs a multithreaded version of weighted reservior sampling, returning /// an array of numSamples, where each sample has been selected from the /// data set with a probability of numSamples/N * weight/(sum(weight)). Buffer /// is sized to the number of threads plus one and stores the minheaps needed to /// perform the per-thread reservior samples. /// /// This method assumes that the numSamples is much smaller than the full dataset as /// it expects to be able to sample numSamples * numThreads. /// /// This is based on the 'A-Res' algorithm in 'Weighted Random Sampling', 2005; Efraimidis, Spirakis: /// https://utopia.duth.gr/~pefraimi/research/data/2007EncOfAlg.pdf /// </summary> public static RowStats ParallelWeightedReservoirSample( IHost host, int numThreads, int numSamples, FeatureFloatVectorCursor.Factory factory, WeightFunc weightFn, RowIndexGetter rowIndexGetter, ref VBuffer<float>[] dst, ref Heap<WeightedPoint>[] buffer) { host.AssertValue(host); host.AssertValue(factory); host.AssertValue(weightFn); host.Assert(numSamples > 0); host.Assert(numThreads > 0); Heap<WeightedPoint> outHeap = null; var rowStats = ParallelMapReduce<Heap<WeightedPoint>, Heap<WeightedPoint>>( numThreads, host, factory, rowIndexGetter, (ref Heap<WeightedPoint> heap) => { if (heap == null) heap = new Heap<WeightedPoint>((x, y) => x.Weight > y.Weight, numSamples); else heap.Clear(); }, (ref VBuffer<float> point, int pointRowIndex, Heap<WeightedPoint> heap, Random rand) => { // We use distance as a proxy for 'is the same point'. By excluding // all points that lie within a very small distance of our current set of // centroids we force the algorithm to explore more broadly and avoid creating a // set of centroids containing the same, or very close to the same, point // more than once. float sameClusterEpsilon = (float)1e-15; float weight = weightFn(in point, pointRowIndex); // If numeric instability has forced it to zero, then we bound it to epsilon to // keep the key valid and avoid NaN, (although the math does tend to work out regardless: // 1 / 0 => Inf, base ^ Inf => 0, when |base| < 1) if (weight == 0) weight = float.Epsilon; if (weight <= sameClusterEpsilon) return; double key = Math.Log(rand.NextDouble()) / weight; // If we are less than all of the samples in the heap and the heap // is full already, early return. if (heap.Count == numSamples && key <= heap.Top.Weight) return; WeightedPoint wRow; if (heap.Count == numSamples) wRow = heap.Pop(); else wRow = new WeightedPoint(); wRow.Weight = key; Utils.Swap(ref wRow.Point, ref point); heap.Add(wRow); }, (Heap<WeightedPoint>[] heaps, Random rand, ref Heap<WeightedPoint> finalHeap) => { host.Assert(finalHeap == null); finalHeap = new Heap<WeightedPoint>((x, y) => x.Weight > y.Weight, numSamples); for (int i = 0; i < heaps.Length; i++) { host.AssertValue(heaps[i]); host.Assert(heaps[i].Count <= numSamples, "heaps[i].Count must not be greater than numSamples"); while (heaps[i].Count > 0) { var row = heaps[i].Pop(); if (finalHeap.Count < numSamples) finalHeap.Add(row); else if (row.Weight > finalHeap.Top.Weight) { finalHeap.Pop(); finalHeap.Add(row); } } } }, ref buffer, ref outHeap); if (outHeap.Count != numSamples) throw host.Except("Failed to initialize clusters: too few examples"); // Keep in mind that the distribution of samples in dst will not be random. It will // have the residual minHeap ordering. Utils.EnsureSize(ref dst, numSamples); for (int i = 0; i < numSamples; i++) { var row = outHeap.Pop(); Utils.Swap(ref row.Point, ref dst[i]); } return rowStats; } public delegate void InitAction<TPartitionState>(ref TPartitionState val); public delegate int RowIndexGetter(FeatureFloatVectorCursor cur); public delegate void MapAction<TPartitionState>(ref VBuffer<float> point, int rowIndex, TPartitionState state, Random rand); public delegate void ReduceAction<TPartitionState, TGlobalState>(TPartitionState[] intermediates, Random rand, ref TGlobalState result); /// <summary> /// Takes a data cursor and perform an in-memory parallel aggregation operation on it. This /// helper wraps some of the behavior common to parallel operations over a IRowCursor set, /// including building the set, creating separate Random instances, and IRowCursor disposal. /// </summary> /// <typeparam name="TPartitionState">The type that each parallel cursor will be expected to aggregate to.</typeparam> /// <typeparam name="TGlobalState">The type of the final output from combining each per-thread instance of TInterAgg.</typeparam> /// <param name="numThreads"></param> /// <param name="baseHost"></param> /// <param name="factory"></param> /// <param name="rowIndexGetter"></param> /// <param name="initChunk">Initializes an instance of TInterAgg, or prepares/clears it if it is already allocated.</param> /// <param name="mapper">Invoked for every row, should update TInterAgg using row cursor data.</param> /// <param name="reducer">Invoked after all row cursors have completed, combines the entire array of TInterAgg instances into a final TAgg result.</param> /// <param name="buffer">A reusable buffer array of TInterAgg.</param> /// <param name="result">A reusable reference to the final result.</param> /// <returns></returns> public static RowStats ParallelMapReduce<TPartitionState, TGlobalState>( int numThreads, IHost baseHost, FeatureFloatVectorCursor.Factory factory, RowIndexGetter rowIndexGetter, InitAction<TPartitionState> initChunk, MapAction<TPartitionState> mapper, ReduceAction<TPartitionState, TGlobalState> reducer, ref TPartitionState[] buffer, ref TGlobalState result) { var set = factory.CreateSet(numThreads); int numCursors = set.Length; Action[] workArr = new Action[numCursors]; Utils.EnsureSize(ref buffer, numCursors, numCursors); for (int i = 0; i < numCursors; i++) { int ii = i; var cur = set[i]; initChunk(ref buffer[i]); var innerWorkState = buffer[i]; Random rand = RandomUtils.Create(baseHost.Rand); workArr[i] = () => { using (cur) { while (cur.MoveNext()) mapper(ref cur.Features, rowIndexGetter(cur), innerWorkState, rand); } }; } Parallel.Invoke(new ParallelOptions() { MaxDegreeOfParallelism = numThreads }, workArr); reducer(buffer, baseHost.Rand, ref result); return new RowStats() { MissingFeatureCount = set.Select(cur => cur.BadFeaturesRowCount).Sum(), TotalTrainingInstances = set.Select(cur => cur.KeptRowCount).Sum() }; } public static int FindBestCluster(in VBuffer<float> features, VBuffer<float>[] centroids, float[] centroidL2s) { float discard1; float discard2; int discard3; int cluster; FindBestCluster(in features, centroids, centroidL2s, centroids.Length, false, out discard1, out cluster, out discard2, out discard3); return cluster; } public static int FindBestCluster(in VBuffer<float> features, VBuffer<float>[] centroids, float[] centroidL2s, int centroidCount, bool realWeight, out float minDistance) { float discard1; int discard2; int cluster; FindBestCluster(in features, centroids, centroidL2s, centroidCount, realWeight, out minDistance, out cluster, out discard1, out discard2); return cluster; } /// <summary> /// Given a point and a set of centroids this method will determine the closest centroid /// using L2 distance. It will return a value equivalent to that distance, the index of the /// closest cluster, and a value equivalent to the distance to the second-nearest cluster. /// </summary> /// <param name="features"></param> /// <param name="centroids"></param> /// <param name="centroidL2s">The L2 norms of the centroids. Used for efficiency and expected to be computed up front.</param> /// <param name="centroidCount">The number of centroids. Must be less than or equal to the length of the centroid array.</param> /// <param name="needRealDistance">Whether to return a real L2 distance, or a value missing the L2 norm of <paramref name="features"/>.</param> /// <param name="minDistance">The distance between <paramref name="features"/> and the nearest centroid in <paramref name="centroids" />.</param> /// <param name="cluster">The index of the nearest centroid.</param> /// <param name="secMinDistance">The second nearest distance, or PosInf if <paramref name="centroids" /> only contains a single point.</param> /// <param name="secCluster">The index of the second nearest centroid, or -1 if <paramref name="centroids" /> only contains a single point.</param> public static void FindBestCluster( in VBuffer<float> features, VBuffer<float>[] centroids, float[] centroidL2s, int centroidCount, bool needRealDistance, out float minDistance, out int cluster, out float secMinDistance, out int secCluster) { Contracts.Assert(centroids.Length >= centroidCount && centroidL2s.Length >= centroidCount && centroidCount > 0); Contracts.Assert(features.Length == centroids[0].Length); minDistance = float.PositiveInfinity; secMinDistance = float.PositiveInfinity; cluster = 0; // currently assigned cluster to the instance secCluster = -1; for (int j = 0; j < centroidCount; j++) { // this is not a real distance, since we don't add L2 norm of the instance // This won't affect minimum calculations, and total score will just be lowered by sum(L2 norms) float distance = -2 * VectorUtils.DotProduct(in features, in centroids[j]) + centroidL2s[j]; if (distance <= minDistance) { // Note the equal to in the branch above. This is important when secMinDistance == minDistance secMinDistance = minDistance; secCluster = cluster; minDistance = distance; cluster = j; } else if (distance < secMinDistance) { secMinDistance = distance; secCluster = j; } } Contracts.Assert(FloatUtils.IsFinite(minDistance)); Contracts.Assert(centroidCount == 1 || (FloatUtils.IsFinite(secMinDistance) && secCluster >= 0)); Contracts.Assert(minDistance <= secMinDistance); if (needRealDistance) { float l2 = VectorUtils.NormSquared(in features); minDistance += l2; if (secCluster != -1) secMinDistance += l2; } } /// <summary> /// Checks that all coordinates of all centroids are finite, and throws otherwise /// </summary> public static void VerifyModelConsistency(VBuffer<float>[] centroids) { foreach (var centroid in centroids) Contracts.Check(centroid.Items().Select(x => x.Value).All(FloatUtils.IsFinite), "Model training failed: non-finite coordinates are generated"); } } }
50.552705
219
0.574872
[ "MIT" ]
calcbench/machinelearning
src/Microsoft.ML.KMeansClustering/KMeansPlusPlusTrainer.cs
90,641
C#
using System; using System.Collections.Generic; using FluentAssertions; using Moq; using NNX.Core.Tests.TestObjects; using NNX.Core.Training; using NNX.Core.Utils; using Xunit; namespace NNX.Core.Tests.Training.BaseTrainerTests { public class TrainTests : IDisposable { private readonly Mock<BaseTrainer> _mockTrainer; private readonly IList<InputOutput> _trainingSet; private readonly INeuralNetwork _nn; private IList<InputOutput> _trainingSubSet; private IList<InputOutput> _validationSubSet; private INeuralNetwork _trainedNeuralNet; public TrainTests() { _mockTrainer = GetMockTrainer(); _trainingSet = GetTrainingSet(); _nn = GetNeuralNetwork(); MockRandom.SetUp(); } public void Dispose() { MockRandom.Dispose(); } [Fact] public void ShouldValidate() { _mockTrainer.Object.Train(_trainingSet, _nn); _mockTrainer.Verify(t => t.Validate(), Times.Once); } [Fact] public void IfNotValid_Throw() { _mockTrainer.Setup(t => t.Validate()).Throws(new NeuralNetworkException("x")); Action action = () =>_mockTrainer.Object.Train(_trainingSet, _nn); action.ShouldThrow<NeuralNetworkException>() .WithMessage("x"); } [Fact] public void IfValidationSetFractionIsZero_ShouldPassFullTrainingSet() { _mockTrainer.Object.Train(_trainingSet, _nn); _trainingSubSet.Should().Equal(_trainingSet); } [Fact] public void IfValidationSetFractionNotZero_ShouldMakeValidationSet() { _mockTrainer.Setup(t => t.GetValidationSetFraction()).Returns(0.25); _mockTrainer.Object.Train(_trainingSet, _nn); _trainingSubSet.Should().HaveCount(3); _validationSubSet.Should().HaveCount(1); } [Fact] public void ShuoldTrainPassedNeuralNet() { _mockTrainer.Object.Train(_trainingSet, _nn); Assert.Same(_nn, _trainedNeuralNet); } [Fact] public void IfInitializeWeights_ShouldInitializeWeights() { var trainer = _mockTrainer.Object; trainer.ShouldInitializeWeights = false; _mockTrainer.Object.Train(_trainingSet, _nn); var expected = GetWeights(); _nn.Weights[0].Should().Equal(expected[0]); _nn.Weights[1].Should().Equal(expected[1]); } [Fact] public void IfNotInitializeWeights_ShouldNotInitializeWeights() { var trainer = _mockTrainer.Object; trainer.ShouldInitializeWeights = true; _mockTrainer.Object.Train(_trainingSet, _nn); var expected = MockRandom.DoubleValue - 0.5; _nn.Weights[0].Should().Equal(expected, expected, expected); _nn.Weights[1].Should().Equal(expected); } //================= Private Helpers ======================= private Mock<BaseTrainer> GetMockTrainer() { var mock = new Mock<BaseTrainer>(); mock.Setup(t => t.Train(It.IsAny<IList<InputOutput>>(), It.IsAny<IList<InputOutput>>(), It.IsAny<IRandomGenerator>(), It.IsAny<INeuralNetwork>())) .Callback((IList<InputOutput> trainingSubSet, IList<InputOutput> validationSubSet, IRandomGenerator rand, INeuralNetwork nn) => { _trainingSubSet = trainingSubSet; _validationSubSet = validationSubSet; _trainedNeuralNet = nn; }); mock.Setup(t => t.Validate()); mock.Setup(t => t.GetValidationSetFraction()).Returns(0); return mock; } private IList<InputOutput> GetTrainingSet() => new[] { new InputOutput {Input = new[] {0.1, 0.2}, Output = new[] {0.0, 1.0}}, new InputOutput {Input = new[] {0.2, 0.3}, Output = new[] {0.0, 1.0}}, new InputOutput {Input = new[] {0.4, 0.5}, Output = new[] {1.0, 0.0}}, new InputOutput {Input = new[] {0.6, 0.7}, Output = new[] {1.0, 0.0}}, }; private INeuralNetwork GetNeuralNetwork() { var mock = new Mock<INeuralNetwork>(); var weights = GetWeights(); mock.SetupGet(n => n.Weights).Returns(weights); return mock.Object; } private double[][] GetWeights() => new[] { new[] { 0.1, 0.1, 0.1 }, new[] { 0.2 } }; } }
34.422535
92
0.549304
[ "Apache-2.0" ]
ikhramts/NNX
NNX.Core.Tests/Training/BaseTrainerTests/TrainTests.cs
4,890
C#
using System; using System.IO; namespace RustTest.Net { public class ULinkStream : Stream { #region Fields private BinaryReader reader = null; private BinaryWriter writer = null; private Stream baseStream = null; #endregion #region Properties /// <summary> /// When overridden in a derived class, gets a value indicating whether the current stream supports reading. /// </summary> public override bool CanRead { get { return this.baseStream.CanRead; } } /// <summary> /// When overridden in a derived class, gets a value indicating whether the current stream supports seeking. /// </summary> public override bool CanSeek { get { return this.baseStream.CanSeek; } } /// <summary> /// When overridden in a derived class, gets a value indicating whether the current stream supports writing. /// </summary> public override bool CanWrite { get { return this.baseStream.CanWrite; } } /// <summary> /// When overridden in a derived class, gets the length in bytes of the stream. /// </summary> public override long Length { get { return this.baseStream.Length; } } /// <summary> /// When overridden in a derived class, gets or sets the position within the current stream. /// </summary> public override long Position { get { return this.baseStream.Position; } set { this.baseStream.Position = value; } } #endregion #region Methods /// <summary> /// Reads the string. /// </summary> /// <returns></returns> public string ReadString() { return reader.ReadString(); } /// <summary> /// Reads the unsigned byte. /// </summary> /// <returns></returns> public byte ReadUByte() { return reader.ReadByte(); } /// <summary> /// Reads the signed byte. /// </summary> /// <returns></returns> public sbyte ReadSByte() { return reader.ReadSByte(); } /// <summary> /// Reads the unsigned short. /// </summary> /// <returns></returns> public ushort ReadUShort() { return reader.ReadUInt16(); } /// <summary> /// Reads the signed short. /// </summary> /// <returns></returns> public short ReadShort() { return reader.ReadInt16(); } /// <summary> /// Reads the unsigned integer. /// </summary> /// <returns></returns> public uint ReadUInt() { return reader.ReadUInt32(); } /// <summary> /// Reads the integer. /// </summary> /// <returns></returns> public int ReadInt() { return reader.ReadInt32(); } /// <summary> /// Reads the encoded int. /// </summary> /// <returns></returns> public int ReadEncodedInt() { int returnValue = 0; int bitIndex = 0; while (bitIndex != 35) { byte currentByte = ReadUByte(); returnValue |= ((int)currentByte & (int)sbyte.MaxValue) << bitIndex; bitIndex += 7; if (((int)currentByte & 128) == 0) return returnValue; } throw new FormatException("Invalid 7-bit encoded integer"); } /// <summary> /// Reads the bytes. /// </summary> /// <param name="count">The count.</param> /// <returns>Data.</returns> public byte[] ReadBytes(int count) { byte[] buffer = new byte[count]; // read Read(buffer, 0, count); return buffer; } /// <summary> /// Reads the float. /// </summary> /// <returns></returns> public float ReadFloat() { return reader.ReadSingle(); } /// <summary> /// Writes the string. /// </summary> /// <param name="str">The string.</param> public void WriteString(string str) { writer.Write(str); } /// <summary> /// Writes the unsigned byte. /// </summary> /// <param name="b">The byte.</param> public void WriteUByte(byte b) { writer.Write(b); } /// <summary> /// Writes the signed byte. /// </summary> /// <param name="b">The byte.</param> public void WriteSByte(sbyte b) { writer.Write(b); } /// <summary> /// Writes the unsigned short. /// </summary> /// <param name="s">The short.</param> public void WriteUShort(ushort s) { writer.Write(s); } /// <summary> /// Writes the signed short. /// </summary> /// <param name="s">The signed.</param> public void WriteShort(short s) { writer.Write(s); } /// <summary> /// Writes the encoded int. /// </summary> /// <param name="value">The value.</param> public void WriteEncodedInt(int value) { uint num = (uint)value; while (num >= 128U) { WriteUByte((byte)(num | 128U)); num >>= 7; } WriteUByte((byte)num); } /// <summary> /// Writes the bytes. /// </summary> /// <param name="data">The data.</param> public void WriteBytes(byte[] data) { Write(data, 0, data.Length); } /// <summary> /// When overridden in a derived class, reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read. /// </summary> /// <param name="buffer">An array of bytes. When this method returns, the buffer contains the specified byte array with the values between <paramref name="offset" /> and (<paramref name="offset" /> + <paramref name="count" /> - 1) replaced by the bytes read from the current source.</param> /// <param name="offset">The zero-based byte offset in <paramref name="buffer" /> at which to begin storing the data read from the current stream.</param> /// <param name="count">The maximum number of bytes to be read from the current stream.</param> /// <returns> /// The total number of bytes read into the buffer. This can be less than the number of bytes requested if that many bytes are not currently available, or zero (0) if the end of the stream has been reached. /// </returns> public override int Read(byte[] buffer, int offset, int count) { return this.baseStream.Read(buffer, offset, count); } /// <summary> /// When overridden in a derived class, sets the position within the current stream. /// </summary> /// <param name="offset">A byte offset relative to the <paramref name="origin" /> parameter.</param> /// <param name="origin">A value of type <see cref="T:System.IO.SeekOrigin" /> indicating the reference point used to obtain the new position.</param> /// <returns> /// The new position within the current stream. /// </returns> public override long Seek(long offset, SeekOrigin origin) { return this.baseStream.Seek(offset, origin); } /// <summary> /// When overridden in a derived class, sets the length of the current stream. /// </summary> /// <param name="value">The desired length of the current stream in bytes.</param> public override void SetLength(long value) { this.baseStream.SetLength(value); } /// <summary> /// When overridden in a derived class, writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written. /// </summary> /// <param name="buffer">An array of bytes. This method copies <paramref name="count" /> bytes from <paramref name="buffer" /> to the current stream.</param> /// <param name="offset">The zero-based byte offset in <paramref name="buffer" /> at which to begin copying bytes to the current stream.</param> /// <param name="count">The number of bytes to be written to the current stream.</param> public override void Write(byte[] buffer, int offset, int count) { this.baseStream.Write(buffer, offset, count); } /// <summary> /// When overridden in a derived class, clears all buffers for this stream and causes any buffered data to be written to the underlying device. /// </summary> public override void Flush() { this.baseStream.Flush(); } /// <summary> /// To the array. /// </summary> /// <returns></returns> public byte[] ToArray() { // cast MemoryStream ms = (MemoryStream)baseStream; return ms.ToArray(); } #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="ULinkStream"/> class. /// </summary> /// <param name="buffer">The array of unsigned bytes from which to create the current stream.</param> public ULinkStream(byte[] buffer) : base() { this.baseStream = new MemoryStream(buffer); this.reader = new BinaryReader(this.baseStream); this.writer = new BinaryWriter(this.baseStream); } /// <summary> /// Initializes a new instance of the <see cref="ULinkStream"/> class. /// </summary> /// <param name="stream">The stream.</param> public ULinkStream(Stream stream) : base() { this.baseStream = stream; this.reader = new BinaryReader(this.baseStream); this.writer = new BinaryWriter(this.baseStream); } /// <summary> /// Initializes a new instance of the <see cref="ULinkStream"/> class. /// </summary> public ULinkStream() : base() { this.baseStream = new MemoryStream(); this.reader = new BinaryReader(this.baseStream); this.writer = new BinaryWriter(this.baseStream); } #endregion } }
33.696594
298
0.532157
[ "MIT" ]
alandoherty/rustpal
RustTest/Net/ULinkStream.cs
10,886
C#
// Copyright (c) Charlie Poole, Rob Prouse and Contributors. MIT License - see LICENSE.txt namespace NUnit.Engine.Communication.Transports { /// <summary> /// The ITransport interface is implemented by a class /// providing a communication interface for another class. /// </summary> public interface ITransport { bool Start(); void Stop(); } }
26
90
0.661538
[ "MIT" ]
G-Research/nunit-console
src/NUnitEngine/nunit.engine.core/Communication/Transports/ITransport.cs
390
C#
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using Aliyun.Acs.Core.Transform; using Aliyun.Acs.Vpc.Model.V20160428; using System; using System.Collections.Generic; namespace Aliyun.Acs.Vpc.Transform.V20160428 { public class RemoveIPv6TranslatorAclListEntryResponseUnmarshaller { public static RemoveIPv6TranslatorAclListEntryResponse Unmarshall(UnmarshallerContext context) { RemoveIPv6TranslatorAclListEntryResponse removeIPv6TranslatorAclListEntryResponse = new RemoveIPv6TranslatorAclListEntryResponse(); removeIPv6TranslatorAclListEntryResponse.HttpResponse = context.HttpResponse; removeIPv6TranslatorAclListEntryResponse.RequestId = context.StringValue("RemoveIPv6TranslatorAclListEntry.RequestId"); return removeIPv6TranslatorAclListEntryResponse; } } }
41.789474
135
0.782746
[ "Apache-2.0" ]
fossabot/aliyun-openapi-net-sdk
aliyun-net-sdk-vpc/Vpc/Transform/V20160428/RemoveIPv6TranslatorAclListEntryResponseUnmarshaller.cs
1,588
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the iot-2015-05-28.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Xml.Serialization; using Amazon.IoT.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.IoT.Model.Internal.MarshallTransformations { /// <summary> /// CreateTopicRuleDestination Request Marshaller /// </summary> public class CreateTopicRuleDestinationRequestMarshaller : IMarshaller<IRequest, CreateTopicRuleDestinationRequest> , IMarshaller<IRequest,AmazonWebServiceRequest> { /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="input"></param> /// <returns></returns> public IRequest Marshall(AmazonWebServiceRequest input) { return this.Marshall((CreateTopicRuleDestinationRequest)input); } /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(CreateTopicRuleDestinationRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.IoT"); request.Headers["Content-Type"] = "application/json"; request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2015-05-28"; request.HttpMethod = "POST"; request.ResourcePath = "/destinations"; using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture)) { JsonWriter writer = new JsonWriter(stringWriter); writer.WriteObjectStart(); var context = new JsonMarshallerContext(request, writer); if(publicRequest.IsSetDestinationConfiguration()) { context.Writer.WritePropertyName("destinationConfiguration"); context.Writer.WriteObjectStart(); var marshaller = TopicRuleDestinationConfigurationMarshaller.Instance; marshaller.Marshall(publicRequest.DestinationConfiguration, context); context.Writer.WriteObjectEnd(); } writer.WriteObjectEnd(); string snippet = stringWriter.ToString(); request.Content = System.Text.Encoding.UTF8.GetBytes(snippet); } return request; } private static CreateTopicRuleDestinationRequestMarshaller _instance = new CreateTopicRuleDestinationRequestMarshaller(); internal static CreateTopicRuleDestinationRequestMarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static CreateTopicRuleDestinationRequestMarshaller Instance { get { return _instance; } } } }
36.179245
167
0.645632
[ "Apache-2.0" ]
Hazy87/aws-sdk-net
sdk/src/Services/IoT/Generated/Model/Internal/MarshallTransformations/CreateTopicRuleDestinationRequestMarshaller.cs
3,835
C#
using System; using Godot; using StormTime.Common; using StormTime.Player.Data; using StormTime.Player.Controllers; using StormTime.Player.Shooting; using StormTime.UI; using StormTime.Utils; namespace StormTime.Scene.MainScene { public class GameManager : Node { private const string BossScenePath = "res://Scenes/Boss.tscn"; // Player Data Controls [Export] public NodePath playerControllerNodePath; [Export] public NodePath playerShooterNodePath; [Export] public NodePath playerHealthSetterNodePath; // Pause and Resume [Export] public NodePath pauseResumeControllerNodePath; private PlayerController _playerController; private PlayerShooting _playerShooting; private HealthSetter _playerHealthSetter; private PauseAndResume _pauseResumeController; private bool _playerInteractingWithShop; private bool _pauseMenuOpen; public override void _Ready() { GD.Randomize(); if (instance == null) { instance = this; } _playerController = GetNode<PlayerController>(playerControllerNodePath); _playerShooting = GetNode<PlayerShooting>(playerShooterNodePath); _playerHealthSetter = GetNode<HealthSetter>(playerHealthSetterNodePath); _pauseResumeController = GetNode<PauseAndResume>(pauseResumeControllerNodePath); Fader.FaderReady faderActivate = null; faderActivate = () => { Fader.instance.StartFading(false, new Color(1, 1, 1)); Fader.faderReady -= faderActivate; }; Fader.faderReady += faderActivate; } public override void _Process(float delta) { if (!Input.IsActionJustPressed(SceneControls.Cancel) || _playerInteractingWithShop) { return; } if (_pauseMenuOpen) { _pauseResumeController.HidePauseMenu(); } else { _pauseResumeController.ShowPauseMenu(); } } #region External Functions public void PauseMenuOpened() => _pauseMenuOpen = true; public void PauseMenuClosed() => _pauseMenuOpen = false; public void PlayerEnemyShopInteractionStarted() => _playerInteractingWithShop = true; public void PlayerEnemyShopInteractionEnded() => _playerInteractingWithShop = false; public void SwitchToBossScene() { float movementSpeed = _playerController.GetPlayerMovementSpeed(); float currentMaxHealth = _playerHealthSetter.GetMaxHealth(); float currentDamageDiff = _playerShooting.GetShootingDamageDiff(); PlayerVariables.PlayerCurrentMovementSpeed = movementSpeed; PlayerVariables.PlayerCurrentMaxHealth = currentMaxHealth; PlayerVariables.PlayerCurrentShootingDamageDiff = currentDamageDiff; GetTree().ChangeScene(BossScenePath); } #endregion #region Singleton public static GameManager instance; #endregion } }
30.443396
95
0.642082
[ "MIT" ]
Rud156/StormTime
Scripts/Scene/MainScene/GameManager.cs
3,227
C#
//----------------------------------------------------------------------------- // // <copyright file="Package.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. // </copyright> // // Description: // This is a base abstract class for Package. This is a part of the // Packaging Layer. // // History: // 01/03/2004: SarjanaS: Initial creation. [Stubs only] // 03/01/2004: SarjanaS: Implemented the functionality for all the members. // 03/17/2004: BruceMac: Initial implementation or PackageRelationship methods // //----------------------------------------------------------------------------- using System; using System.IO; using System.Collections; using System.Collections.Generic; // For SortedList<> using System.Windows; // For Exception strings - SRID using System.Diagnostics; // For Debug.Assert using MS.Internal.IO.Packaging; using MS.Internal.WindowsBase; // for [FriendAccessAllowed] using MS.Internal; // For Invariant.Assert using MS.Utility; namespace System.IO.Packaging { /// <summary> /// Abstract Base class for the Package. /// This is a part of the Packaging Layer APIs /// </summary> public abstract class Package : IDisposable { //------------------------------------------------------ // // Public Constructors // //------------------------------------------------------ #region Protected Constructor /// <summary> /// Protected constructor for the abstract Base class. /// This is the current contract between the subclass and the base class /// If we decide some registration mechanism then this might change /// </summary> /// <param name="openFileAccess"></param> /// <exception cref="ArgumentOutOfRangeException">If FileAccess enumeration does not have one of the valid values</exception> protected Package(FileAccess openFileAccess) : this(openFileAccess, false /* not streaming by default */) { } /// <summary> /// Protected constructor for the abstract Base class. /// This is the current contract between the subclass and the base class /// If we decide some registration mechanism then this might change /// </summary> /// <param name="openFileAccess"></param> /// <param name="streaming">Whether the package is being opened for streaming.</param> /// <exception cref="ArgumentOutOfRangeException">If FileAccess enumeration does not have one of the valid values</exception> protected Package(FileAccess openFileAccess, bool streaming) { ThrowIfFileAccessInvalid(openFileAccess); _openFileAccess = openFileAccess; //PackUriHelper.ValidatedPartUri implements the IComparable interface. _partList = new SortedList<PackUriHelper.ValidatedPartUri, PackagePart>(); // initial default is zero _partCollection = null; _disposed = false; _inStreamingCreation = (openFileAccess == FileAccess.Write && streaming); } #endregion Protected Constructor //------------------------------------------------------ // // Public Properties // //------------------------------------------------------ #region Public Properties /// <summary> /// Gets the FileAccess with which the package was opened. This is a read only property. /// This property gets set when the package is opened. /// </summary> /// <value>FileAccess</value> /// <exception cref="ObjectDisposedException">If this Package object has been disposed</exception> public FileAccess FileOpenAccess { get { ThrowIfObjectDisposed(); return _openFileAccess; } } /// <summary> /// The package properties are a subset of the standard OLE property sets /// SummaryInformation and DocumentSummaryInformation, and include such properties /// as Title and Subject. /// </summary> /// <exception cref="ObjectDisposedException">If this Package object has been disposed</exception> public PackageProperties PackageProperties { get { ThrowIfObjectDisposed(); if (_packageProperties == null) _packageProperties = new PartBasedPackageProperties(this); return _packageProperties; } } #endregion Public Properties //------------------------------------------------------ // // Public Methods // //------------------------------------------------------ #region Public Methods #region OpenOnFileMethods /// <summary> /// Opens a package at the specified Path. This method calls the overload which accepts all the parameters /// with the following defaults - /// FileMode - FileMode.OpenOrCreate, /// FileAccess - FileAccess.ReadWrite /// FileShare - FileShare.None /// </summary> /// <param name="path">Path to the package</param> /// <returns>Package</returns> /// <exception cref="ArgumentNullException">If path parameter is null</exception> public static Package Open(string path) { return Open(path, _defaultFileMode, _defaultFileAccess, _defaultFileShare); } /// <summary> /// Opens a package at the specified Path in the given mode. This method calls the overload which /// accepts all the parameters with the following defaults - /// FileAccess - FileAccess.ReadWrite /// FileShare - FileShare.None /// </summary> /// <param name="path">Path to the package</param> /// <param name="packageMode">FileMode in which the package should be opened</param> /// <returns>Package</returns> /// <exception cref="ArgumentNullException">If path parameter is null</exception> /// <exception cref="ArgumentOutOfRangeException">If FileMode enumeration [packageMode] does not have one of the valid values</exception> public static Package Open(string path, FileMode packageMode) { return Open(path, packageMode, _defaultFileAccess, _defaultFileShare); } /// <summary> /// Opens a package at the specified Path in the given mode with the specified access. This method calls /// the overload which accepts all the parameters with the following defaults - /// FileShare - FileShare.None /// </summary> /// <param name="path">Path to the package</param> /// <param name="packageMode">FileMode in which the package should be opened</param> /// <param name="packageAccess">FileAccess with which the package should be opened</param> /// <returns>Package</returns> /// <exception cref="ArgumentNullException">If path parameter is null</exception> /// <exception cref="ArgumentOutOfRangeException">If FileMode enumeration [packageMode] does not have one of the valid values</exception> /// <exception cref="ArgumentOutOfRangeException">If FileAccess enumeration [packageAccess] does not have one of the valid values</exception> public static Package Open(string path, FileMode packageMode, FileAccess packageAccess) { return Open(path, packageMode, packageAccess, _defaultFileShare); } /// <summary> /// Opens the package with the specified parameters. /// /// Note:- /// Since currently there is no plan to implement a generic registration mechanism, this method /// has some hard coded knowledge about the sub classes. This might change later if we come up /// with a registration mechanism. /// There is no caching mechanism in case the FileShare is specified to ReadWrite/Write. /// We do not have any refresh mechanism, to make sure that the cached parts reflect the actual parts, /// in the case where there might be more than one processes writing to the same underlying package. /// </summary> /// <param name="path">Path to the package</param> /// <param name="packageMode">FileMode in which the package should be opened</param> /// <param name="packageAccess">FileAccess with which the package should be opened</param> /// <param name="packageShare">FileShare with which the package is opened.</param> /// <returns>Package</returns> /// <exception>InvalidArgumentException - If the combination of the FileMode, /// FileAccess and FileShare parameters is not meaningful.</exception> /// <exception cref="ArgumentNullException">If path parameter is null</exception> /// <exception cref="ArgumentOutOfRangeException">If FileMode enumeration [packageMode] does not have one of the valid values</exception> /// <exception cref="ArgumentOutOfRangeException">If FileAccess enumeration [packageAccess] does not have one of the valid values</exception> public static Package Open(string path, FileMode packageMode, FileAccess packageAccess, FileShare packageShare) { return Open(path, packageMode, packageAccess, packageShare, false /* not in streaming mode */); } #endregion OpenOnFileMethods #region OpenOnStreamMethods /// <summary> /// Open a package on this stream. This method calls the overload which accepts all the parameters /// with the following defaults - /// FileMode - FileMode.Open /// FileAccess - FileAccess.Read /// </summary> /// <param name="stream">Stream on which the package is to be opened</param> /// <returns>Package</returns> /// <exception cref="ArgumentNullException">If stream parameter is null</exception> /// <exception cref="IOException">If package to be created should have readwrite/read access and underlying stream is write only</exception> /// <exception cref="IOException">If package to be created should have readwrite/write access and underlying stream is read only</exception> public static Package Open(Stream stream) { return Open(stream, _defaultStreamMode, _defaultStreamAccess); } /// <summary> /// Open a package on this stream. This method calls the overload which accepts all the parameters /// with the following defaults - /// FileAccess - FileAccess.ReadWrite /// </summary> /// <param name="stream">Stream on which the package is to be opened</param> /// <param name="packageMode">FileMode in which the package should be opened.</param> /// <returns>Package</returns> /// <exception cref="ArgumentNullException">If stream parameter is null</exception> /// <exception cref="ArgumentOutOfRangeException">If FileMode enumeration [packageMode] does not have one of the valid values</exception> /// <exception cref="IOException">If package to be created should have readwrite/read access and underlying stream is write only</exception> /// <exception cref="IOException">If package to be created should have readwrite/write access and underlying stream is read only</exception> public static Package Open(Stream stream, FileMode packageMode) { //If the user is providing a FileMode, in all the modes, except FileMode.Open, //its most likely that the user intends to write to the stream. return Open(stream, packageMode, _defaultFileAccess); } /// <summary> /// Opens a package on this stream. The package is opened in the specified mode and with the access /// specified. /// </summary> /// <param name="stream">Stream on which the package is created</param> /// <param name="packageMode">FileMode in which the package is to be opened</param> /// <param name="packageAccess">FileAccess on the package that is opened</param> /// <returns>Package</returns> /// <exception cref="ArgumentNullException">If stream parameter is null</exception> /// <exception cref="ArgumentOutOfRangeException">If FileMode enumeration [packageMode] does not have one of the valid values</exception> /// <exception cref="ArgumentOutOfRangeException">If FileAccess enumeration [packageAccess] does not have one of the valid values</exception> /// <exception cref="IOException">If package to be created should have readwrite/read access and underlying stream is write only</exception> /// <exception cref="IOException">If package to be created should have readwrite/write access and underlying stream is read only</exception> public static Package Open(Stream stream, FileMode packageMode, FileAccess packageAccess) { return Open(stream, packageMode, packageAccess, false /* not in streaming mode */); } #endregion OpenOnStreamMethods #region PackagePart Methods /// <summary> /// Creates a new part in the package. An empty stream corresponding to this part will be created in the /// package. If a part with the specified uri already exists then we throw an exception. /// This methods will call the CreatePartCore method which will create the actual PackagePart in the package. /// </summary> /// <param name="partUri">Uri of the PackagePart that is to be added</param> /// <param name="contentType">ContentType of the stream to be added</param> /// <returns></returns> /// <exception cref="ObjectDisposedException">If this Package object has been disposed</exception> /// <exception cref="IOException">If the package is readonly, it cannot be modified</exception> /// <exception cref="ArgumentNullException">If partUri parameter is null</exception> /// <exception cref="ArgumentNullException">If contentType parameter is null</exception> /// <exception cref="ArgumentException">If partUri parameter does not conform to the valid partUri syntax</exception> /// <exception cref="InvalidOperationException">If a PackagePart with the given partUri already exists in the Package</exception> public PackagePart CreatePart(Uri partUri, string contentType) { return CreatePart(partUri, contentType, CompressionOption.NotCompressed); } /// <summary> /// Creates a new part in the package. An empty stream corresponding to this part will be created in the /// package. If a part with the specified uri already exists then we throw an exception. /// This methods will call the CreatePartCore method which will create the actual PackagePart in the package. /// </summary> /// <param name="partUri">Uri of the PackagePart that is to be added</param> /// <param name="contentType">ContentType of the stream to be added</param> /// <param name="compressionOption">CompressionOption describing compression configuration /// for the new part. This compression apply only to the part, it doesn't affect relationship parts or related parts. /// This parameter is optional. </param> /// <returns></returns> /// <exception cref="ObjectDisposedException">If this Package object has been disposed</exception> /// <exception cref="IOException">If the package is readonly, it cannot be modified</exception> /// <exception cref="ArgumentNullException">If partUri parameter is null</exception> /// <exception cref="ArgumentNullException">If contentType parameter is null</exception> /// <exception cref="ArgumentException">If partUri parameter does not conform to the valid partUri syntax</exception> /// <exception cref="ArgumentOutOfRangeException">If CompressionOption enumeration [compressionOption] does not have one of the valid values</exception> /// <exception cref="InvalidOperationException">If a PackagePart with the given partUri already exists in the Package</exception> public PackagePart CreatePart(Uri partUri, string contentType, CompressionOption compressionOption) { ThrowIfObjectDisposed(); ThrowIfReadOnly(); if (partUri == null) throw new ArgumentNullException("partUri"); if (contentType == null) throw new ArgumentNullException("contentType"); ThrowIfCompressionOptionInvalid(compressionOption); PackUriHelper.ValidatedPartUri validatedPartUri = PackUriHelper.ValidatePartUri(partUri); if (_partList.ContainsKey(validatedPartUri)) throw new InvalidOperationException(SR.Get(SRID.PartAlreadyExists)); // Add the part to the _partList if there is no prefix collision // Note: This is the only place where we pass a null to this method for the part and if the // methods returns successfully then we replace the null with an actual part. AddIfNoPrefixCollisionDetected(validatedPartUri, null /* since we don't have a part yet */); PackagePart addedPart = CreatePartCore(validatedPartUri, contentType, compressionOption); //Set the entry for this Uri with the actual part _partList[validatedPartUri] = addedPart; return addedPart; } /// <summary> /// Returns a part that already exists in the package. If the part /// Corresponding to the URI does not exist in the package then an exception is /// thrown. The method calls the GetPartCore method which actually fetches the part. /// </summary> /// <param name="partUri"></param> /// <returns></returns> /// <exception cref="ObjectDisposedException">If this Package object has been disposed</exception> /// <exception cref="IOException">If the package is write only, information cannot be retrieved from it</exception> /// <exception cref="ArgumentNullException">If partUri parameter is null</exception> /// <exception cref="ArgumentException">If partUri parameter does not conform to the valid partUri syntax</exception> /// <exception cref="InvalidOperationException">If the requested part does not exists in the Package</exception> public PackagePart GetPart(Uri partUri) { PackagePart returnedPart = GetPartHelper(partUri); if (returnedPart == null) throw new InvalidOperationException(SR.Get(SRID.PartDoesNotExist)); else return returnedPart; } /// <summary> /// This is a convenient method to check whether a given part exists in the /// package. This will have a default implementation that will try to retrieve /// the part and then if successful, it will return true. /// If the custom file format has an easier way to do this, they can override this method /// to get this information in a more efficient way. /// </summary> /// <param name="partUri"></param> /// <returns></returns> /// <exception cref="ObjectDisposedException">If this Package object has been disposed</exception> /// <exception cref="IOException">If the package is write only, information cannot be retrieved from it</exception> /// <exception cref="ArgumentNullException">If partUri parameter is null</exception> /// <exception cref="ArgumentException">If partUri parameter does not conform to the valid partUri syntax</exception> public virtual bool PartExists(Uri partUri) { return (GetPartHelper(partUri) != null); } /// <summary> /// This method will do all the house keeping required when a part is deleted /// Then the DeletePartCore method will be called which will have the actual logic to /// do the work specific to the underlying file format and will actually delete the /// stream corresponding to this part. This method does not throw if the specified /// part does not exist. This is in conformance with the FileInfo.Delete call. /// </summary> /// <param name="partUri"></param> /// <exception cref="ObjectDisposedException">If this Package object has been disposed</exception> /// <exception cref="IOException">If the package is readonly, it cannot be modified</exception> /// <exception cref="ArgumentNullException">If partUri parameter is null</exception> /// <exception cref="ArgumentException">If partUri parameter does not conform to the valid partUri syntax</exception> public void DeletePart(Uri partUri) { ThrowIfObjectDisposed(); ThrowIfReadOnly(); ThrowIfInStreamingCreation("DeletePart"); if (partUri == null) throw new ArgumentNullException("partUri"); PackUriHelper.ValidatedPartUri validatedPartUri = (PackUriHelper.ValidatedPartUri)PackUriHelper.ValidatePartUri(partUri); if (_partList.ContainsKey(validatedPartUri)) { //This will get the actual casing of the part that //is stored in the partList which is equivalent to the //partUri provided by the user validatedPartUri = (PackUriHelper.ValidatedPartUri)_partList[validatedPartUri].Uri; _partList[validatedPartUri].IsDeleted = true; _partList[validatedPartUri].Close(); //Call the Subclass to delete the part //!!Important Note: The order of this call is important as one of the //sub-classes - ZipPackage relies upon the abstract layer to be //able to provide the ZipPackagePart in order to do the proper //clean up and delete operation. //The dependency is in ZipPackagePart.DeletePartCore method. //Ideally we would have liked to avoid this kind of a restriction //but due to the current class interfaces and data structure ownerships //between these objects, it tough to re-design at this point. DeletePartCore(validatedPartUri); //Finally remove it from the list of parts in the cache _partList.Remove(validatedPartUri); } else //If the part is not in memory we still call the underlying layer //to delete the part if it exists DeletePartCore(validatedPartUri); if (PackUriHelper.IsRelationshipPartUri(validatedPartUri)) { //We clear the in-memory data structure corresponding to that relationship part //This will ensure that the intention of the user to delete the part, is respected. //And thus we will not try to recreate it just in case there was some data in the //memory structure. Uri owningPartUri = PackUriHelper.GetSourcePartUriFromRelationshipPartUri(validatedPartUri); //Package-level relationships in /_rels/.rels if (Uri.Compare(owningPartUri, PackUriHelper.PackageRootUri, UriComponents.SerializationInfoString, UriFormat.UriEscaped, StringComparison.Ordinal)==0) { //Clear any data in memory this.ClearRelationships(); } else { //Clear any data in memory if (this.PartExists(owningPartUri)) { PackagePart owningPart = this.GetPart(owningPartUri); owningPart.ClearRelationships(); } } } else { // remove any relationship part DeletePart(PackUriHelper.GetRelationshipPartUri(validatedPartUri)); } } /// <summary> /// This returns a collection of all the Parts within the package. /// </summary> /// <returns></returns> /// <exception cref="ObjectDisposedException">If this Package object has been disposed</exception> /// <exception cref="IOException">If the package is writeonly, no information can be retrieved from it</exception> public PackagePartCollection GetParts() { ThrowIfObjectDisposed(); ThrowIfWriteOnly(); //Ideally we should decide whether we should query the underlying layer for parts based on the //FileShare enum. But since we do not have that information, currently the design is to just //query the underlying layer once. //Note: //Currently the incremental behavior for GetPart method is not consistent with the GetParts method //which just queries the underlying layer once. if (_partCollection == null) { PackagePart[] parts = GetPartsCore(); //making sure that we get a valid array Debug.Assert((parts != null), "Subclass is expected to return an array [an empty one if there are no parts] as a result of GetPartsCore method call. "); PackUriHelper.ValidatedPartUri partUri; //We need this dictionary to detect any collisions that might be present in the //list of parts that was given to us from the underlying physical layer, as more than one //partnames can be mapped to the same normalized part. //Note: We cannot use the _partList member variable, as that gets updated incrementally and so its //not possible to find the collisions using that list. //PackUriHelper.ValidatedPartUri implements the IComparable interface. Dictionary<PackUriHelper.ValidatedPartUri, PackagePart> seenPartUris = new Dictionary<PackUriHelper.ValidatedPartUri, PackagePart>(parts.Length); for (int i = 0; i < parts.Length; i++) { partUri = (PackUriHelper.ValidatedPartUri)parts[i].Uri; if (seenPartUris.ContainsKey(partUri)) throw new FileFormatException(SR.Get(SRID.BadPackageFormat)); else { // Add the part to the list of URIs that we have already seen seenPartUris.Add(partUri, parts[i]); if (!_partList.ContainsKey(partUri)) { // Add the part to the _partList if there is no prefix collision AddIfNoPrefixCollisionDetected(partUri, parts[i]); } } } _partCollection = new PackagePartCollection(_partList); } return _partCollection; } #endregion PackagePart Methods #region IDisposable Methods /// <summary> /// Member of the IDisposable interface. This method will clean up all the resources. /// It calls the Flush method to make sure that all the changes made get persisted. /// Note - subclasses should only override Dispose(bool) if they have resources to release. /// See the Design Guidelines for the Dispose() pattern. /// </summary> void IDisposable.Dispose() { if (!_disposed) { try { // put our house in order before involving the subclass // close core properties // This method will write out the core properties to the stream // In non-streaming mode - These will get flushed to the disk as a part of the DoFlush operation if (_packageProperties != null) _packageProperties.Close(); // flush relationships if (InStreamingCreation) ClosePackageRelationships(); else FlushRelationships(); //Write out the Relationship XML for the parts //These streams will get flushed in the DoClose operation. DoOperationOnEachPart(DoCloseRelationshipsXml); // Close all the parts that are currently open DoOperationOnEachPart(DoClose); // start the dispose chain Dispose(true); } finally { // do this no matter what (handles case of poorly behaving subclass that doesn't call back into Dispose(bool) _disposed = true; } //Since all the resources we care about are freed at this point. GC.SuppressFinalize(this); } } #endregion IDisposable Methods #region Other Methods /// <summary> /// Closes the package and all the underlying parts and relationships. /// Calls the Dispose Method, since they have the same semantics /// </summary> public void Close() { ((IDisposable)this).Dispose(); } /// <summary> /// Flushes the contents of the parts and the relationships to the package. /// This method will call the FlushCore method which will do the actual flushing of contents. /// </summary> /// <exception cref="ObjectDisposedException">If this Package object has been disposed</exception> /// <exception cref="IOException">If the package is readonly, it cannot be modified</exception> public void Flush() { ThrowIfObjectDisposed(); ThrowIfReadOnly(); // Flush core properties (in streaming production, has to be done before parts get flushed). // Write core properties (in streaming production, has to be done before parts get flushed). // This call will write out the xml for the core properties to the stream // In non-streaming mode - These properties will get flushed to disk as a part of the DoFlush operation if (_packageProperties != null) _packageProperties.Flush(); // Write package relationships XML to the relationship part stream. // These will get flushed to disk as a part of the DoFlush operation if (InStreamingCreation) FlushPackageRelationships(); // Create a piece. else FlushRelationships(); // Flush into .rels part. //Write out the Relationship XML for the parts //These streams will get flushed in the DoFlush operation. DoOperationOnEachPart(DoWriteRelationshipsXml); // Flush all the parts that are currently open. // This will flush part relationships. DoOperationOnEachPart(DoFlush); FlushCore(); } #endregion Other Methods #region PackageRelationship Methods /// <summary> /// Creates a relationship at the Package level with the Target PackagePart specified as the Uri /// </summary> /// <param name="targetUri">Target's URI</param> /// <param name="targetMode">Enumeration indicating the base uri for the target uri</param> /// <param name="relationshipType">PackageRelationship type, having uri like syntax that is used to /// uniquely identify the role of the relationship</param> /// <returns></returns> /// <exception cref="ObjectDisposedException">If this Package object has been disposed</exception> /// <exception cref="IOException">If the package is readonly, it cannot be modified</exception> /// <exception cref="ArgumentNullException">If parameter "targetUri" is null</exception> /// <exception cref="ArgumentNullException">If parameter "relationshipType" is null</exception> /// <exception cref="ArgumentOutOfRangeException">If parameter "targetMode" enumeration does not have a valid value</exception> /// <exception cref="ArgumentException">If TargetMode is TargetMode.Internal and the targetUri is an absolute Uri </exception> /// <exception cref="ArgumentException">If relationship is being targeted to a relationship part</exception> public PackageRelationship CreateRelationship(Uri targetUri, TargetMode targetMode, string relationshipType) { return CreateRelationship(targetUri, targetMode, relationshipType, null); } /// <summary> /// Creates a relationship at the Package level with the Target PackagePart specified as the Uri /// </summary> /// <param name="targetUri">Target's URI</param> /// <param name="targetMode">Enumeration indicating the base uri for the target uri</param> /// <param name="relationshipType">PackageRelationship type, having uri like syntax that is used to /// uniquely identify the role of the relationship</param> /// <param name="id">String that conforms to the xsd:ID datatype. Unique across the source's /// relationships. Null is OK (ID will be generated). An empty string is an invalid XML ID.</param> /// <returns></returns> /// <exception cref="ObjectDisposedException">If this Package object has been disposed</exception> /// <exception cref="IOException">If the package is readonly, it cannot be modified</exception> /// <exception cref="ArgumentNullException">If parameter "targetUri" is null</exception> /// <exception cref="ArgumentNullException">If parameter "relationshipType" is null</exception> /// <exception cref="ArgumentOutOfRangeException">If parameter "targetMode" enumeration does not have a valid value</exception> /// <exception cref="ArgumentException">If TargetMode is TargetMode.Internal and the targetUri is an absolute Uri </exception> /// <exception cref="ArgumentException">If relationship is being targeted to a relationship part</exception> /// <exception cref="System.Xml.XmlException">If parameter "id" is not a valid Xsd Id</exception> /// <exception cref="System.Xml.XmlException">If an id is provided in the method, and its not unique</exception> public PackageRelationship CreateRelationship(Uri targetUri, TargetMode targetMode, string relationshipType, String id) { ThrowIfObjectDisposed(); ThrowIfReadOnly(); EnsureRelationships(); //All parameter validation is done in the following call return _relationships.Add(targetUri, targetMode, relationshipType, id); } /// <summary> /// Deletes a relationship from the Package. This is done based on the /// relationship's ID. The target PackagePart is not affected by this operation. /// </summary> /// <param name="id">The ID of the relationship to delete. An invalid ID will not /// throw an exception, but nothing will be deleted.</param> /// <exception cref="ObjectDisposedException">If this Package object has been disposed</exception> /// <exception cref="IOException">If the package is readonly, it cannot be modified</exception> /// <exception cref="ArgumentNullException">If parameter "id" is null</exception> /// <exception cref="System.Xml.XmlException">If parameter "id" is not a valid Xsd Id</exception> public void DeleteRelationship(String id) { ThrowIfObjectDisposed(); ThrowIfReadOnly(); ThrowIfInStreamingCreation("DeleteRelationship"); if (id == null) throw new ArgumentNullException("id"); InternalRelationshipCollection.ThrowIfInvalidXsdId(id); EnsureRelationships(); _relationships.Delete(id); } /// <summary> /// Returns a collection of all the Relationships that are /// owned by the package /// </summary> /// <returns></returns> /// <exception cref="ObjectDisposedException">If this Package object has been disposed</exception> /// <exception cref="IOException">If the package is write only, no information can be retrieved from it</exception> public PackageRelationshipCollection GetRelationships() { //All the validations for dispose and file access are done in the //GetRelationshipsHelper method. return GetRelationshipsHelper(null); } /// <summary> /// Returns a collection of filtered Relationships that are /// owned by the package /// The filter string is compared with the type of the relationships /// in a case sensitive and culture ignorant manner. /// </summary> /// <returns></returns> /// <exception cref="ObjectDisposedException">If this Package object has been disposed</exception> /// <exception cref="IOException">If the package is write only, no information can be retrieved from it</exception> /// <exception cref="ArgumentNullException">If parameter "relationshipType" is null</exception> /// <exception cref="ArgumentException">If parameter "relationshipType" is an empty string</exception> public PackageRelationshipCollection GetRelationshipsByType(string relationshipType) { //These checks are made in the GetRelationshipsHelper as well, but we make them //here as we need to perform parameter validation ThrowIfObjectDisposed(); ThrowIfWriteOnly(); if (relationshipType == null) throw new ArgumentNullException("relationshipType"); InternalRelationshipCollection.ThrowIfInvalidRelationshipType(relationshipType); return GetRelationshipsHelper(relationshipType); } /// <summary> /// Retrieve a relationship per ID. /// </summary> /// <param name="id">The relationship ID.</param> /// <returns>The relationship with ID 'id' or throw an exception if not found.</returns> /// <exception cref="ObjectDisposedException">If this Package object has been disposed</exception> /// <exception cref="IOException">If the package is write only, no information can be retrieved from it</exception> /// <exception cref="ArgumentNullException">If parameter "id" is null</exception> /// <exception cref="System.Xml.XmlException">If parameter "id" is not a valid Xsd Id</exception> /// <exception cref="InvalidOperationException">If the requested relationship does not exist in the Package</exception> public PackageRelationship GetRelationship(string id) { //All the validations for dispose and file access are done in the //GetRelationshipHelper method. PackageRelationship returnedRelationship = GetRelationshipHelper(id); if (returnedRelationship == null) throw new InvalidOperationException(SR.Get(SRID.PackageRelationshipDoesNotExist)); else return returnedRelationship; } /// <summary> /// Returns whether there is a relationship with the specified ID. /// </summary> /// <param name="id">The relationship ID.</param> /// <returns>true iff a relationship with ID 'id' is defined on this source.</returns> /// <exception cref="ObjectDisposedException">If this Package object has been disposed</exception> /// <exception cref="IOException">If the package is write only, no information can be retrieved from it</exception> /// <exception cref="ArgumentNullException">If parameter "id" is null</exception> /// <exception cref="System.Xml.XmlException">If parameter "id" is not a valid Xsd Id</exception> public bool RelationshipExists(string id) { //All the validations for dispose and file access are done in the //GetRelationshipHelper method. return (GetRelationshipHelper(id) != null); } #endregion PackageRelationship Methods #endregion Public Methods #region Protected Abstract Methods /// <summary> /// This method is for custom implementation corresponding to the underlying file format. /// This method will actually add a new part to the package. An empty part should be /// created as a result of this call. /// </summary> /// <param name="partUri"></param> /// <param name="contentType"></param> /// <param name="compressionOption"></param> /// <returns></returns> protected abstract PackagePart CreatePartCore(Uri partUri, string contentType, CompressionOption compressionOption); /// <summary> /// This method is for custom implementation corresponding to the underlying file format. /// This method will actually return the part after reading the actual physical bits. /// If the PackagePart does not exists in the underlying package then this method should return a null. /// This method must not throw an exception if a part does not exist. /// </summary> /// <param name="partUri"></param> /// <returns></returns> protected abstract PackagePart GetPartCore(Uri partUri); /// <summary> /// This method is for custom implementation corresponding to the underlying file format. /// This method will actually delete the part from the underlying package. /// This method should not throw if the specified part does not exist. /// This is in conformance with the FileInfo.Delete call. /// </summary> /// <param name="partUri"></param> protected abstract void DeletePartCore(Uri partUri); /// <summary> /// This method is for custom implementation corresponding to the underlying file format. /// This is the method that knows how to get the actual parts. If there are no parts, /// this method should return an empty array. /// </summary> /// <returns></returns> protected abstract PackagePart[] GetPartsCore(); /// <summary> /// This method is for custom implementation corresponding to the underlying file format. /// This method should be used to dispose the resources that are specific to the file format. /// Also everything should be flushed to the disc before closing the package. /// </summary> /// <remarks>Subclasses that manage non-memory resources should override this method and free these resources. /// Any override should be careful to always call base.Dispose(disposing) to ensure orderly cleanup.</remarks> protected virtual void Dispose(bool disposing) { if (!_disposed && disposing) { if (_partList != null) { _partList.Clear(); } if (_packageProperties != null) { _packageProperties.Dispose(); _packageProperties = null; } //release objects _partList = null; _partCollection = null; _relationships = null; _disposed = true; } } /// <summary> /// This method is for custom implementation corresponding to the underlying file format. /// This method flushes the contents of the package to the disc. /// </summary> protected abstract void FlushCore(); #endregion Protected Abstract Methods //------------------------------------------------------ // // Internal Constructors // //------------------------------------------------------ // None //------------------------------------------------------ //------------------------------------------------------ // // Internal Properties // //------------------------------------------------------ #region Internal Properties /// <summary> /// true iff the package was opened for streaming. /// </summary> internal bool InStreamingCreation { get { return _inStreamingCreation; } } #endregion Internal Properties //------------------------------------------------------ // // Internal Methods // //------------------------------------------------------ #region Internal Methods // Some operations are not supported while producing a package in streaming mode. internal void ThrowIfInStreamingCreation(string methodName) { if (_inStreamingCreation) throw new IOException(SR.Get(SRID.OperationIsNotSupportedInStreamingProduction, methodName)); } // Some operations are supported only while producing a package in streaming mode. internal void ThrowIfNotInStreamingCreation(string methodName) { if (!InStreamingCreation) throw new IOException(SR.Get(SRID.MethodAvailableOnlyInStreamingCreation, methodName)); } //If the container is readonly then we cannot add/delete to it internal void ThrowIfReadOnly() { if (_openFileAccess == FileAccess.Read) throw new IOException(SR.Get(SRID.CannotModifyReadOnlyContainer)); } // If the container is writeonly, parts cannot be retrieved from it internal void ThrowIfWriteOnly() { if (_openFileAccess == FileAccess.Write) throw new IOException(SR.Get(SRID.CannotRetrievePartsOfWriteOnlyContainer)); } // return true to continue internal delegate bool PartOperation(PackagePart p); internal static void ThrowIfFileModeInvalid(FileMode mode) { //We do the enum check as suggested by the following condition for performance reasons. if (mode < FileMode.CreateNew || mode > FileMode.Append) throw new ArgumentOutOfRangeException("mode"); } internal static void ThrowIfFileAccessInvalid(FileAccess access) { //We do the enum check as suggested by the following condition for performance reasons. if (access < FileAccess.Read || access > FileAccess.ReadWrite) throw new ArgumentOutOfRangeException("access"); } internal static void ThrowIfCompressionOptionInvalid(CompressionOption compressionOption) { //We do the enum check as suggested by the following condition for performance reasons. if (compressionOption < CompressionOption.NotCompressed || compressionOption > CompressionOption.SuperFast) throw new ArgumentOutOfRangeException("compressionOption"); } #region Write-time streaming API /// <summary> /// This method gives the possibility of opening a package in streaming mode. /// When 'streaming' is true, the only allowed file modes are Create and CreateNew, /// the only allowed file access is Write and the only allowed FileShare values are /// Null and Read. /// </summary> /// <param name="path">Path to the package.</param> /// <param name="packageMode">FileMode in which the package should be opened.</param> /// <param name="packageAccess">FileAccess with which the package should be opened.</param> /// <param name="packageShare">FileShare with which the package is opened.</param> /// <param name="streaming">Whether to allow the creation of part pieces while enforcing write-once access.</param> /// <returns>Package</returns> /// <exception cref="ArgumentNullException">If path parameter is null</exception> /// <exception cref="ArgumentOutOfRangeException">If FileAccess enumeration [packageAccess] does not have one of the valid values</exception> /// <exception cref="ArgumentOutOfRangeException">If FileMode enumeration [packageMode] does not have one of the valid values</exception> internal static Package Open( string path, FileMode packageMode, FileAccess packageAccess, FileShare packageShare, bool streaming) { EventTrace.EasyTraceEvent(EventTrace.Keyword.KeywordXPS, EventTrace.Event.WClientDRXOpenPackageBegin); Package package = null; try { if (path == null) throw new ArgumentNullException("path"); ThrowIfFileModeInvalid(packageMode); ThrowIfFileAccessInvalid(packageAccess); ValidateStreamingAccess(packageMode, packageAccess, packageShare, streaming); //Note: FileShare enum is not being verfied at this stage, as we do not interpret the flag in this //code at all and just pass it on to the next layer, where the necessary validation can be //performed. Also, there is no meaningful way to check this parameter at this layer, as the //FileShare enumeration is a set of flags and flags/Bit-fields can be combined using a //bitwise OR operation to create different values, and validity of these values is specific to //the actual physical implementation. //Verify if this is valid for filenames FileInfo packageFileInfo = new FileInfo(path); try { package = new ZipPackage(packageFileInfo.FullName, packageMode, packageAccess, packageShare, streaming); if (!package._inStreamingCreation) // No read operation in streaming production. { //We need to get all the parts if any exists from the underlying file //so that we have the names in the Normalized form in our in-memory //data structures. //Note: If ever this call is removed, each individual call to GetPartCore, //may result in undefined behavior as the underlying ZipArchive, maintains the //files list as being case-sensitive. if (package.FileOpenAccess == FileAccess.ReadWrite || package.FileOpenAccess == FileAccess.Read) package.GetParts(); } } catch { if (package != null) { package.Close(); } throw; } } finally { EventTrace.EasyTraceEvent(EventTrace.Keyword.KeywordXPS, EventTrace.Event.WClientDRXOpenPackageEnd); } return package; } /// <summary> /// This method gives the possibility of opening a package in streaming mode. /// When 'streaming' is true, the only allowed file modes are Create and CreateNew, /// and the only allowed file access is Write. /// </summary> /// <param name="stream">Stream on which the package is created</param> /// <param name="packageMode">FileMode in which the package is to be opened</param> /// <param name="packageAccess">FileAccess on the package that is opened</param> /// <param name="streaming">Whether to allow the creation of part pieces while enforcing write-once access.</param> /// <returns>Package</returns> /// <exception cref="ArgumentNullException">If stream parameter is null</exception> /// <exception cref="ArgumentOutOfRangeException">If FileMode enumeration [packageMode] does not have one of the valid values</exception> /// <exception cref="ArgumentOutOfRangeException">If FileAccess enumeration [packageAccess] does not have one of the valid values</exception> /// <exception cref="IOException">If package to be created should have readwrite/read access and underlying stream is write only</exception> /// <exception cref="IOException">If package to be created should have readwrite/write access and underlying stream is read only</exception> [FriendAccessAllowed] internal static Package Open(Stream stream, FileMode packageMode, FileAccess packageAccess, bool streaming) { EventTrace.EasyTraceEvent(EventTrace.Keyword.KeywordXPS, EventTrace.Event.WClientDRXOpenPackageBegin); Package package = null; try { if (stream == null) throw new ArgumentNullException("stream"); ValidateStreamingAccess(packageMode, packageAccess, null /* no FileShare info */, streaming); //FileMode and FileAccess Enums are validated in the following call Stream ensuredStream = ValidateModeAndAccess(stream, packageMode, packageAccess); try { // Today the Open(Stream) method is purely used for streams of Zip file format as // that is the default underlying file format mapper implemented. package = new ZipPackage(ensuredStream, packageMode, packageAccess, streaming); if (!package._inStreamingCreation) // No read operation in streaming production. { //We need to get all the parts if any exists from the underlying file //so that we have the names in the Normalized form in our in-memory //data structures. //Note: If ever this call is removed, each individual call to GetPartCore, //may result in undefined behavior as the underlying ZipArchive, maintains the //files list as being case-sensitive. if (package.FileOpenAccess == FileAccess.ReadWrite || package.FileOpenAccess == FileAccess.Read) package.GetParts(); } } catch { if (package != null) { package.Close(); } throw; } } finally { EventTrace.EasyTraceEvent(EventTrace.Keyword.KeywordXPS, EventTrace.Event.WClientDRXOpenPackageEnd); } return package; } /// <summary> /// Write a nonterminal piece for /_rels/.rels. /// </summary> internal void FlushPackageRelationships() { ThrowIfNotInStreamingCreation("FlushPackageRelationships"); if (_relationships == null) return; // nothing to flush _relationships.Flush(); } /// <summary> /// Write a terminal piece for /_rels/.rels. /// </summary> internal void ClosePackageRelationships() { ThrowIfNotInStreamingCreation("ClosePackageRelationships"); if (_relationships == null) return; // no relationship part _relationships.CloseInStreamingCreationMode(); } #endregion Write-time streaming API #endregion Internal Methods //------------------------------------------------------ // // Internal Events // //------------------------------------------------------ // None //------------------------------------------------------ // // Private Methods // //------------------------------------------------------ #region Private Methods // This method is only when new part is added to the Package object. // This method will throw an exception if the name of the part being added is a // prefix of the name of an existing part. // Example - Say the following parts exist in the package // 1. /abc.xaml // 2. /xyz/pqr/a.jpg // As an example - Adding any of the following parts will throw an exception - // 1. /abc.xaml/new.xaml // 2. /xyz/pqr private void AddIfNoPrefixCollisionDetected(PackUriHelper.ValidatedPartUri partUri, PackagePart part) { //Add the Normalized Uri to the sorted _partList tentatively to see where it will get inserted _partList.Add(partUri, part); //Get the index of the entry at which this part was added int index = _partList.IndexOfKey(partUri); Invariant.Assert(index >= 0, "Given uri must be present in the dictionary"); string normalizedPartName = partUri.NormalizedPartUriString; string precedingPartName = null; string followingPartName = null; if (index > 0) { precedingPartName = _partList.Keys[index - 1].NormalizedPartUriString; } if (index < _partList.Count - 1) { followingPartName = _partList.Keys[index + 1].NormalizedPartUriString; } if ((precedingPartName != null && normalizedPartName.StartsWith(precedingPartName, StringComparison.Ordinal) && normalizedPartName.Length > precedingPartName.Length && normalizedPartName[precedingPartName.Length] == PackUriHelper.ForwardSlashChar) || (followingPartName != null && followingPartName.StartsWith(normalizedPartName, StringComparison.Ordinal) && followingPartName.Length > normalizedPartName.Length && followingPartName[normalizedPartName.Length] == PackUriHelper.ForwardSlashChar)) { //Removing the invalid entry from the _partList. _partList.Remove(partUri); throw new InvalidOperationException(SR.Get(SRID.PartNamePrefixExists)); } } // Test consistency of file opening parameters with the value of 'streaming', and record // whether the streaming mode is for consumption or production. // private static void ValidateStreamingAccess( FileMode packageMode, FileAccess packageAccess, Nullable<FileShare> packageShare, bool streaming) { if (streaming) { if (packageMode == FileMode.Create || packageMode == FileMode.CreateNew) { if (packageAccess != FileAccess.Write) throw new IOException(SR.Get(SRID.StreamingPackageProductionImpliesWriteOnlyAccess)); if ( packageShare != null && packageShare != FileShare.Read && packageShare != FileShare.None) throw new IOException(SR.Get(SRID.StreamingPackageProductionRequiresSingleWriter)); } else { // Blanket exception pending design of streaming consumption. throw new NotSupportedException(SR.Get(SRID.StreamingModeNotSupportedForConsumption)); } } } //Checking if the mode and access parameters are compatible with the provided stream. private static Stream ValidateModeAndAccess(Stream s, FileMode mode, FileAccess access) { ThrowIfFileModeInvalid(mode); ThrowIfFileAccessInvalid(access); //asking for more permissions than the underlying stream. // Stream cannot write, but package to be created should have write access if (!s.CanWrite && (access == FileAccess.ReadWrite || access == FileAccess.Write)) throw new IOException(SR.Get(SRID.IncompatibleModeOrAccess)); //asking for more permissions than the underlying stream. // Stream cannot read, but the package to be created should have read access if (!s.CanRead && (access == FileAccess.ReadWrite || access == FileAccess.Read)) throw new IOException(SR.Get(SRID.IncompatibleModeOrAccess)); //asking for less restricted access to the underlying stream //stream is ReadWrite but the package is either readonly, or writeonly if ((s.CanRead && s.CanWrite) && (access == FileAccess.Read || access == FileAccess.Write)) { return new RestrictedStream(s, access); } else return s; } //Throw if the object is in a disposed state private void ThrowIfObjectDisposed() { if (_disposed == true) throw new ObjectDisposedException(null, SR.Get(SRID.ObjectDisposed)); } private void EnsureRelationships() { // once per package if (_relationships == null) { _relationships = new InternalRelationshipCollection(this); } } //Delete All Package-level Relationships private void ClearRelationships() { if(_relationships!=null) _relationships.Clear(); } //Flush the relationships at package level private void FlushRelationships() { // flush relationships if (_relationships != null && _openFileAccess != FileAccess.Read) { _relationships.Flush(); } } //We do the close or the flush operation per part private void DoOperationOnEachPart(PartOperation operation) { //foreach (PackagePart p in _partList.Values) // p.Close(); - this throws // Make local copy of part names to prevent exception during enumeration when // a new relationship part gets created (flushing relationships can cause part creation). // This code throws in such a case: // // foreach (PackagePart p in _partList.Values) // p.Flush(); // if (_partList.Count > 0) { int partCount = 0; PackUriHelper.ValidatedPartUri[] partKeys = new PackUriHelper.ValidatedPartUri[_partList.Keys.Count]; foreach (PackUriHelper.ValidatedPartUri uri in _partList.Keys) { partKeys[partCount++] = uri; } // this throws an exception in certain cases (when a part has been deleted) // // _partList.Keys.CopyTo(keys, 0); for (int i = 0; i < _partList.Keys.Count; i++) { // Some of these may disappear during above close because the list contains "relationship parts" // and these are removed if their parts' relationship collection is empty // This fails: // _partList[keys[i]].Flush(); PackagePart p; if (_partList.TryGetValue(partKeys[i], out p)) { if (!operation(p)) break; } } } } //We needed to separate the rels parts from the other parts //because if a rels part for a part occured earlier than the part itself in the array, //the rels part would be closed and then when close the part and try to persist the relationships //for the particular part, it would throw an exception private bool DoClose(PackagePart p) { if (!p.IsClosed) { if (PackUriHelper.IsRelationshipPartUri(p.Uri) && PackUriHelper.ComparePartUri(p.Uri, PackageRelationship.ContainerRelationshipPartName) != 0) { //First we close the source part. //Note - we can safely do this as DoClose is being called on all parts. So ultimately we will end up //closing the source part as well. //This logic only takes care of out of order parts. PackUriHelper.ValidatedPartUri owningPartUri = (PackUriHelper.ValidatedPartUri)PackUriHelper.GetSourcePartUriFromRelationshipPartUri(p.Uri); //If the source part for this rels part exists then we close it. PackagePart sourcePart; if (_partList.TryGetValue(owningPartUri, out sourcePart)) sourcePart.Close(); } p.Close(); } return true; } private bool DoFlush(PackagePart p) { p.Flush(); return true; } private bool DoWriteRelationshipsXml(PackagePart p) { if (!p.IsRelationshipPart) { p.FlushRelationships(); } return true; } private bool DoCloseRelationshipsXml(PackagePart p) { if (!p.IsRelationshipPart) { p.CloseRelationships(); } return true; } private PackagePart GetPartHelper(Uri partUri) { ThrowIfObjectDisposed(); ThrowIfWriteOnly(); if (partUri == null) throw new ArgumentNullException("partUri"); PackUriHelper.ValidatedPartUri validatePartUri = PackUriHelper.ValidatePartUri(partUri); if (_partList.ContainsKey(validatePartUri)) return _partList[validatePartUri]; else { //Ideally we should decide whether we should query the underlying layer for the part based on the //FileShare enum. But since we do not have that information, currently the design is to always //ask the underlying layer, this allows for incremental access to the package. //Note: //Currently this incremental behavior for GetPart is not consistent with the GetParts method //which just queries the underlying layer once. PackagePart returnedPart = GetPartCore(validatePartUri); if (returnedPart != null) { // Add the part to the _partList if there is no prefix collision AddIfNoPrefixCollisionDetected(validatePartUri, returnedPart); } return returnedPart; } } /// <summary> /// Retrieve a relationship per ID. /// </summary> /// <param name="id">The relationship ID.</param> /// <returns>The relationship with ID 'id' or null if not found.</returns> private PackageRelationship GetRelationshipHelper(string id) { ThrowIfObjectDisposed(); ThrowIfWriteOnly(); if (id == null) throw new ArgumentNullException("id"); InternalRelationshipCollection.ThrowIfInvalidXsdId(id); EnsureRelationships(); return _relationships.GetRelationship(id); } /// <summary> /// Returns a collection of all the Relationships that are /// owned by the package based on the filter string. /// </summary> /// <returns></returns> private PackageRelationshipCollection GetRelationshipsHelper(string filterString) { ThrowIfObjectDisposed(); ThrowIfWriteOnly(); EnsureRelationships(); //Internally null is used to indicate that no filter string was specified and //and all the relationships should be returned. return new PackageRelationshipCollection(_relationships, filterString); } #endregion Private Methods //------------------------------------------------------ // // Private Fields // //------------------------------------------------------ #region Private Members // Default values for the Package.Open method overloads private static readonly FileMode _defaultFileMode = FileMode.OpenOrCreate; private static readonly FileAccess _defaultFileAccess = FileAccess.ReadWrite; private static readonly FileShare _defaultFileShare = FileShare.None; private static readonly FileMode _defaultStreamMode = FileMode.Open; private static readonly FileAccess _defaultStreamAccess = FileAccess.Read; private bool _inStreamingCreation; // false by default private FileAccess _openFileAccess; private bool _disposed; private SortedList<PackUriHelper.ValidatedPartUri, PackagePart> _partList; private PackagePartCollection _partCollection; private InternalRelationshipCollection _relationships; private PartBasedPackageProperties _packageProperties; #endregion Private Members //------------------------------------------------------ // // Private Class // //------------------------------------------------------ #region Private Class: Restricted Stream /// <summary> /// This implementation of Stream class is a simple wrapper to restrict the /// read or write access to the underlying stream, as per user request. /// No validation for the stream method calls is done in this wrapper, the calls /// are passed onto the underlying stream object, which should do the /// validation as required. /// </summary> private sealed class RestrictedStream : Stream { #region Constructor /// <summary> /// Constructor /// </summary> /// <param name="stream"></param> /// <param name="access"></param> internal RestrictedStream(Stream stream, FileAccess access) { if (stream == null) throw new ArgumentNullException("stream"); //Verifying if the FileAccess enum is valid //This constructor will never be called with FileAccess.ReadWrite Debug.Assert(access==FileAccess.Read || access == FileAccess.Write, "The constructor of this private class is expected to be called with FileAccess.Read or FileAccess.Write"); _stream = stream; if (access == FileAccess.Read) { _canRead = true; _canWrite = false; } else if (access == FileAccess.Write) { _canRead = false; _canWrite = true; } } #endregion Constructor #region Properties /// <summary> /// Member of the abstract Stream class /// </summary> /// <value>Bool, true if the stream can be read from, else false</value> public override bool CanRead { get { if(!_disposed) return _canRead; else return false; } } /// <summary> /// Member of the abstract Stream class /// </summary> /// <value>Bool, true if the stream can be seeked, else false</value> public override bool CanSeek { get { if(!_disposed) return _stream.CanSeek; else return false; } } /// <summary> /// Member of the abstract Stream class /// </summary> /// <value>Bool, true if the stream can be written to, else false</value> public override bool CanWrite { get { if(!_disposed) return _canWrite; else return false; } } /// <summary> /// Member of the abstract Stream class /// </summary> /// <value>Long value indicating the length of the stream</value> public override long Length { get { ThrowIfStreamDisposed(); return _stream.Length; } } /// <summary> /// Member of the abstract Stream class /// </summary> /// <value>Long value indicating the current position in the stream</value> public override long Position { get { ThrowIfStreamDisposed(); return _stream.Position; } set { ThrowIfStreamDisposed(); _stream.Position = value; } } #endregion Properties #region Methods /// <summary> /// Member of the abstract Stream class /// </summary> /// <param name="offset">only zero is supported</param> /// <param name="origin">only SeekOrigin.Begin is supported</param> /// <returns>zero</returns> public override long Seek(long offset, SeekOrigin origin) { ThrowIfStreamDisposed(); return _stream.Seek(offset, origin); } /// <summary> /// Member of the abstract Stream class /// </summary> /// <param name="newLength"></param> public override void SetLength(long newLength) { ThrowIfStreamDisposed(); if (_canWrite) _stream.SetLength(newLength); else throw new NotSupportedException(SR.Get(SRID.ReadOnlyStream)); } /// <summary> /// Member of the abstract Stream class /// </summary> /// <param name="buffer"></param> /// <param name="offset"></param> /// <param name="count"></param> /// <returns></returns> /// <remarks> /// The standard Stream.Read semantics, and in particular the restoration of the current /// position in case of an exception, is implemented by the underlying stream. /// </remarks> public override int Read(byte[] buffer, int offset, int count) { ThrowIfStreamDisposed(); if (_canRead) return _stream.Read(buffer, offset, count); else throw new NotSupportedException(SR.Get(SRID.WriteOnlyStream)); } /// <summary> /// Member of the abstract Stream class /// </summary> /// <param name="buf"></param> /// <param name="offset"></param> /// <param name="count"></param> public override void Write(byte[] buf, int offset, int count) { ThrowIfStreamDisposed(); if (_canWrite) _stream.Write(buf, offset, count); else throw new NotSupportedException(SR.Get(SRID.ReadOnlyStream)); } /// <summary> /// Member of the abstract Stream class /// </summary> public override void Flush() { ThrowIfStreamDisposed(); if (_canWrite) _stream.Flush(); } #endregion Methods //------------------------------------------------------ // // Protected Methods // //------------------------------------------------------ /// <summary> /// Dispose(bool) /// </summary> /// <param name="disposing"></param> protected override void Dispose(bool disposing) { try { if (disposing) { if (!_disposed) { _stream.Close(); } } } finally { _disposed = true; base.Dispose(disposing); } } #region Private Methods private void ThrowIfStreamDisposed() { if (_disposed) throw new ObjectDisposedException(null, SR.Get(SRID.StreamObjectDisposed)); } #endregion Private Methods #region Private Variables private Stream _stream; private bool _canRead; private bool _canWrite; private bool _disposed; #endregion Private Variables } #endregion Private Class: Restricted Stream } }
45.89422
167
0.584758
[ "Apache-2.0" ]
295007712/295007712.github.io
sourceCode/dotNet4.6/wpf/src/Base/System/IO/Packaging/Package.cs
79,397
C#
using System; using System.IO; namespace ScottPlotTests; internal static class TestIO { public static string SaveFig(ScottPlot.Plot plot) { var stackTrace = new System.Diagnostics.StackTrace(); string callingMethodName = stackTrace.GetFrame(1)!.GetMethod()!.Name; string filename = callingMethodName + ".png"; string folder = Path.GetFullPath("RenderTest"); if (!Directory.Exists(folder)) Directory.CreateDirectory(folder); string path = Path.Combine(folder, filename); var sw = System.Diagnostics.Stopwatch.StartNew(); plot.SaveFig(path); sw.Stop(); Console.WriteLine($"Saved in {sw.Elapsed.TotalMilliseconds:N3} ms"); Console.WriteLine(path); return path; } }
29.148148
77
0.653113
[ "MIT" ]
Glepooek/ScottPlot
dev/ScottPlot5/ScottPlotTests/TestIO.cs
789
C#
using System.Resources; 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("Colour Creator")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Colour Creator")] [assembly: AssemblyCopyright("Copyright © Peter Wagner (aka Wagnerp) & Simon Coghlan (aka Smurf-IV) 2018 - 2020. All rights reserved.")] [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("eec1bbb0-c57d-4a84-960e-c43069190f6f")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("5.451.453.0")] [assembly: AssemblyFileVersion("5.451.453.0")] [assembly: NeutralResourcesLanguage("en-GB")]
39.025
136
0.75016
[ "BSD-3-Clause" ]
Krypton-Suite-Legacy/Krypton-Toolkit-Suite-Extended-NET-5.451
Source/Krypton Toolkit Suite Extended/Applications/Colour Creator/Properties/AssemblyInfo.cs
1,564
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Represents a simple compiler generated parameter of a given type. /// </summary> internal abstract class SynthesizedParameterSymbolBase : ParameterSymbol { private readonly MethodSymbol _container; private readonly TypeWithAnnotations _type; private readonly int _ordinal; private readonly string _name; private readonly RefKind _refKind; public SynthesizedParameterSymbolBase( MethodSymbol container, TypeWithAnnotations type, int ordinal, RefKind refKind, string name = "") { Debug.Assert(type.HasType); Debug.Assert(name != null); Debug.Assert(ordinal >= 0); _container = container; _type = type; _ordinal = ordinal; _refKind = refKind; _name = name; } public override TypeWithAnnotations TypeWithAnnotations { get { return _type; } } public override RefKind RefKind { get { return _refKind; } } internal override bool IsMetadataIn => RefKind == RefKind.In; internal override bool IsMetadataOut => RefKind == RefKind.Out; internal override MarshalPseudoCustomAttributeData MarshallingInformation { get { return null; } } public override string Name { get { return _name; } } public abstract override ImmutableArray<CustomModifier> RefCustomModifiers { get; } public override int Ordinal { get { return _ordinal; } } public override bool IsParams { get { return false; } } internal override bool IsMetadataOptional { get { return false; } } public override bool IsImplicitlyDeclared { get { return true; } } internal override ConstantValue ExplicitDefaultConstantValue { get { return null; } } internal override bool IsIDispatchConstant { get { return false; } } internal override bool IsIUnknownConstant { get { return false; } } internal override bool IsCallerLineNumber { get { return false; } } internal override bool IsCallerFilePath { get { return false; } } internal override bool IsCallerMemberName { get { return false; } } internal override FlowAnalysisAnnotations FlowAnalysisAnnotations { get { return FlowAnalysisAnnotations.None; } } public override Symbol ContainingSymbol { get { return _container; } } public override ImmutableArray<Location> Locations { get { return ImmutableArray<Location>.Empty; } } public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences { get { return ImmutableArray<SyntaxReference>.Empty; } } internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder<SynthesizedAttributeData> attributes) { // Emit [Dynamic] on synthesized parameter symbols when the original parameter was dynamic // in order to facilitate debugging. In the case the necessary attributes are missing // this is a no-op. Emitting an error here, or when the original parameter was bound, would // adversely effect the compilation or potentially change overload resolution. var compilation = this.DeclaringCompilation; var type = this.TypeWithAnnotations; if (type.Type.ContainsDynamic() && compilation.HasDynamicEmitAttributes() && compilation.CanEmitBoolean()) { AddSynthesizedAttribute(ref attributes, compilation.SynthesizeDynamicAttribute(type.Type, type.CustomModifiers.Length + this.RefCustomModifiers.Length, this.RefKind)); } if (type.Type.ContainsTupleNames() && compilation.HasTupleNamesAttributes && compilation.CanEmitSpecialType(SpecialType.System_String)) { AddSynthesizedAttribute(ref attributes, compilation.SynthesizeTupleNamesAttribute(type.Type)); } if (TypeWithAnnotations.NeedsNullableAttribute()) { AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeNullableAttribute(this, TypeWithAnnotations)); } if (this.RefKind == RefKind.RefReadOnly) { AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeIsReadOnlyAttribute(this)); } } } internal sealed class SynthesizedParameterSymbol : SynthesizedParameterSymbolBase { private SynthesizedParameterSymbol( MethodSymbol container, TypeWithAnnotations type, int ordinal, RefKind refKind, string name) : base(container, type, ordinal, refKind, name) { } public static ParameterSymbol Create( MethodSymbol container, TypeWithAnnotations type, int ordinal, RefKind refKind, string name = "", ImmutableArray<CustomModifier> refCustomModifiers = default(ImmutableArray<CustomModifier>)) { if (refCustomModifiers.IsDefaultOrEmpty) { return new SynthesizedParameterSymbol(container, type, ordinal, refKind, name); } return new SynthesizedParameterSymbolWithCustomModifiers(container, type, ordinal, refKind, name, refCustomModifiers); } /// <summary> /// For each parameter of a source method, construct a corresponding synthesized parameter /// for a destination method. /// </summary> /// <param name="sourceMethod">Has parameters.</param> /// <param name="destinationMethod">Needs parameters.</param> /// <returns>Synthesized parameters to add to destination method.</returns> internal static ImmutableArray<ParameterSymbol> DeriveParameters(MethodSymbol sourceMethod, MethodSymbol destinationMethod) { var builder = ArrayBuilder<ParameterSymbol>.GetInstance(); foreach (var oldParam in sourceMethod.Parameters) { //same properties as the old one, just change the owner builder.Add(SynthesizedParameterSymbol.Create(destinationMethod, oldParam.TypeWithAnnotations, oldParam.Ordinal, oldParam.RefKind, oldParam.Name, oldParam.RefCustomModifiers)); } return builder.ToImmutableAndFree(); } public override ImmutableArray<CustomModifier> RefCustomModifiers { get { return ImmutableArray<CustomModifier>.Empty; } } private sealed class SynthesizedParameterSymbolWithCustomModifiers : SynthesizedParameterSymbolBase { private readonly ImmutableArray<CustomModifier> _refCustomModifiers; public SynthesizedParameterSymbolWithCustomModifiers( MethodSymbol container, TypeWithAnnotations type, int ordinal, RefKind refKind, string name, ImmutableArray<CustomModifier> refCustomModifiers) : base(container, type, ordinal, refKind, name) { _refCustomModifiers = refCustomModifiers.NullToEmpty(); } public override ImmutableArray<CustomModifier> RefCustomModifiers { get { return _refCustomModifiers; } } } } }
34.003984
183
0.612888
[ "Apache-2.0" ]
JoeRobich/roslyn
src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedParameterSymbol.cs
8,537
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using TMPro; public class WeaponPickUp : Interactable { public WeaponItem weapon; public override void Interact(PlayerManager playerManager) { base.Interact(playerManager); // Pick up item and add to player inventory PickUpItem(playerManager); } private void PickUpItem(PlayerManager playerManager) { PlayerInventory inventory; PlayerLocomotion playerLocomotion; AnimatorHandler animatorHandler; inventory = playerManager.GetComponent<PlayerInventory>(); playerLocomotion = playerManager.GetComponent<PlayerLocomotion>(); animatorHandler = playerManager.GetComponentInChildren<AnimatorHandler>(); playerLocomotion.rigidbody.velocity = Vector3.zero; animatorHandler.PlayTargetAnimation(AnimatorHandler.Pick_Up_Item_STATE, true); inventory.weaponInventory.Add(weapon); playerManager.interactableUI.itemText.text = weapon.itemName; playerManager.interactableUI.itemIcon.sprite = weapon.itemIcon; playerManager.itemInteractableObject.SetActive(true); Destroy(gameObject); } }
32.5
86
0.736842
[ "MIT" ]
tsabobo/gitgud
Assets/Scripts/Item/WeaponPickUp.cs
1,235
C#
using System.Collections; using System.Collections.Generic; using UnityEngine;
13.5
33
0.82716
[ "MIT" ]
Joji-S/MobileGame
SurvivalGame/Assets/Scripts/Item/Stick.cs
81
C#
using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo("LWGraphicsTests")] [assembly: InternalsVisibleTo("Unity.RenderPipelines.Lightweight.Editor.Tests")]
34.2
80
0.836257
[ "MIT" ]
AcquaWh/MuseoLeapmotion
Library/PackageCache/com.unity.render-pipelines.lightweight@5.7.2/Runtime/AssemblyInfo.cs
171
C#
using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Hosting; namespace TAPSS.Web { public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); } }
25.75
70
0.574757
[ "MIT" ]
SSimco/TAPSS
src/TAPSS.Web/Program.cs
515
C#
using System.Threading; using System.Threading.Tasks; namespace WorkflowCore.Interface { /// <remarks> /// The implemention of this interface will be responsible for /// providing a (distributed) locking mechanism to manage in flight workflows /// </remarks> public interface IDistributedLockProvider { /// <summary> /// Acquire a lock on the specified resource. /// </summary> /// <param name="Id">Resource ID to lock.</param> /// <param name="cancellationToken"></param> /// <returns>`true`, if the lock was acquired.</returns> Task<bool> AcquireLock(string Id, CancellationToken cancellationToken); Task ReleaseLock(string Id); Task Start(); Task Stop(); } }
28.851852
85
0.629012
[ "MIT" ]
ChenxiaobaoPros/workflow-core
src/WorkflowCore/Interface/IDistributedLockProvider.cs
781
C#
using Microsoft.AspNetCore.Builder; using Tips.Middleware.ExceptionHandling; using Tips.Middleware.Logging; namespace Tips.Middleware.Extensions { public static class ApplicationBuilderExtensions { public static IApplicationBuilder ConfigureExceptionHandler(this IApplicationBuilder builder) => builder.UseMiddleware<ExceptionHandlerMiddleware>(); public static IApplicationBuilder ConfigureHttpInfoLogger(this IApplicationBuilder builder) => builder.UseMiddleware<HttpInfoLoggerMiddleware>(); } }
40.615385
157
0.816288
[ "MIT" ]
penblade/Tips
Tips.ApiMessage/src/Middleware/Extensions/ApplicationBuilderExtensions.cs
530
C#
using System; using System.Threading; using TheGamedevGuru; using UnityEngine; public class Logic_GrabACoffeeSlow_Sliced_6 : MonoBehaviour, IBatchUpdate { private void Start() { UpdateManager.Instance.RegisterUpdateSliced(this, 0); } private void OnDestroy() { UpdateManager.Instance.DeregisterUpdate(this); } public void BatchUpdate() { SlowWork(); } private void SlowWork() { Thread.Sleep(6); // A lot of calculations, trust me! } }
18.821429
73
0.645161
[ "MIT" ]
The-Gamedev-Guru/Unity-CPU-Slicing
UnityProject/Assets/TheGamedevGuru/BatchUpdate/Examples/Scripts/Logic_GrabACoffeeSlow_Sliced_6.cs
529
C#
using System; using System.Collections.Generic; namespace SKIT.FlurlHttpClient.Wechat.Api.Models { /// <summary> /// <para>表示 [GET] /cgi-bin/wxopen/getweappsupportversion 接口的响应。</para> /// </summary> public class CgibinWxopenGetWeappSupportVersionResponse : WechatApiResponse { public static class Types { public class SdkVersionList { /// <summary> /// 获取或设置基础库版本列表。 /// </summary> [Newtonsoft.Json.JsonProperty("items")] [System.Text.Json.Serialization.JsonPropertyName("items")] public SdkVersionItem[] Items { get; set; } = default!; } public class SdkVersionItem { /// <summary> /// 获取或设置基础库版本。 /// </summary> [Newtonsoft.Json.JsonProperty("version")] [System.Text.Json.Serialization.JsonPropertyName("version")] public string SdkVersion { get; set; } = default!; /// <summary> /// 获取或设置用户分布百分比。 /// </summary> [Newtonsoft.Json.JsonProperty("percentage")] [System.Text.Json.Serialization.JsonPropertyName("percentage")] public double Percentage { get; set; } } } /// <summary> /// 获取或设置当前基础库版本。 /// </summary> [Newtonsoft.Json.JsonProperty("now_version")] [System.Text.Json.Serialization.JsonPropertyName("now_version")] public string NowSdkVersion { get; set; } = default!; /// <summary> /// 获取或设置基础库版本列表。 /// </summary> [Newtonsoft.Json.JsonProperty("uv_info")] [System.Text.Json.Serialization.JsonPropertyName("uv_info")] public Types.SdkVersionList SdkVersionList { get; set; } = default!; } }
34.160714
79
0.541035
[ "MIT" ]
KimMeng2015/DotNetCore.SKIT.FlurlHttpClient.Wechat
src/SKIT.FlurlHttpClient.Wechat.Api/Models/CgibinWxopen/WeappSupportVersion/CgibinWxopenGetWeappSupportVersionResponse.cs
2,057
C#
// cs1584-3.cs: XML comment on `Test' has syntactically incorrect cref attribute `.' // Line: 8 // Compiler options: -doc:dummy.xml -warnaserror -warn:1 using System; /// <see cref="." /> public class Test { }
19.272727
84
0.674528
[ "Apache-2.0" ]
Sectoid/debian-mono
mcs/errors/cs1584-3.cs
212
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace WindowsFormsApp1 { public partial class LectureUploadForm : Form { public LectureUploadForm() { InitializeComponent(); lvwLecture.View = View.Details; lvwLecture.Columns.Add("주차", "주차"); lvwLecture.Columns.Add("학습단원", "학습단원"); lvwLecture.Columns.Add("구분", "구분"); lvwLecture.Columns.Add("학습목차", "학습목차"); lvwLecture.Columns.Add("인정시간", "인정시간"); lvwLecture.Columns.Add("학습하기", "학습하기"); lvwLecture.Columns.Add("달성시간", "달성시간"); lvwLecture.Columns[0].Width = 100; lvwLecture.Columns[1].Width = 210; lvwLecture.Columns[2].Width = 100; lvwLecture.Columns[3].Width = 180; lvwLecture.Columns[4].Width = 120; lvwLecture.Columns[5].Width = 110; lvwLecture.Columns[6].Width = 110; string[] subject = { "알고리즘", "응용소프트웨어실습", "알고리즘", "컴퓨터구조" }; cmbSubject.Items.AddRange(subject); cmbSubject.SelectedIndex = 0; } private void button1_Click(object sender, EventArgs e) { if (cmbMenu.Visible) cmbMenu.Visible = false; else cmbMenu.Visible = true; } private void btnExit_Click(object sender, EventArgs e) { loginForm login = new loginForm(); this.Close(); login.Show(); } private void btnAddLecture_Click(object sender, EventArgs e) { AddLectureForm addLecture = new AddLectureForm(); addLecture.Show(); } } }
29.3125
72
0.56823
[ "MIT" ]
liyusang1/--TeamProject
project1/WindowsFormsApp1/LectureUploadForm.cs
2,018
C#
//---------------------------------------------------------------------------------- // Microsoft Developer & Platform Evangelism // // Copyright (c) Microsoft Corporation. All rights reserved. // // THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, // EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE. //---------------------------------------------------------------------------------- // The example companies, organizations, products, domain names, // e-mail addresses, logos, people, places, and events depicted // herein are fictitious. No association with any real company, // organization, product, domain name, email address, logo, person, // places, or events is intended or should be inferred. //---------------------------------------------------------------------------------- using Microsoft.WindowsAzure.Management.WebSites.Models; namespace DeployManageWebSites { internal enum WebSitePlans { Free, Shared, Standard }; internal class ManagementControllerParameters { internal string GeoRegion { get; set; } internal string WebSiteName { get; set; } internal WebSitePlans UpgradePlan { get; set; } internal WorkerSizeOptions WorkerSize { get; set; } internal int NumberOfWorkers { get; set; } internal string PublishSettingsFilePath { get; set; } } }
42.911765
85
0.603838
[ "MIT" ]
Azure/AzureQuickStartsProjects
Compute/DeployManageWebSites/ManagementControllerParameters.cs
1,461
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.EntityFrameworkCore; using OnlineBankingApp.Data; using OnlineBankingApp.Models; namespace OnlineBankingApp.Pages.FundTransfers { public class DeleteModel : PageModel { private readonly OnlineBankingApp.Data.OnlineBankingAppContext _context; public DeleteModel(OnlineBankingApp.Data.OnlineBankingAppContext context) { _context = context; } [BindProperty] public FundTransfer FundTransfer { get; set; } public async Task<IActionResult> OnGetAsync(int? id) { if (id == null) { return NotFound(); } FundTransfer = await _context.FundTransfer.FirstOrDefaultAsync(m => m.ID == id); if (FundTransfer == null) { return NotFound(); } return Page(); } public async Task<IActionResult> OnPostAsync(int? id) { if (id == null) { return NotFound(); } FundTransfer = await _context.FundTransfer.FindAsync(id); if (FundTransfer != null) { _context.FundTransfer.Remove(FundTransfer); await _context.SaveChangesAsync(); } return RedirectToPage("./Index"); } } }
25.583333
92
0.581107
[ "MIT" ]
JWilh/ASP.NET-Core-Secure-Coding-Cookbook
Chapter01/data-protection/after/OnlineBankingApp/Pages/FundTransfers/Delete.cshtml.cs
1,535
C#
using System; namespace HatcheryManagement { class AdminUser { public void task() { while(true) { FishRepo fishRepo = FishRepo.GetInstance(); MarketStore marketStore = new MarketStore(); Market market = new Market(); Hatchery hatchery = new Hatchery(); Console.WriteLine(" --------------------------------------------"); Console.WriteLine("| Admin User Mode |"); Console.WriteLine("| |"); Console.WriteLine("| want to Add some fish? |"); Console.WriteLine("| For Rui Fish({0})({1}) [Select-1] |", marketStore.getRui(),fishRepo.getRui()); Console.WriteLine("| For Katla Fish({0})({1}) [Select-2] |", marketStore.getKatla(),fishRepo.getKatla()); Console.WriteLine("| For Ilish Fish({0})({1}) [Select-3] |", marketStore.getIlish(),fishRepo.getIlish()); Console.WriteLine("| Quit [Select-0] |"); Console.WriteLine(" --------------------------------------------"); int option = Convert.ToInt32(Console.ReadLine()); if (option == 0) { break; } else if (option == 1) { Console.WriteLine("Rui Selected"); Console.WriteLine("Enter the ammount of fish: "); int ammount = Convert.ToInt32(Console.ReadLine()); market.buyEvent += hatchery.OnRuiBuy; market.MarketBuy(ammount); } else if (option == 2) { Console.WriteLine("Katla Selected"); Console.WriteLine("Enter the ammount of fish: "); int ammount = Convert.ToInt32(Console.ReadLine()); market.buyEvent += hatchery.OnKatlaBuy; market.MarketBuy(ammount); } else if (option == 3) { Console.WriteLine("Ilish Selected"); Console.WriteLine("Enter the ammount of fish: "); int ammount = Convert.ToInt32(Console.ReadLine()); market.buyEvent += hatchery.OnIlishBuy; market.MarketBuy(ammount); } else { System.Console.WriteLine("xxxxxxx Invalid Input xxxxxxx"); } } } } }
40.746269
128
0.42381
[ "MIT" ]
Koushik-Sarker-Seemanto/HatcheryManagement
AdminUser.cs
2,730
C#
using FluentValidation; using BayiPuan.Entities.Concrete; using BayiPuan.Business.DependencyResolvers.Ninject; using BayiPuan.Business.Abstract; namespace BayiPuan.Business.ValidationRules.FluentValidation { public class ProductValidator:AbstractValidator<Product> { public ProductValidator() { //Eğer CustomRule yazmak istenirse service interfacelerini çözer custom rule için gerekli metodlara ulaşmanızı sağlar var productService = DependencyResolver<IProductService>.Resolve(); //Sadece Boş Olamaz Kontrolü Yapar RuleFor(x => x.ProductId).NotEmpty(); RuleFor(x => x.ProductCode).NotEmpty(); RuleFor(x => x.ProductShortCode).NotEmpty(); RuleFor(x => x.ProductName).NotEmpty(); RuleFor(x => x.UnitTypeId).NotEmpty(); RuleFor(x => x.StockAmount).NotEmpty(); RuleFor(x => x.RemainingStockAmount).NotEmpty(); RuleFor(x => x.CriticalStockAmount).NotEmpty(); RuleFor(x => x.Point).NotEmpty(); RuleFor(x => x.PointToMoney).NotEmpty(); //Custom Rule Kullanımı Aşağıdaki gibidir //Custom(rm => //{ //var useremail = userService.UniqueEmail(rm.Email); // if (rm.Agreement != true /*&& useremail.Email != null*/) // { // return new ValidationFailure(/*you must type the property name here, you must type the error message here */); // } // return null; //}); } } }
37.076923
132
0.657676
[ "MIT" ]
keremvaris/NewGenFramework
BayiPuan.Business/ValidationRules/FluentValidation/ProductValidator.cs
1,463
C#
using System; using System.Collections.Generic; using Microsoft.VisualStudio.TestTools.UnitTesting; using AWSSDK_DotNet.IntegrationTests.Utils; using Amazon.Runtime; using Amazon; using Amazon.S3; using System.IO; using System.Net; using System.Diagnostics; using System.Reflection; using AWSSDK_DotNet.CommonTest.Utils; namespace AWSSDK_DotNet.IntegrationTests.Tests { [TestClass] public class CredentialsTests { [TestMethod] [TestCategory("General")] public void TestSessionCredentials() { using (var sts = new Amazon.SecurityToken.AmazonSecurityTokenServiceClient()) { AWSCredentials credentials = sts.GetSessionToken().Credentials; var originalS3Signature = AWSConfigsS3.UseSignatureVersion4; AWSConfigsS3.UseSignatureVersion4 = true; try { using (var ec2 = new Amazon.EC2.AmazonEC2Client(credentials)) { var regions = ec2.DescribeRegions().Regions; Console.WriteLine(regions.Count); } using (var s3 = new Amazon.S3.AmazonS3Client(credentials)) { var buckets = s3.ListBuckets().Buckets; Console.WriteLine(buckets.Count); } using (var swf = new Amazon.SimpleWorkflow.AmazonSimpleWorkflowClient(credentials)) { var domains = swf.ListDomains(new Amazon.SimpleWorkflow.Model.ListDomainsRequest { RegistrationStatus = "REGISTERED" }).DomainInfos; Console.WriteLine(domains.Infos.Count); } using (var swf = new Amazon.SimpleWorkflow.AmazonSimpleWorkflowClient(credentials, new Amazon.SimpleWorkflow.AmazonSimpleWorkflowConfig { SignatureVersion = "4" })) { var domains = swf.ListDomains(new Amazon.SimpleWorkflow.Model.ListDomainsRequest { RegistrationStatus = "REGISTERED" }).DomainInfos; Console.WriteLine(domains.Infos.Count); } } finally { AWSConfigsS3.UseSignatureVersion4 = originalS3Signature; } } } [TestMethod] [TestCategory("General")] public void TestCredentialsFile() { var ic = new ImmutableCredentials("access-key", "secret-key", null); TestCredentialsFile(ic); ic = new ImmutableCredentials("access-key", "secret-key", "token"); TestCredentialsFile(ic); } [TestMethod] [TestCategory("General")] [TestCategory("ECS")] public void TestECSCredentialsLocal() { string uri = "/ECS/Test/Endpoint/"; string accessKey = "SomeKey"; string secretKey = "SomeSecretKey"; string token = "Token"; string expiration = DateTime.UtcNow.AddHours(1).ToString("s") + "Z"; System.Environment.SetEnvironmentVariable(ECSTaskCredentials.ContainerCredentialsURIEnvVariable, uri); using (ResponseTestServlet servlet = new ResponseTestServlet(uri)) { string server = "http://localhost:" + servlet.Port; servlet.Response = string.Format( @"{{ ""AccessKeyId"" : ""{0}"", ""SecretAccessKey"" : ""{1}"", ""Token"" : ""{2}"", ""Expiration"" : ""{3}"" }}", accessKey, secretKey, token, expiration); ECSTaskCredentials generator = new ECSTaskCredentials(); FieldInfo serverField = generator.GetType().GetField("Server", BindingFlags.Instance | BindingFlags.NonPublic ); Assert.IsNotNull(serverField); serverField.SetValue(generator, server); ImmutableCredentials credentials = generator.GetCredentials(); Assert.AreEqual(accessKey, credentials.AccessKey); Assert.AreEqual(secretKey, credentials.SecretKey); Assert.AreEqual(token, credentials.Token); } System.Environment.SetEnvironmentVariable(ECSTaskCredentials.ContainerCredentialsURIEnvVariable, ""); } private static void TestCredentialsFile(ImmutableCredentials ic) { var profileName = "testProfile"; var profilesLocation = WriteCreds(profileName, ic); #pragma warning disable 618 var creds = new StoredProfileAWSCredentials(profileName, profilesLocation); #pragma warning restore 618 var rc = creds.GetCredentials(); Assert.AreEqual(ic.SecretKey, rc.SecretKey); Assert.AreEqual(ic.AccessKey, rc.AccessKey); Assert.AreEqual(ic.UseToken, rc.UseToken); Assert.AreEqual(ic.Token, rc.Token); for (int i = 0; i < 4; i++) { var shouldHaveToken = (i % 2 == 1); #pragma warning disable 618 creds = new StoredProfileAWSCredentials(profileName + i, profilesLocation); #pragma warning restore 618 Assert.IsNotNull(creds); rc = creds.GetCredentials(); Assert.IsNotNull(rc.AccessKey); Assert.IsNotNull(rc.SecretKey); Assert.AreEqual(shouldHaveToken, rc.UseToken); if (rc.UseToken) { Assert.AreEqual(sessionCreds.AccessKey, rc.AccessKey); Assert.AreEqual(sessionCreds.SecretKey, rc.SecretKey); Assert.AreEqual(sessionCreds.Token, rc.Token); } else { Assert.AreEqual(basicCreds.AccessKey, rc.AccessKey); Assert.AreEqual(basicCreds.SecretKey, rc.SecretKey); } } } private static ImmutableCredentials basicCreds = new ImmutableCredentials("=ac0", "sc=1", null); private static ImmutableCredentials sessionCreds = new ImmutableCredentials("ac2", "sc3=", "token=="); private static string WriteCreds(string profileName, ImmutableCredentials ic) { string configPath = Path.GetFullPath("credentials"); using (var stream = File.Open(configPath, FileMode.Create, FileAccess.Write, FileShare.None)) using (var writer = new StreamWriter(stream)) { AppendCredentialsSet(writer, profileName + "0", basicCreds); AppendCredentialsSet(writer, profileName + "1", sessionCreds); AppendCredentialsSet(writer, profileName, ic); AppendCredentialsSet(writer, profileName + "2", basicCreds); AppendCredentialsSet(writer, profileName + "3", sessionCreds); } return configPath; } private static void AppendCredentialsSet(StreamWriter writer, string profileName, ImmutableCredentials ic) { writer.WriteLine(); writer.WriteLine("; profile {0} and its credentials", profileName); writer.WriteLine("# alternative comment marker"); writer.WriteLine("[{0}]", profileName); writer.WriteLine("aws_access_key_id = {0}", ic.AccessKey); writer.WriteLine("aws_secret_access_key={0}", ic.SecretKey); if (ic.UseToken) writer.WriteLine("aws_session_token= {0}", ic.Token); writer.WriteLine(); } } }
40.306878
184
0.586637
[ "Apache-2.0" ]
Bio2hazard/aws-sdk-net
sdk/test/Services/ECS/IntegrationTests/CredentialsTests.cs
7,620
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc.Rendering; namespace Mapa.Models.AccountViewModels { public class SendCodeViewModel { public string SelectedProvider { get; set; } public ICollection<SelectListItem> Providers { get; set; } public string ReturnUrl { get; set; } public bool RememberMe { get; set; } } }
22.3
66
0.701794
[ "MIT" ]
tacitomv/MapRS
Models/AccountViewModels/SendCodeViewModel.cs
448
C#
using MISD.Core; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Data; using System.Windows.Media; namespace MISD.Client.ViewModel.Converters { public class AvailableAndStateToBackroundConverter : IMultiValueConverter { public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture) { var state = values[0]; var avilable = values[1]; if (avilable is bool) { if (!((bool)avilable)) { return Brushes.Navy; } } if (state is MappingState) { // get colours var stateConverter = new StateToBackgroundConverter(); return stateConverter.Convert(state, targetType, parameter, culture); } else { return Brushes.Violet; } } public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } } }
29.659091
130
0.556322
[ "BSD-3-Clause" ]
sebastianzillessen/MISD-OWL
Code/MISDCode/MISD.Client.ViewModel/Converters/AvailableAndStateToBackroundConverter.cs
1,307
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Apocalypse.Any.Infrastructure.Common.Services.Data { public class IntDeltaService : DeltaService<int> { protected override int GetDelta(int before, int after) { return after - before; } public override int GetMeanOfRecords() { if (RecordDeltas) return (int)Math.Round(DeltaRecords.Average()); else return 0; } } }
22.541667
63
0.595194
[ "MIT" ]
inidibininging/apocalypse_netcore
Apocalypse.Any.Infrastructure.Common.Services.Data/IntDeltaService.cs
543
C#
using CsvHelper; using CsvHelper.Configuration; using System.IO; namespace SharePointRunner.LauncherV1 { internal class CsvWriterWrapper<T1, T2> where T2 : ClassMap<T1> { private bool HeaderWritten { get; set; } = false; private string FilePath { get; set; } = string.Empty; /// <summary> /// Constructor /// </summary> /// <param name="filePath">Path of the file to write</param> public CsvWriterWrapper(string filePath) { FilePath = filePath; } /// <summary> /// Write record to CSV file /// </summary> /// <param name="record">Record to write</param> public void WriteRecord(T1 record) { using (TextWriter writer = new StreamWriter(FilePath, true)) using (CsvWriter csv = new CsvWriter(writer)) { csv.Configuration.Delimiter = ";"; csv.Configuration.QuoteAllFields = true; csv.Configuration.RegisterClassMap<T2>(); if (!HeaderWritten) { // Write the header if not already csv.WriteHeader<T1>(); csv.NextRecord(); HeaderWritten = true; } csv.WriteRecord(record); csv.NextRecord(); } } } }
28.14
72
0.513859
[ "MIT" ]
BPerdriau/SharePointRunner
Examples/V1/SharePointRunner.LauncherV1/CsvWriterWrapper.cs
1,409
C#
using ChromaBoy.Hardware; namespace ChromaBoy.Software.Opcodes { public class LDAHL : Opcode // LD A, (HL-) | LD (HL-), A | LD A, (HL+) | LD (HL+), A { private bool inc; private bool load; public LDAHL(Gameboy parent, byte opcode) : base(parent) { inc = (opcode & 0b10000) == 0; load = (opcode & 0b1000) > 0; Cycles = 8; TickAccurate = true; Disassembly = load ? "ld a, [hl" + (inc ? "+" : "-") + "]" : "ld [hl" + (inc ? "+" : "-") + "], a"; } public override void Execute() { byte srcVal = !load ? parent.Registers[Register.A] : parent.Memory[(parent.Registers[Register.H] << 8) | (parent.Registers[Register.L])]; if (load) parent.Registers[Register.A] = srcVal; else parent.Memory[(parent.Registers[Register.H] << 8) | (parent.Registers[Register.L])] = srcVal; parent.WriteRegister16(Register16.HL, (ushort)(parent.ReadRegister16(Register16.HL) + (inc ? 1 : -1))); } public override void ExecuteTick() { base.ExecuteTick(); if (Tick == 3) Execute(); } } }
33
149
0.510238
[ "MIT" ]
Hacktix/ChromaBoy
Software/Opcodes/Loads/LDAHL.cs
1,223
C#
class ShellSort { static void printArray(int []arr) { int n = arr.Length; for (int i=0; i<n; ++i) Console.Write(arr[i] + " "); Console.WriteLine(); } int sort(int []arr) { int n = arr.Length; for (int gap = n/2; gap > 0; gap /= 2) { for (int i = gap; i < n; i += 1) { int temp = arr[i]; int j; for (j = i; j >= gap && arr[j - gap] > temp; j -= gap) arr[j] = arr[j - gap]; arr[j] = temp; } } return 0; } public static void Main() { int []arr = {12, 34, 54, 2, 3}; Console.Write("Array before sorting :\n"); printArray(arr); ShellSort ob = new ShellSort(); ob.sort(arr); Console.Write("Array after sorting :\n"); printArray(arr); } }
23.068182
72
0.367488
[ "MIT" ]
1305Tanmay/algo_ds_101
Algorithms/Sorting/Shell_Sort/Shell_Sort.cs
1,015
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("DanbooruDBProvider")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("DanbooruDBProvider")] [assembly: AssemblyCopyright("Copyright © 2020")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("f739df92-6e43-486e-915c-1dd6231f03a7")] // 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.2020.06.14")] [assembly: AssemblyFileVersion("1.2020.06.14")]
38.216216
84
0.751768
[ "Unlicense" ]
JuanVillalba/DanbooruDownloader
DanbooruDBProvider/Properties/AssemblyInfo.cs
1,417
C#
using MediatR; using Microsoft.EntityFrameworkCore; using Poo.Api.Core.Domain.EstoqueAgg.Entities; using Poo.Api.Core.Domain.ProductAgg.Entities; using Poo.Api.Core.Domain.Shared.Repositories; using Poo.Api.Core.Domain.Shared; namespace Poo.Api.Core.Infrastructure.Shared { public class PedidoDbContext : DbContext, IUnitOfWork { private readonly DbContextOptions<PedidoDbContext> options; private readonly IMediator _mediator; public PedidoDbContext(DbContextOptions<PedidoDbContext> options, IMediator mediator) : base(options) { this.options = options; _mediator = mediator; } public DbSet<Produto> Produtos { get; set; } public DbSet<EstoqueItem> EstoqueItens { get; set; } void IUnitOfWork.SaveChanges() { var entities = ChangeTracker.Entries<IAggregateRoot>().Select(x => x.Entity).ToList(); var domainEvents = entities.SelectMany(x => x.GetDomainEvents()).ToList(); foreach (var entity in entities) { entity.ClearDomainEvents(); } foreach (var domainEvent in domainEvents) { _mediator.Publish(domainEvent).GetAwaiter().GetResult(); } base.SaveChanges(); } } }
32.047619
109
0.628529
[ "MIT" ]
Nathanscs/POO
src/Api/Core/Infrastructure/Shared/PedidoDbContext.cs
1,348
C#
using System.Data; using System.Data.Entity.Infrastructure; using System.Linq; using System.Net; using System.Web.Http; using System.Web.Http.OData; using LibraryManagement.ObjectModel; using LibraryManagement.Data.DataContext; namespace LibraryManagementAPI.Controllers { /* The WebApiConfig class may require additional changes to add a route for this controller. Merge these statements into the Register method of the WebApiConfig class as applicable. Note that OData URLs are case sensitive. using System.Web.Http.OData.Builder; using System.Web.Http.OData.Extensions; using LibraryManagement.ObjectModel; ODataConventionModelBuilder builder = new ODataConventionModelBuilder(); builder.EntitySet<Level>("Levels"); config.Routes.MapODataServiceRoute("odata", "odata", builder.GetEdmModel()); */ public class LevelsController : ODataController { private LibraryManagementDbContext db = new LibraryManagementDbContext(); // GET: odata/Levels [EnableQuery] public IQueryable<Level> GetLevels() { return db.Levels; } // GET: odata/Levels(5) [EnableQuery] public SingleResult<Level> GetLevel([FromODataUri] int key) { return SingleResult.Create(db.Levels.Where(level => level.Id == key)); } // PUT: odata/Levels(5) public IHttpActionResult Put([FromODataUri] int key, Delta<Level> patch) { Validate(patch.GetEntity()); if (!ModelState.IsValid) { return BadRequest(ModelState); } Level level = db.Levels.Find(key); if (level == null) { return NotFound(); } patch.Put(level); try { db.SaveChanges(); } catch (DbUpdateConcurrencyException) { if (!LevelExists(key)) { return NotFound(); } else { throw; } } return Updated(level); } // POST: odata/Levels public IHttpActionResult Post(Level level) { if (!ModelState.IsValid) { return BadRequest(ModelState); } db.Levels.Add(level); db.SaveChanges(); return Created(level); } // PATCH: odata/Levels(5) [AcceptVerbs("PATCH", "MERGE")] public IHttpActionResult Patch([FromODataUri] int key, Delta<Level> patch) { Validate(patch.GetEntity()); if (!ModelState.IsValid) { return BadRequest(ModelState); } Level level = db.Levels.Find(key); if (level == null) { return NotFound(); } patch.Patch(level); try { db.SaveChanges(); } catch (DbUpdateConcurrencyException) { if (!LevelExists(key)) { return NotFound(); } else { throw; } } return Updated(level); } // DELETE: odata/Levels(5) public IHttpActionResult Delete([FromODataUri] int key) { Level level = db.Levels.Find(key); if (level == null) { return NotFound(); } db.Levels.Remove(level); db.SaveChanges(); return StatusCode(HttpStatusCode.NoContent); } protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } private bool LevelExists(int key) { return db.Levels.Count(e => e.Id == key) > 0; } } }
26.962264
224
0.484021
[ "MIT" ]
ajay-dotnet/LibraryManagementSystem
LibraryManagementAPI/Controllers/LevelsController.cs
4,289
C#
#define COSMOSDEBUG using System; using System.Collections.Generic; using System.IO; using Cosmos.System.FileSystem.Listing; namespace Cosmos.System.FileSystem.VFS { /// <summary> /// VFSManager (Virtual File System Manager) class. Used to manage files and directories. /// </summary> public static class VFSManager { private static VFSBase mVFS; /// <summary> /// Register VFS. Initialize the VFS. /// </summary> /// <param name="aVFS">A VFS to register.</param> /// <exception cref="Exception">Thrown if VFS already registered / memory error.</exception> /// <exception cref="IOException">Thrown on I/O exception.</exception> /// <exception cref="ArgumentNullException">Thrown on memory error.</exception> /// <exception cref="OverflowException">Thrown on memory error.</exception> /// <exception cref="ArgumentException">Thrown on memory error.</exception> /// <exception cref="ArgumentOutOfRangeException">Thrown on memory error.</exception> /// <exception cref="PathTooLongException">Thrown on fatal error.</exception> /// <exception cref="System.Security.SecurityException">Thrown on fatal error.</exception> /// <exception cref="FileNotFoundException">Thrown on memory error.</exception> /// <exception cref="DirectoryNotFoundException">Thrown on fatal error.</exception> public static void RegisterVFS(VFSBase aVFS, bool aShowInfo = true, bool aAllowReinitialise = false) { Global.mFileSystemDebugger.SendInternal("--- VFSManager.RegisterVFS ---"); if (!aAllowReinitialise && mVFS != null) { throw new Exception("Virtual File System Manager already initialized!"); } aVFS.Initialize(aShowInfo); mVFS = aVFS; } /// <summary> /// Create a file. /// </summary> /// <param name="aPath">A path to the file.</param> /// <returns>DirectoryEntry value.</returns> /// <exception cref="ArgumentNullException">Thrown if aPath is null.</exception> /// <exception cref="ArgumentException">Thrown if aPath is empty or contains invalid chars.</exception> /// <exception cref="Exception"> /// <list type="bullet"> /// <item>Thrown when the entry at aPath is not a file.</item> /// <item>Thrown when the parent directory of aPath is not a directory.</item> /// </list> /// </exception> /// <exception cref="PathTooLongException">Thrown when aPath is longer than the system defined max lenght.</exception> public static DirectoryEntry CreateFile(string aPath) { Global.mFileSystemDebugger.SendInternal("--- VFSManager.CreateFile ---"); if (string.IsNullOrEmpty(aPath)) { throw new ArgumentNullException(nameof(aPath)); } Global.mFileSystemDebugger.SendInternal("aPath =" + aPath); return mVFS.CreateFile(aPath); } /// <summary> /// Delete a file. /// </summary> /// <param name="aPath">A path to the file.</param> /// <exception cref="Exception"> /// <list type="bullet"> /// <item>Thrown if VFS manager is null.</item> /// <item>The entry at aPath is not a file.</item> /// </list> /// </exception> /// <exception cref="UnauthorizedAccessException">Thrown when the specified path isn't a file</exception> public static void DeleteFile(string aPath) { if (mVFS == null) throw new Exception("VFSManager isn't ready."); var xFile = mVFS.GetFile(aPath); if (xFile.mEntryType != DirectoryEntryTypeEnum.File) throw new UnauthorizedAccessException("The specified path isn't a file"); mVFS.DeleteFile(xFile); } /// <summary> /// Get file. /// </summary> /// <param name="aPath">A path to the file.</param> /// <returns>DirectoryEntry value.</returns> /// <exception cref="ArgumentException"> /// <list type="bullet"> /// <item>Thrown if aPath is null / empty / invalid.</item> /// <item>Root path is null or empty.</item> /// <item>Memory error.</item> /// <item>Fatal error.</item> /// </list> /// </exception> /// <exception cref="ArgumentNullException"> /// <list type="bullet"> /// <item>Thrown if aPath is null or empty.</item> /// <item>Filesystem is null.</item> /// <item>Root directory is null.</item> /// <item>Memory error.</item> /// </list> /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// <list type="bullet"> /// <item>Thrown when root directory address is smaller then root directory address.</item> /// <item>Memory error.</item> /// </list> /// </exception> /// <exception cref="OverflowException"> /// <list type="bullet"> /// <item>Thrown when aPath is too deep.</item> /// <item>Data lenght is greater then Int32.MaxValue.</item> /// </list> /// </exception> /// <exception cref="Exception"> /// <list type="bullet"> /// <item>Thrown when unable to determine filesystem for path: + aPath.</item> /// <item>data size invalid.</item> /// <item>invalid directory entry type.</item> /// <item>path not found.</item> /// </list> /// </exception> /// <exception cref="DecoderFallbackException">Thrown on memory error.</exception> public static DirectoryEntry GetFile(string aPath) { Global.mFileSystemDebugger.SendInternal("-- VFSManager.GetFile --"); if (string.IsNullOrEmpty(aPath)) { throw new ArgumentNullException(nameof(aPath)); } Global.mFileSystemDebugger.SendInternal("aPath = " + aPath); string xFileName = Path.GetFileName(aPath); Global.mFileSystemDebugger.SendInternal("xFileName = " + xFileName); string xDirectory = aPath.Remove(aPath.Length - xFileName.Length); Global.mFileSystemDebugger.SendInternal("xDirectory = " + xDirectory); char xLastChar = xDirectory[xDirectory.Length - 1]; if (xLastChar != Path.DirectorySeparatorChar) { xDirectory += Path.DirectorySeparatorChar; } var xList = GetDirectoryListing(xDirectory); for (int i = 0; i < xList.Count; i++) { var xEntry = xList[i]; if ((xEntry != null) && (xEntry.mEntryType == DirectoryEntryTypeEnum.File) && (xEntry.mName.ToUpper() == xFileName.ToUpper())) { return xEntry; } } return null; } /// <summary> /// Create directory. /// </summary> /// <param name="aPath">A path to the directory.</param> /// <returns>DirectoryEntry value.</returns> /// <exception cref="ArgumentNullException"> /// <list type="bullet"> /// <item>Thrown if aPath is null / empty / invalid.</item> /// <item>memory error.</item> /// </list> /// </exception> /// <exception cref="ArgumentOutOfRangeException">Thrown on memory error / unknown directory entry type.</exception> /// <exception cref="OverflowException">Thrown when data lenght is greater then Int32.MaxValue.</exception> /// <exception cref="Exception"> /// <list type="bullet"> /// <item>Thrown when data size invalid.</item> /// <item>invalid directory entry type.</item> /// <item>the entry at aPath is not a directory.</item> /// <item>memory error.</item> /// </list> /// </exception> /// <exception cref="ArgumentException"> /// <list type="bullet"> /// <item>Thrown if aPath length is zero.</item> /// <item>Thrown if aPath is invalid.</item> /// <item>memory error.</item> /// </list> /// </exception> /// <exception cref="DecoderFallbackException">Thrown on memory error.</exception> /// <exception cref="RankException">Thrown on fatal error (contact support).</exception> /// <exception cref="ArrayTypeMismatchException">Thrown on fatal error (contact support).</exception> /// <exception cref="InvalidCastException">Thrown on memory error.</exception> /// <exception cref="PathTooLongException">Thrown when The aPath is longer than the system defined maximum length.</exception> public static DirectoryEntry CreateDirectory(string aPath) { Global.mFileSystemDebugger.SendInternal("-- VFSManager.CreateDirectory -- " + aPath); Global.mFileSystemDebugger.SendInternal("aPath = " + aPath); if (String.IsNullOrEmpty(aPath)) { throw new ArgumentNullException(nameof(aPath)); } var directoryEntry = mVFS.CreateDirectory(aPath); Global.mFileSystemDebugger.SendInternal("-- -------------------------- -- " + aPath); return directoryEntry; } /// <summary> /// Delete directory. /// </summary> /// <param name="aPath">A path to the directory.</param> /// <param name="recursive">Recursive delete (not empty directory).</param> /// <exception cref="ArgumentException"> /// <list type="bullet"> /// <item>Thrown if aPath is null or empty.</item> /// <item>Memory error.</item> /// <item>Fatal error.</item> /// </list> /// </exception> /// <exception cref="ArgumentNullException"> /// <list type="bullet"> /// <item>Thrown if VFSManager is null.</item> /// <item>Root directory is null.</item> /// <item>Memory error.</item> /// </list> /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// <list type="bullet"> /// <item>Thrown when root directory address is smaller then root directory address.</item> /// <item>Memory error.</item> /// </list> /// </exception> /// <exception cref="OverflowException"> /// <list type="bullet"> /// <item>Thrown when aPath is too deep.</item> /// <item>Data lenght is greater then Int32.MaxValue.</item> /// </list> /// </exception> /// <exception cref="Exception"> /// <list type="bullet"> /// <item>Thrown if VFSManager is null.</item> /// <item>Thrown when unable to determine filesystem for path: + aPath.</item> /// <item>data size invalid.</item> /// <item>invalid directory entry type.</item> /// <item>path not found.</item> /// </list> /// </exception> /// <exception cref="DecoderFallbackException">Thrown on memory error.</exception> /// <exception cref="IOException">Thrown if specified path isn't a directory / trying to delete not empty directory not recursivly / directory contains a corrupted file.</exception> /// <exception cref="UnauthorizedAccessException">Thrown when trying to delete unknown type entry.</exception> public static void DeleteDirectory(string aPath, bool recursive) { if (mVFS == null) { throw new Exception("VFSManager isn't ready."); } var xDirectory = mVFS.GetDirectory(aPath); var xDirectoryListing = mVFS.GetDirectoryListing(xDirectory); if (xDirectory.mEntryType != DirectoryEntryTypeEnum.Directory) { throw new IOException("The specified path isn't a directory"); } if (xDirectoryListing.Count > 0 && !recursive) { throw new IOException("Directory is not empty"); } if (recursive) { foreach (var entry in xDirectoryListing) { if (entry.mEntryType == DirectoryEntryTypeEnum.Directory) { DeleteDirectory(entry.mFullPath, true); } else if (entry.mEntryType == DirectoryEntryTypeEnum.File) { DeleteFile(entry.mFullPath); } else { throw new IOException("The directory contains a corrupted file"); } } } mVFS.DeleteDirectory(xDirectory); } /// <summary> /// Get directory. /// </summary> /// <param name="aPath">A path to the directory.</param> /// <returns>DirectoryEntry value.</returns> /// <exception cref="ArgumentException"> /// <list type="bullet"> /// <item>Thrown if aPath is null or empty.</item> /// <item>Root path is null or empty.</item> /// <item>Memory error.</item> /// <item>Fatal error.</item> /// </list> /// </exception> /// <exception cref="ArgumentNullException"> /// <list type="bullet"> /// <item>Thrown if VFSManager is null.</item> /// <item>Thrown if aPath is null.</item> /// <item>Root directory is null.</item> /// <item>Memory error.</item> /// </list> /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// <list type="bullet"> /// <item>Thrown when root directory address is smaller then root directory address.</item> /// <item>Memory error.</item> /// </list> /// </exception> /// <exception cref="OverflowException"> /// <list type="bullet"> /// <item>Thrown when aPath is too deep.</item> /// <item>Data lenght is greater then Int32.MaxValue.</item> /// </list> /// </exception> /// <exception cref="Exception"> /// <list type="bullet"> /// <item>Thrown when unable to determine filesystem for path: + aPath.</item> /// <item>data size invalid.</item> /// <item>invalid directory entry type.</item> /// <item>path not found.</item> /// </list> /// </exception> /// <exception cref="DecoderFallbackException">Thrown on memory error.</exception> public static DirectoryEntry GetDirectory(string aPath) { Global.mFileSystemDebugger.SendInternal("--- VFSManager.GetDirectory ---"); if (string.IsNullOrEmpty(aPath)) { throw new ArgumentNullException(nameof(aPath)); } Global.mFileSystemDebugger.SendInternal("aPath = " + aPath); return mVFS.GetDirectory(aPath); } /// <summary> /// Get directory listing. /// </summary> /// <param name="aPath">A path to the entry.</param> /// <returns>DirectoryEntry list value.</returns> /// <exception cref="ArgumentException"> /// <list type="bullet"> /// <item>Thrown if aPath is null or empty.</item> /// <item>Root path is null or empty.</item> /// <item>Memory error.</item> /// <item>Fatal error.</item> /// </list> /// </exception> /// <exception cref="ArgumentNullException"> /// <list type="bullet"> /// <item>Thrown if aPath is null or empty.</item> /// <item>Filesystem is null.</item> /// <item>Root directory is null.</item> /// <item>Memory error.</item> /// </list> /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// <list type="bullet"> /// <item>Thrown when root directory address is smaller then root directory address.</item> /// <item>Memory error.</item> /// </list> /// </exception> /// <exception cref="OverflowException"> /// <list type="bullet"> /// <item>Thrown when aPath is too deep.</item> /// <item>Data lenght is greater then Int32.MaxValue.</item> /// </list> /// </exception> /// <exception cref="Exception"> /// <list type="bullet"> /// <item>Thrown when unable to determine filesystem for path: + aPath.</item> /// <item>data size invalid.</item> /// <item>invalid directory entry type.</item> /// <item>path not found.</item> /// </list> /// </exception> /// <exception cref="DecoderFallbackException">Thrown on memory error.</exception> public static List<DirectoryEntry> GetDirectoryListing(string aPath) { Global.mFileSystemDebugger.SendInternal("--- VFSManager.GetDirectoryListing ---"); if (string.IsNullOrEmpty(aPath)) { throw new ArgumentNullException(nameof(aPath)); } Global.mFileSystemDebugger.SendInternal("aPath ="); Global.mFileSystemDebugger.SendInternal(aPath); return mVFS.GetDirectoryListing(aPath); } /// <summary> /// Get volume. /// </summary> /// <param name="aVolume">The volume root path.</param> /// <returns>A directory entry for the volume.</returns> /// <exception cref="ArgumentException">Thrown when aVolume is null or empty.</exception> /// <exception cref="Exception">Unable to determine filesystem for path: + aVolume</exception> /// <exception cref="ArgumentNullException">Thrown if aVolume / filesystem is null.</exception> /// <exception cref="ArgumentOutOfRangeException">Thrown when root directory address is smaller then root directory address.</exception> public static DirectoryEntry GetVolume(string aVolume) { Global.mFileSystemDebugger.SendInternal("--- VFSManager.GetVolume ---"); if (string.IsNullOrEmpty(aVolume)) { throw new ArgumentNullException(nameof(aVolume)); } Global.mFileSystemDebugger.SendInternal("aVolume ="); Global.mFileSystemDebugger.SendInternal(aVolume); return mVFS.GetVolume(aVolume); } /// <summary> /// Gets the volumes for all registered file systems. /// </summary> /// <returns>A list of directory entries for all volumes.</returns> /// <exception cref="ArgumentNullException">Thrown if filesystem is null.</exception> /// <exception cref="ArgumentOutOfRangeException">Thrown when root directory address is smaller then root directory address.</exception> /// <exception cref="ArgumentException">Thrown when root path is null or empty.</exception> public static List<DirectoryEntry> GetVolumes() { Global.mFileSystemDebugger.SendInternal("--- VFSManager.GetVolumes ---"); return mVFS.GetVolumes(); } /// <summary> /// Register file system. /// </summary> /// <param name="aFileSystemFactory">A file system to register.</param> public static void RegisterFileSystem(FileSystemFactory aFileSystemFactory) { mVFS.RegisterFileSystem(aFileSystemFactory); } /// <summary> /// Get logical drivers list. /// </summary> /// <returns>List of strings value.</returns> /// <exception cref="ArgumentNullException">Thrown if filesystem is null.</exception> /// <exception cref="ArgumentOutOfRangeException">Thrown when root directory address is smaller then root directory address.</exception> /// <exception cref="ArgumentException">Thrown when root path is null or empty.</exception> public static List<string> GetLogicalDrives() { Global.mFileSystemDebugger.SendInternal("--- VFSManager.GetLogicalDrives ---"); List<string> xDrives = new List<string>(); foreach (DirectoryEntry entry in GetVolumes()) xDrives.Add(entry.mName + Path.VolumeSeparatorChar + Path.DirectorySeparatorChar); return xDrives; } /// <summary> /// Check if file exists. /// </summary> /// <param name="aPath">A path to the file.</param> /// <returns>bool value.</returns> public static bool FileExists(string aPath) { Global.mFileSystemDebugger.SendInternal("-- VFSManager.FileExists --"); if (aPath == null) { return false; } Global.mFileSystemDebugger.SendInternal("aPath = " + aPath); string xPath = Path.GetFullPath(aPath); Global.mFileSystemDebugger.SendInternal("xPath = " + xPath); return GetFile(xPath) != null; } /// <summary> /// Check if file exists. /// </summary> /// <param name="aEntry">A entry of the file.</param> /// <returns>bool value.</returns> public static bool FileExists(DirectoryEntry aEntry) { Global.mFileSystemDebugger.SendInternal("--- VFSManager.FileExists ---"); if (aEntry == null) { return false; } try { Global.mFileSystemDebugger.SendInternal("aEntry.mName ="); Global.mFileSystemDebugger.SendInternal(aEntry.mName); string xPath = GetFullPath(aEntry); Global.mFileSystemDebugger.SendInternal("After GetFullPath"); Global.mFileSystemDebugger.SendInternal("xPath ="); Global.mFileSystemDebugger.SendInternal(xPath); return GetFile(xPath) != null; } catch { /* Simply map any Exception to false as this method should return only bool */ return false; } } /// <summary> /// Check if directory exists. /// </summary> /// <param name="aPath">A path to the directory.</param> /// <returns>bool value.</returns> /// <exception cref="ArgumentException">Thrown when aPath is null or empty.</exception> public static bool DirectoryExists(string aPath) { if (String.IsNullOrEmpty(aPath)) { throw new ArgumentException("Argument is null or empty", nameof(aPath)); } Global.mFileSystemDebugger.SendInternal("--- VFSManager.DirectoryExists ---"); Global.mFileSystemDebugger.SendInternal("aPath = " + aPath); try { string xPath = Path.GetFullPath(aPath); Global.mFileSystemDebugger.SendInternal("After GetFullPath"); Global.mFileSystemDebugger.SendInternal("xPath = " + xPath); var result = GetDirectory(xPath) != null; Global.mFileSystemDebugger.SendInternal("--- VFSManager.DirectoryExists --- Returns: " + result); return result; } catch { /* Simply map any Exception to false as this method should return only bool */ return false; } } /// <summary> /// Check if directory exists. /// </summary> /// <param name="aEntry">A entry of the directory.</param> /// <returns>bool value.</returns> /// <exception cref="ArgumentNullException">Thrown when aEntry is null.</exception> public static bool DirectoryExists(DirectoryEntry aEntry) { Global.mFileSystemDebugger.SendInternal("--- VFSManager.DirectoryExists ---"); if (aEntry == null) { throw new ArgumentNullException(nameof(aEntry)); } try { Global.mFileSystemDebugger.SendInternal("aEntry.mName ="); Global.mFileSystemDebugger.SendInternal(aEntry.mName); string xPath = GetFullPath(aEntry); Global.mFileSystemDebugger.SendInternal("After GetFullPath"); Global.mFileSystemDebugger.SendInternal("xPath ="); Global.mFileSystemDebugger.SendInternal(xPath); return GetDirectory(xPath) != null; } catch (Exception e) { global::System.Console.Write("Exception occurred: "); global::System.Console.WriteLine(e.Message); return false; } } /// <summary> /// Get full path to the entry. /// </summary> /// <param name="aEntry">A entry.</param> /// <returns>string value.</returns> /// <exception cref="ArgumentNullException">Thrown when aEntry is null.</exception> public static string GetFullPath(DirectoryEntry aEntry) { Global.mFileSystemDebugger.SendInternal("--- VFSManager.GetFullPath ---"); if (aEntry == null) { throw new ArgumentNullException(nameof(aEntry)); } Global.mFileSystemDebugger.SendInternal("aEntry.mName ="); Global.mFileSystemDebugger.SendInternal(aEntry.mName); var xParent = aEntry.mParent; string xPath = aEntry.mName; while (xParent != null) { xPath = xParent.mName + xPath; Global.mFileSystemDebugger.SendInternal("xPath ="); Global.mFileSystemDebugger.SendInternal(xPath); xParent = xParent.mParent; Global.mFileSystemDebugger.SendInternal("xParent.mName ="); Global.mFileSystemDebugger.SendInternal(xParent.mName); } Global.mFileSystemDebugger.SendInternal("xPath ="); Global.mFileSystemDebugger.SendInternal(xPath); return xPath; } /// <summary> /// Get file stream. /// </summary> /// <param name="aPathname">A path to the file.</param> /// <returns>Stream value.</returns> /// <exception cref="ArgumentException"> /// <list type="bullet"> /// <item>Thrown if aPathname is null / empty / invalid.</item> /// <item>Root path is null or empty.</item> /// <item>Memory error.</item> /// <item>Fatal error.</item> /// </list> /// </exception> /// <exception cref="ArgumentNullException"> /// <list type="bullet"> /// <item>Thrown if aPathname is null or empty.</item> /// <item>Filesystem is null.</item> /// <item>Root directory is null.</item> /// <item>Memory error.</item> /// </list> /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// <list type="bullet"> /// <item>Thrown when root directory address is smaller then root directory address.</item> /// <item>Memory error.</item> /// </list> /// </exception> /// <exception cref="OverflowException"> /// <list type="bullet"> /// <item>Thrown when aPathname is too deep.</item> /// <item>Data lenght is greater then Int32.MaxValue.</item> /// <item>The number of clusters in the FAT entry is greater than Int32.MaxValue.</item> /// </list> /// </exception> /// <exception cref="Exception"> /// <list type="bullet"> /// <item>Thrown when unable to determine filesystem for path: + aPathname.</item> /// <item>data size invalid.</item> /// <item>invalid directory entry type.</item> /// <item>path not found.</item> /// <item>FAT table not found.</item> /// <item>memory error.</item> /// </list> /// </exception> /// <exception cref="DecoderFallbackException">Thrown on memory error.</exception> public static Stream GetFileStream(string aPathname) { Global.mFileSystemDebugger.SendInternal("--- VFSManager.GetFileStream ---"); if (string.IsNullOrEmpty(aPathname)) { return null; } Global.mFileSystemDebugger.SendInternal("aPathName ="); Global.mFileSystemDebugger.SendInternal(aPathname); var xFileInfo = GetFile(aPathname); if (xFileInfo == null) { throw new Exception("File not found: " + aPathname); } return xFileInfo.GetFileStream(); } /// <summary> /// Get file attributes. /// </summary> /// <param name="aPath">A path to the file</param> /// <returns>FileAttributes value.</returns> /// <exception cref="ArgumentException"> /// <list type="bullet"> /// <item>Thrown if aPath is null or empty.</item> /// <item>Thrown when aFS root path is null or empty.</item> /// <item>Thrown on memory error.</item> /// <item>Fatal error.</item> /// </list> /// </exception> /// <exception cref="ArgumentNullException"> /// <list type="bullet"> /// <item>Thrown if VFSManager is null.</item> /// <item>Thrown when root directory is null.</item> /// <item>Thrown on memory error.</item> /// </list> /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// <list type="bullet"> /// <item>Thrown when root directory address is smaller then root directory address.</item> /// <item>Thrown on memory error.</item> /// </list> /// </exception> /// <exception cref="OverflowException"> /// <list type="bullet"> /// <item>Thrown when aPath is too deep.</item> /// <item>Thrown when data lenght is greater then Int32.MaxValue.</item> /// </list> /// </exception> /// <exception cref="Exception"> /// <list type="bullet"> /// <item>Thrown when data size invalid.</item> /// <item>Thrown on invalid directory entry type.</item> /// <item>Thrown when aPath entry not found.</item> /// <item>Thrown when unable to determine filesystem for path: + aPath.</item> /// <item>Thrown aPath is neither a file neither a directory.</item> /// </list> /// </exception> /// <exception cref="DecoderFallbackException">Thrown on memory error.</exception> public static FileAttributes GetFileAttributes(string aPath) { Global.mFileSystemDebugger.SendInternal("--- VFSManager.GetFileAttributes ---"); return mVFS.GetFileAttributes(aPath); } /// <summary> /// Sets the attributes for a File / Directory. /// Not implemented. /// </summary> /// <param name="aPath">The path of the File / Directory.</param> /// <param name="fileAttributes">The attributes of the File / Directory.</param> /// <exception cref="NotImplementedException">Thrown always</exception> public static void SetFileAttributes(string aPath, FileAttributes fileAttributes) { Global.mFileSystemDebugger.SendInternal("--- VFSManager.GetFileAttributes ---"); mVFS.SetFileAttributes(aPath, fileAttributes); } /// <summary> /// Check if drive id is valid. /// </summary> /// <param name="driveId">Drive id to check.</param> /// <returns>bool value.</returns> /// <exception cref="ArgumentOutOfRangeException">Thrown if aPath length is smaller then 2, or greater than Int32.MaxValue.</exception> public static bool IsValidDriveId(string aPath) { Global.mFileSystemDebugger.SendInternal("--- VFSManager.GetFileAttributes ---"); return mVFS.IsValidDriveId(aPath); } /// <summary> /// Get total size in bytes. /// </summary> /// <param name="aDriveId">A drive id to get the size of.</param> /// <returns>long value.</returns> /// <exception cref="ArgumentException">Thrown when aDriveId is null or empty.</exception> /// <exception cref="Exception">Unable to determine filesystem for path: + aDriveId</exception> public static long GetTotalSize(string aDriveId) { Global.mFileSystemDebugger.SendInternal("--- VFSManager.GetTotalSize ---"); return mVFS.GetTotalSize(aDriveId); } /// <summary> /// Get available free space. /// </summary> /// <param name="aDriveId">A drive id to get the size of.</param> /// <returns>long value.</returns> /// <exception cref="ArgumentException">Thrown when aDriveId is null or empty.</exception> /// <exception cref="Exception">Unable to determine filesystem for path: + aDriveId</exception> public static long GetAvailableFreeSpace(string aDriveId) { Global.mFileSystemDebugger.SendInternal("--- VFSManager.GetAvailableFreeSpace ---"); return mVFS.GetAvailableFreeSpace(aDriveId); } /// <summary> /// Get total free space. /// </summary> /// <param name="aDriveId">A drive id to get the size of.</param> /// <returns>long value.</returns> /// <exception cref="ArgumentException">Thrown when aDriveId is null or empty.</exception> /// <exception cref="Exception">Unable to determine filesystem for path: + aDriveId</exception> public static long GetTotalFreeSpace(string aDriveId) { Global.mFileSystemDebugger.SendInternal("--- VFSManager.GetTotalFreeSpace ---"); return mVFS.GetTotalFreeSpace(aDriveId); } /// <summary> /// Get file system type. /// </summary> /// <param name="aDriveId">A drive id.</param> /// <returns>string value.</returns> /// <exception cref="ArgumentException">Thrown when aDriveId is null or empty.</exception> /// <exception cref="Exception">Unable to determine filesystem for path: + aDriveId</exception> public static string GetFileSystemType(string aDriveId) { Global.mFileSystemDebugger.SendInternal("--- VFSManager.GetFileSystemType ---"); return mVFS.GetFileSystemType(aDriveId); } /// <summary> /// Get file system label. /// </summary> /// <param name="aDriveId">A drive id.</param> /// <returns>string value.</returns> /// <exception cref="ArgumentException">Thrown when aDriveId is null or empty.</exception> /// <exception cref="Exception">Unable to determine filesystem for path: + aDriveId</exception> public static string GetFileSystemLabel(string aDriveId) { Global.mFileSystemDebugger.SendInternal("--- VFSManager.GetFileSystemLabel ---"); return mVFS.GetFileSystemLabel(aDriveId); } /// <summary> /// Set file system type. /// </summary> /// <param name="aDriveId">A drive id.</param> /// <param name="aLabel">A label to be set.</param> /// <exception cref="ArgumentException">Thrown when aDriveId is null or empty.</exception> /// <exception cref="Exception">Unable to determine filesystem for path: + aDriveId</exception> public static void SetFileSystemLabel(string aDriveId, string aLabel) { Global.mFileSystemDebugger.SendInternal("--- VFSManager.SetFileSystemLabel ---"); mVFS.SetFileSystemLabel(aDriveId, aLabel); } /// <summary> /// Format partition. /// </summary> /// <param name="aDriveId">A drive id.</param> /// <param name="aDriveFormat">A drive format.</param> /// <param name="aQuick">Quick format.</param> /// <exception cref="ArgumentOutOfRangeException"> /// <list type = "bullet" > /// <item>Thrown when the data length is 0 or greater then Int32.MaxValue.</item> /// <item>Entrys matadata offset value is invalid.</item> /// <item>Fatal error (contact support).</item> /// </list> /// </exception> /// <exception cref="ArgumentNullException">Thrown when filesystem is null / memory error.</exception> /// <exception cref="ArgumentException"> /// <list type="bullet"> /// <item>Thrown when aDriveId is null or empty.</item> /// <item>Data length is 0.</item> /// <item>Root path is null or empty.</item> /// <item>Memory error.</item> /// </list> /// </exception> /// <exception cref="Exception"> /// <list type="bullet"> /// <item>Unable to determine filesystem for path: + aDriveId.</item> /// <item>Thrown when data size invalid.</item> /// <item>Thrown on unknown file system type.</item> /// <item>Thrown on fatal error (contact support).</item> /// </list> /// </exception> /// <exception cref="OverflowException">Thrown when data lenght is greater then Int32.MaxValue.</exception> /// <exception cref="DecoderFallbackException">Thrown on memory error.</exception> /// <exception cref="NotImplementedException">Thrown when FAT type is unknown.</exception> /// <exception cref="RankException">Thrown on fatal error (contact support).</exception> /// <exception cref="ArrayTypeMismatchException">Thrown on fatal error (contact support).</exception> /// <exception cref="InvalidCastException">Thrown when the data in aData is corrupted.</exception> /// <exception cref="NotSupportedException">Thrown when FAT type is unknown.</exception> public static void Format(string aDriveId, string aDriveFormat, bool aQuick) { Global.mFileSystemDebugger.SendInternal("--- VFSManager.Format ---"); mVFS.Format(aDriveId, aDriveFormat, aQuick); } #region Helpers /// <summary> /// Get alt. directory separator char. /// </summary> /// <returns>char value.</returns> public static char GetAltDirectorySeparatorChar() { return '/'; } /// <summary> /// Get directory separator char. /// </summary> /// <returns>char value.</returns> public static char GetDirectorySeparatorChar() { return '\\'; } /// <summary> /// Get invalid filename chars. /// </summary> /// <returns>char array value.</returns> public static char[] GetInvalidFileNameChars() { char[] xReturn = { '"', '<', '>', '|', '\0', '\a', '\b', '\t', '\n', '\v', '\f', '\r', ':', '*', '?', '\\', '/' }; return xReturn; } /// <summary> /// Get invalid path chars with additional checks. /// </summary> /// <returns>char array value.</returns> public static char[] GetInvalidPathCharsWithAdditionalChecks() { char[] xReturn = { '"', '<', '>', '|', '\0', '\a', '\b', '\t', '\n', '\v', '\f', '\r', '*', '?' }; return xReturn; } /// <summary> /// Get path separator char. /// </summary> /// <returns>char value.</returns> public static char GetPathSeparator() { return ';'; } /// <summary> /// Get real invalid path chars. /// </summary> /// <returns>char array value.</returns> public static char[] GetRealInvalidPathChars() { char[] xReturn = { '"', '<', '>', '|' }; return xReturn; } /// <summary> /// Get trim end chars. /// </summary> /// <returns>char array value.</returns> public static char[] GetTrimEndChars() { char[] xReturn = { (char) 0x9, (char) 0xA, (char) 0xB, (char) 0xC, (char) 0xD, (char) 0x20, (char) 0x85, (char) 0xA0 }; return xReturn; } /// <summary> /// Get volume separator char. /// </summary> /// <returns>char value.</returns> public static char GetVolumeSeparatorChar() { return ':'; } /// <summary> /// Get max path. /// </summary> /// <returns>int value.</returns> public static int GetMaxPath() { return 260; } //public static bool IsAbsolutePath(this string aPath) //{ // return ((aPath[0] == VFSBase.DirectorySeparatorChar) || (aPath[0] == VFSBase.AltDirectorySeparatorChar)); //} //public static bool IsRelativePath(this string aPath) //{ // return (aPath[0] != VFSBase.DirectorySeparatorChar || aPath[0] != VFSBase.AltDirectorySeparatorChar); //} /// <summary> /// Split path. /// </summary> /// <param name="aPath">A path to split.</param> /// <returns>string array.</returns> /// <exception cref="ArgumentException">Thrown on fatal error.</exception> public static string[] SplitPath(string aPath) { //TODO: This should call Path.GetDirectoryName() and then loop calling Directory.GetParent(), but those aren't implemented yet. return aPath.Split(GetDirectorySeparators(), StringSplitOptions.RemoveEmptyEntries); } /// <summary> /// Get directory separators. /// </summary> /// <returns>char array value.</returns> private static char[] GetDirectorySeparators() { return new[] { GetDirectorySeparatorChar(), GetAltDirectorySeparatorChar() }; } #endregion Helpers /// <summary> /// Gets the parent directory entry from the path. /// </summary> /// <param name="aPath">The full path to the current directory entry.</param> /// <returns>The parent directory entry.</returns> /// <exception cref="ArgumentException"> /// <list type="bullet"> /// <item>Thrown if aPath is null / empty / invalid.</item> /// <item>Root path is null or empty.</item> /// <item>Memory error.</item> /// <item>Fatal error.</item> /// </list> /// </exception> /// <exception cref="ArgumentNullException"> /// <list type="bullet"> /// <item>Thrown if VFSManager is null.</item> /// <item>Thrown if aPath is null.</item> /// <item>Root directory is null.</item> /// <item>Memory error.</item> /// </list> /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// <list type="bullet"> /// <item>Thrown when root directory address is smaller then root directory address.</item> /// <item>Memory error.</item> /// <item>Fatal error.</item> /// </list> /// </exception> /// <exception cref="OverflowException"> /// <list type="bullet"> /// <item>Thrown when aPath is too deep.</item> /// <item>Data lenght is greater then Int32.MaxValue.</item> /// </list> /// </exception> /// <exception cref="Exception"> /// <list type="bullet"> /// <item>Thrown when unable to determine filesystem for path: + aPath.</item> /// <item>data size invalid.</item> /// <item>invalid directory entry type.</item> /// <item>path not found.</item> /// </list> /// </exception> /// <exception cref="DecoderFallbackException">Thrown on memory error.</exception> public static DirectoryEntry GetParent(string aPath) { Global.mFileSystemDebugger.SendInternal("--- VFSManager.GetParent ---"); if (string.IsNullOrEmpty(aPath)) { throw new ArgumentException("Argument is null or empty", nameof(aPath)); } Global.mFileSystemDebugger.SendInternal("aPath ="); Global.mFileSystemDebugger.SendInternal(aPath); if (aPath == Path.GetPathRoot(aPath)) { return null; } string xFileOrDirectory = Path.HasExtension(aPath) ? Path.GetFileName(aPath) : Path.GetDirectoryName(aPath); if (xFileOrDirectory != null) { string xPath = aPath.Remove(aPath.Length - xFileOrDirectory.Length); return GetDirectory(xPath); } return null; } /// <summary> /// Cleans up manager if the VFS has to be reintialised. /// </summary> internal static void Reset() { mVFS = null; } } }
39.793103
189
0.554593
[ "BSD-3-Clause" ]
Project-Prism/Cosmos
source/Cosmos.System2/FileSystem/VFS/VFSManager.cs
46,162
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Text; namespace Aiursoft.Pylon.Models.OSS.ApiAddressModels { public class UploadFileAddressModel : CommonAddressModel { [Required] [Range(1, 18250)] public int AliveDays { get; set; } } }
22.133333
60
0.710843
[ "MIT" ]
hv0905/Nexus
Pylon/Models/OSS/ApiAddressModels/UploadFileAddressModel.cs
334
C#
using Moq; using SafeOrbit.Cryptography.Random; using SafeOrbit.Tests; namespace SafeOrbit.Fakes { /// <seealso cref="IFastRandom" /> public class FastRandomFaker : StubProviderBase<IFastRandom> { public override IFastRandom Provide() { var fake = new Mock<IFastRandom>(); fake.Setup(x => x.GetBytes(It.IsAny<int>())).Returns<int>(x => new byte[x]); return fake.Object; } } }
27.588235
89
0.592751
[ "MIT" ]
undergroundwires/SafeOrbit
src/tests/UnitTests/Internal/Fakes/FastRandomFaker.cs
471
C#
namespace NaGet.Protocol; public partial class NuGetClientFactory { private class AutocompleteClient : IAutocompleteClient { private readonly NuGetClientFactory clientfactory; public AutocompleteClient(NuGetClientFactory clientFactory) { clientfactory = clientFactory ?? throw new ArgumentNullException(nameof(clientFactory)); } public async Task<AutocompleteResponse?> AutocompleteAsync( string? query = null, int skip = 0, int take = 20, bool includePrerelease = true, bool includeSemVer2 = true, CancellationToken cancellationToken = default) { // TODO: Support search failover. // See: https://github.com/loic-sharma/NaGet/issues/314 var client = await clientfactory.GetAutocompleteClientAsync(cancellationToken); return await client.AutocompleteAsync(query, skip, take, includePrerelease, includeSemVer2, cancellationToken); } public async Task<AutocompleteResponse?> ListPackageVersionsAsync( string packageId, bool includePrerelease = true, bool includeSemVer2 = true, CancellationToken cancellationToken = default) { // TODO: Support search failover. // See: https://github.com/loic-sharma/NaGet/issues/314 var client = await clientfactory.GetAutocompleteClientAsync(cancellationToken); return await client.ListPackageVersionsAsync(packageId, includePrerelease, includeSemVer2, cancellationToken); } } }
39.902439
123
0.660758
[ "MIT" ]
SeppPenner/NaGet
src/NaGet.Protocol/Search/AutocompleteClient.cs
1,636
C#
using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Text; using Jannesen.FileFormat.Pdf.Internal; namespace Jannesen.FileFormat.Pdf { public sealed class PdfContent: PdfObject, IDisposable { private static readonly byte[] bs_b = Encoding.ASCII.GetBytes("b\n"); private static readonly byte[] bs_B = Encoding.ASCII.GetBytes("B\n"); private static readonly byte[] bs_CS = Encoding.ASCII.GetBytes("CS\n"); private static readonly byte[] bs_cs = Encoding.ASCII.GetBytes("cs\n"); private static readonly byte[] bs_d = Encoding.ASCII.GetBytes("d\n"); private static readonly byte[] bs_l = Encoding.ASCII.GetBytes("l\n"); private static readonly byte[] bs_BT = Encoding.ASCII.GetBytes("BT\n"); private static readonly byte[] bs_ET = Encoding.ASCII.GetBytes("ET\n"); private static readonly byte[] bs_f = Encoding.ASCII.GetBytes("f\n"); private static readonly byte[] bs_h = Encoding.ASCII.GetBytes("h\n"); private static readonly byte[] bs_J = Encoding.ASCII.GetBytes("J\n"); private static readonly byte[] bs_j = Encoding.ASCII.GetBytes("j\n"); private static readonly byte[] bs_m = Encoding.ASCII.GetBytes("m\n"); private static readonly byte[] bs_M = Encoding.ASCII.GetBytes("M\n"); private static readonly byte[] bs_Tf = Encoding.ASCII.GetBytes("Tf\n"); private static readonly byte[] bs_Tj = Encoding.ASCII.GetBytes("Tj\n"); private static readonly byte[] bs_Tm_POS_H = Encoding.ASCII.GetBytes("1 0 0 1 "); private static readonly byte[] bs_Tm_POS_V = Encoding.ASCII.GetBytes("0 1 -1 0 "); private static readonly byte[] bs_Tm = Encoding.ASCII.GetBytes("Tm\n"); private static readonly byte[] bs_re = Encoding.ASCII.GetBytes("re\n"); private static readonly byte[] bs_s = Encoding.ASCII.GetBytes("s\n"); private static readonly byte[] bs_S = Encoding.ASCII.GetBytes("S\n"); private static readonly byte[] bs_SC = Encoding.ASCII.GetBytes("SC\n"); private static readonly byte[] bs_sc = Encoding.ASCII.GetBytes("sc\n"); private static readonly byte[] bs_w = Encoding.ASCII.GetBytes("w\n"); private static readonly byte[] bs_q = Encoding.ASCII.GetBytes("q\n"); private static readonly byte[] bs_Q = Encoding.ASCII.GetBytes("Q\n"); private static readonly byte[] bs_cm = Encoding.ASCII.GetBytes("cm\n"); private static readonly byte[] bs_Do = Encoding.ASCII.GetBytes("Do\n"); private static readonly byte[] bs_0 = Encoding.ASCII.GetBytes("0"); private static readonly byte[] bs_0S = Encoding.ASCII.GetBytes("0 "); private PdfContent _parent; private bool _locked; private StreamBuffer _dataStream; private PdfResourceEntryList _resources; private string _curStrokeColorSpace; private string _curNonStrokeColorSpace; private PdfColor _curStrokeColor; private PdfColor _curNonStrokeColor; private PdfDistance _curLineWidth; private PdfLineCapStyle _curLineCap; private PdfLineJoinStyle _curLineJoin; private double _curMiterLimit; private PdfDistance[] _curDashArray; private PdfDistance _curDashPhase; private bool _textMode; private PdfFont _curFont; private PdfDistance _curFontSize; public override bool hasStream { get => true; } public PdfContent Parent { get { return _parent; } } public PdfResourceEntryList Resources { get { return _resources; } } public string PostScript { get { return ASCIIEncoding.Default.GetString(_dataStream.ToArray()); } set { _dataStream = new StreamBuffer(); _curStrokeColorSpace = null; _curNonStrokeColorSpace = null; _curStrokeColor = null; _curNonStrokeColor = null; _curLineWidth = new PdfDistance(-1); _curLineCap = PdfLineCapStyle.Unknown; _curLineJoin = PdfLineJoinStyle.Unknown; _curMiterLimit = -1; _curDashArray = null; _curDashPhase = new PdfDistance(-1); var bytes = ASCIIEncoding.Default.GetBytes(value); _dataStream.Write(bytes, 0, bytes.Length); } } public PdfContent() { _init(); } public PdfContent(PdfContent parent) { _parent = parent; _init(); if (parent != null) { for (int i = 0 ; i < parent._resources.Count ; ++i) _resources.Add(parent._resources[i]); } } public PdfContent(PdfDictionary dictonary) { if (dictonary is null) throw new ArgumentNullException(nameof(dictonary)); if (dictonary.NamedType != PdfObject.ntPage) throw new PdfException("Object is not a page or content."); try { _init(); _readPageResources(dictonary); _readPageContent(dictonary); } catch(Exception err) { throw new PdfException("Construct content from ReaderPage failed.", err); } } private PdfContent(PdfContent parent, PdfObjectReader obj) { _parent = parent; _init(); _readContent(obj); } public void Dispose() { if (_dataStream != null) { _dataStream.Dispose(); _dataStream = null; } } public void TextBox(PdfPoint upperLeftCorner, PdfStyleText style, PdfTextAlign align, PdfDistance width, int maxLines, string text) { if (!string.IsNullOrEmpty(text)) { Formatter.TextBox TextBox = new Formatter.TextBox(style, align, width, maxLines, text); TextBox.Print(upperLeftCorner, this); } } public void DrawLine(PdfStyleLine lineStyle, PdfPoint begin, PdfSize size) { if (_textMode) opEndText(); SetLineStyle(lineStyle); opMoveTo(begin); opLineTo(begin + size); opStroke(); } public void DrawRectangle(PdfStyleLine lineStyle, PdfStyleFill fillStyle, PdfPoint begin, PdfSize size) { if (_textMode) opEndText(); if (lineStyle != null) SetLineStyle(lineStyle); if (fillStyle != null) SetFillStyle(fillStyle); opRectangle(begin, size); if (lineStyle != null & fillStyle != null) opFillStroke(); else if (lineStyle != null) opStroke(); else if (fillStyle != null) opFill(); } public void Draw(PdfStyleLine lineStyle, PdfStyleFill fillStyle, PdfPoint begin, PdfSize[] sizes, bool closePath) { if (_textMode) opEndText(); if (lineStyle != null) SetLineStyle(lineStyle); if (fillStyle != null) SetFillStyle(fillStyle); opMoveTo(begin); if (sizes != null) { PdfPoint Pos = begin; for (int i = 0 ; i < sizes.Length ; ++i) { Pos += sizes[i]; opLineTo(Pos); } } if (closePath) { if (lineStyle != null & fillStyle != null) opCloseFillStroke(); else if (lineStyle != null) opCloseStroke(); else if (fillStyle != null) { opClosePath(); opFill(); } } else { if (fillStyle != null) throw new PdfException("Can't fill a non closed path."); opStroke(); } } public void Text(PdfStyleText textStyle, PdfPoint point, PdfTextAlign align, string txt) { if (textStyle is null) throw new ArgumentNullException(nameof(textStyle)); if (!string.IsNullOrEmpty(txt)) { SetTextStyle(textStyle); if (align != PdfTextAlign.Left) { PdfDistance Width = textStyle.Font.TextWidth(textStyle.FontSize, txt); switch(align) { case PdfTextAlign.Right: point.x -= Width; break; case PdfTextAlign.Center: point.x -= Width / 2; break; } } SetTextMatrixH(point); opShowText(txt, 0, txt.Length); } } public void Text(PdfStyleText textStyle, PdfPoint point, PdfTextAlign align, double rotation, string txt) { if (textStyle is null) throw new ArgumentNullException(nameof(textStyle)); if (!string.IsNullOrEmpty(txt)) { SetTextStyle(textStyle); rotation *= Math.PI/180.0; double Rotation_Sin = Math.Round(Math.Sin(rotation), 5); double Rotation_Cos = Math.Round(Math.Cos(rotation), 5); if (align != PdfTextAlign.Left) { PdfDistance Width = textStyle.Font.TextWidth(textStyle.FontSize, txt); if (align == PdfTextAlign.Center) Width = Width / 2.0; point.x -= Width * Rotation_Cos; point.y -= Width * Rotation_Sin; } SetTextMatrix(point, Rotation_Sin, Rotation_Cos); opShowText(txt, 0, txt.Length); } } public void Image(PdfPoint point, PdfSize size, PdfImage image) { if (image is null) throw new ArgumentNullException(nameof(image)); if (_textMode) opEndText(); opSaveGraphicsState(); opCurrentTransformationMatrix(1,0,0,1,point.y.pnts,point.x.pnts); opCurrentTransformationMatrix(size.height.pnts,0,0,size.width.pnts,0,0); WriteResourceName(image); WriteStr(bs_Do); opRestoreGraphicsState(); } public void SetLineStyle(PdfStyleLine style) { if (style is null) throw new ArgumentNullException(nameof(style)); if (style.LineColor != _curStrokeColor) { if (style.LineColor.ColorSpace != _curStrokeColorSpace) opSetStrokeColorSpace(style.LineColor.ColorSpace); opSetStrokeColor(style.LineColor); } if (style.LineWidth != _curLineWidth) opSetLineWidth(style.LineWidth); if (style.CapStyle != _curLineCap) opSetLineCap(style.CapStyle); if (style.JoinStyle != _curLineJoin) opSetLineJoin(style.JoinStyle); if (style.MiterLimit != _curMiterLimit) opSetMiterLimit(style.MiterLimit); if (style.DashArray != _curDashArray || style.DashPhase != _curDashPhase) opSetDash(style.DashArray, style.DashPhase); } public void SetFillStyle(PdfStyleFill style) { if (style is null) throw new ArgumentNullException(nameof(style)); if (style.FillColor != _curNonStrokeColor) { if (style.FillColor.ColorSpace != _curNonStrokeColorSpace) opSetNonStrokeColorSpace(style.FillColor.ColorSpace); opSetNonStrokeColor(style.FillColor); } } public void SetTextStyle(PdfStyleText style) { if (style is null) throw new ArgumentNullException(nameof(style)); if (style.TextColor != _curNonStrokeColor) { if (style.TextColor.ColorSpace != _curNonStrokeColorSpace) opSetNonStrokeColorSpace(style.TextColor.ColorSpace); opSetNonStrokeColor(style.TextColor); } if (style.Font != _curFont || style.FontSize != _curFontSize) opSelectFont(style.Font, style.FontSize); } public void SetTextMatrixH(PdfPoint point) { if (!_textMode) opBeginText(); WriteStr(bs_Tm_POS_H); WriteNumber(point.x.pnts, 2, true); WriteNumber(point.y.pnts, 2, true); WriteStr(bs_Tm); } public void SetTextMatrix(PdfPoint point, double rotation_Sin, double rotation_Cos) { if (!_textMode) opBeginText(); if (rotation_Sin == 0.0 && rotation_Cos == 1.0) { WriteStr(bs_Tm_POS_H); } else if (rotation_Sin == 1.0 && rotation_Cos == 0.0) { WriteStr(bs_Tm_POS_V); } else { WriteNumber( rotation_Cos, 6, true); WriteNumber( rotation_Sin, 6, true); WriteNumber(-rotation_Sin, 6, true); WriteNumber( rotation_Cos, 6, true); } WriteNumber(point.x.pnts, 2, true); WriteNumber(point.y.pnts, 2, true); WriteStr(bs_Tm); } public void opSetStrokeColorSpace(string name) { if (name is null) throw new ArgumentNullException(nameof(name)); WriteByte((byte)'/'); WriteStr(name); WriteByte((byte)' '); WriteStr(bs_CS); _curStrokeColorSpace = name; } public void opSetNonStrokeColorSpace(string name) { if (name is null) throw new ArgumentNullException(nameof(name)); WriteByte((byte)'/'); WriteStr(name); WriteByte((byte)' '); WriteStr(bs_cs); _curNonStrokeColorSpace = name; } public void opSetStrokeColor(PdfColor color) { if (color is PdfColorRGB rgb) { WriteNumber(rgb.Red, 4, true); WriteNumber(rgb.Green, 4, true); WriteNumber(rgb.Blue, 4, true); } else if (color is PdfColorCMYK cmyk) { WriteNumber(cmyk.Cyan, 4, true); WriteNumber(cmyk.Magenta, 4, true); WriteNumber(cmyk.Yellow, 4, true); WriteNumber(cmyk.Black, 4, true); } WriteStr(bs_SC); _curStrokeColor = color; } public void opSetNonStrokeColor(PdfColor color) { if (color is PdfColorRGB rgb) { if (_curNonStrokeColorSpace != "DeviceRGB") throw new PdfException("Can't set RGB Color, Invalid device colorspace "+_curStrokeColorSpace+" selected."); WriteNumber(rgb.Red, 4, true); WriteNumber(rgb.Green, 4, true); WriteNumber(rgb.Blue, 4, true); } else if (color is PdfColorCMYK cmyk) { if (_curNonStrokeColorSpace != "DeviceCMYK") throw new PdfException("Can't set CMYK Color, Invalid device colorspace "+_curStrokeColorSpace+" selected."); WriteNumber(cmyk.Cyan, 4, true); WriteNumber(cmyk.Magenta, 4, true); WriteNumber(cmyk.Yellow, 4, true); WriteNumber(cmyk.Black, 4, true); } WriteStr(bs_sc); _curNonStrokeColor = color; } public void opBeginText() { WriteStr(bs_BT); _textMode = true; } public void opSelectFont(PdfFont font, PdfDistance size) { if (font is null) throw new ArgumentNullException(nameof(font)); WriteResourceName(font); WriteNumber(size.pnts, 2, true); WriteStr(bs_Tf); _curFont = font; _curFontSize = size; } public void opShowText(string text, int start, int length) { if (text is null) throw new ArgumentNullException(nameof(text)); WriteString(text, start, length); WriteStr(bs_Tj); } public void opEndText() { WriteStr(bs_ET); _textMode = false; } public void opSetLineWidth(PdfDistance width) { WriteNumber(width.pnts, 2, true); WriteStr(bs_w); _curLineWidth = width; } public void opSetLineCap(PdfLineCapStyle style) { WriteInteger((int)style, true); WriteStr(bs_J); _curLineCap = style; } public void opSetLineJoin(PdfLineJoinStyle style) { WriteInteger((int)style, true); WriteStr(bs_j); _curLineJoin = style; } public void opSetMiterLimit(double miterLimit) { WriteNumber(miterLimit, 2, true); WriteStr(bs_M); _curMiterLimit = miterLimit; } public void opSetDash(PdfDistance[] dashArray, PdfDistance dashPhase) { WriteByte((byte)'['); if (dashArray != null) { for(int i = 0 ; i < dashArray.Length ; ++i) { WriteNumber(dashArray[i].pnts, 2, i < dashArray.Length - 1); } } WriteByte((byte)']'); WriteByte((byte)' '); WriteNumber(dashPhase.pnts, 2, true); WriteStr(bs_d); _curDashArray = dashArray; _curDashPhase = dashPhase; } public void opMoveTo(PdfPoint point) { WriteNumber(point.x.pnts, 2, true); WriteNumber(point.y.pnts, 2, true); WriteStr(bs_m); } public void opLineTo(PdfPoint point) { WriteNumber(point.x.pnts, 2, true); WriteNumber(point.y.pnts, 2, true); WriteStr(bs_l); } public void opRectangle(PdfPoint point, PdfSize size) { WriteNumber(point.x.pnts, 2, true); WriteNumber(point.y.pnts, 2, true); WriteNumber(size.width.pnts, 2, true); WriteNumber(size.height.pnts, 2, true); WriteStr(bs_re); } public void opClosePath() { WriteStr(bs_h); } public void opStroke() { WriteStr(bs_S); } public void opFill() { WriteStr(bs_f); } public void opFillStroke() { WriteStr(bs_B); } public void opCloseStroke() { WriteStr(bs_s); } public void opCloseFillStroke() { WriteStr(bs_b); } public void opSaveGraphicsState() { WriteStr(bs_q); } public void opRestoreGraphicsState() { WriteStr(bs_Q); } public void opCurrentTransformationMatrix(double a, double b, double c, double d, double e, double f) { WriteNumber(a, 4, true); WriteNumber(b, 4, true); WriteNumber(c, 4, true); WriteNumber(d, 4, true); WriteNumber(e, 4, true); WriteNumber(f, 4, true); WriteStr(bs_cm); } public void WriteResourceName(PdfObject resource) { if (resource is null) throw new ArgumentNullException(nameof(resource)); WriteByte((byte)'/'); WriteStr(_resources.GetName(resource)); WriteByte((byte)' '); } public void WriteInteger(int value, bool trailingSpace) { bool sign = false; byte[] buf = new byte[16]; int pos = buf.Length; if (value < 0) { sign = true; value = -value; } if (trailingSpace) buf[--pos] = (byte)' '; if (value == 0) { buf[--pos] = (byte)'0'; } else { while (value > 0) { buf[--pos] = (byte)('0' + (value % 10)); value /= 10; } if (sign) buf[--pos] = (byte)'-'; } if (_locked) throw new PdfExceptionWriter("Not allowed to change the content after it is added to a document."); _dataStream.Write(buf, pos, buf.Length - pos); } public void WriteNumber(double number, int precision, bool trailingSpace) { if (number != 0.0) { bool sign = false; byte[] buf = new byte[16]; int pos = buf.Length; bool f = false; if (number < 0) { sign = true; number = -number; } switch(precision) { case 0: case 1: number *= 10.0; break; case 2: number *= 100.0; break; case 3: number *= 1000.0; break; case 4: number *= 10000.0; break; case 5: number *= 100000.0; break; case 6: number *= 1000000.0; break; default: throw new ArgumentException("Precision out of range"); } Int64 Value = (Int64)(number + 0.5); if (trailingSpace) buf[--pos] = (byte)' '; if (Value == 0) { buf[--pos] = (byte)'0'; } else { ++precision; while (Value > 0 || precision > 0) { if (precision > 0) { if (--precision == 0) { if (f) buf[--pos] = (byte)'.'; f = true; } } if (f || (Value % 10) != 0) { buf[--pos] = (byte)('0' + (Value % 10)); f = true; } Value /= 10; } if (sign) buf[--pos] = (byte)'-'; } if (_locked) throw new PdfExceptionWriter("Not allowed to change the content after it is added to a document."); _dataStream.Write(buf, pos, buf.Length - pos); } else WriteStr(trailingSpace ? bs_0S : bs_0); } public void WriteString(string value, int start, int length) { if (value is null) throw new ArgumentNullException(nameof(value)); if (_locked) throw new PdfExceptionWriter("Not allowed to change the content after it is added to a document."); _dataStream.WriteByte((byte)'('); for (int i = 0 ; i < length ; ++i) { byte chr = PdfFont.Encode(value[start++]); if (chr == '(' || chr==')' || chr=='\\') _dataStream.WriteByte((byte)'\\'); _dataStream.WriteByte(chr); } _dataStream.WriteByte((byte)')'); _dataStream.WriteByte((byte)' '); } public void WriteStr(string data) { if (data is null) throw new ArgumentNullException(nameof(data)); WriteStr(Encoding.ASCII.GetBytes(data)); } public void WriteStr(byte[] byteStr) { if (byteStr is null) throw new ArgumentNullException(nameof(byteStr)); if (_locked) throw new PdfExceptionWriter("Not allowed to change the content after it is added to a document."); _dataStream.Write(byteStr, 0, byteStr.Length); } public void WriteByte(byte b) { if (_locked) throw new PdfExceptionWriter("Not allowed to change the content after it is added to a document."); _dataStream.WriteByte(b); } public string GetResourceName(PdfObject resource) { if (resource is null) throw new ArgumentNullException(nameof(resource)); return _resources.GetName(resource); } internal override void pdfAddToDocument(PdfDocumentWriter writer) { if (_textMode) opEndText(); _locked = true; if (Parent != null) writer.AddObj(Parent); for(int i = 0 ; i<_resources.Count ; ++i) { if (_resources[i].Resource is PdfObject obj) writer.AddObj(obj); } } internal override void pdfWriteToDocument(PdfDocumentWriter document, PdfStreamWriter writer) { if (document.CompressContent) { using (var compressStream = new StreamBuffer()) { string Filter = "FlateDecode"; using (Stream CompressWriter = PdfFilter.GetCompressor(Filter, compressStream)) CompressWriter.Write(_dataStream.GetBuffer(), 0, (int)_dataStream.Length); _writeContent(writer, Filter, compressStream); } } else _writeContent(writer, null, _dataStream); } private void _writeContent(PdfStreamWriter writer, string filter, StreamBuffer buffer) { writer.WriteDictionaryBegin(); if (filter != null) { writer.WriteName("Filter"); writer.WriteName(filter); } writer.WriteName("Length"); writer.WriteInteger((int)buffer.Length); writer.WriteDictionaryEnd(); writer.WriteStream(buffer.GetBuffer(), (int)buffer.Length); _dataStream.Dispose(); _dataStream = null; // Release datastream for less memory usage } private void _init() { _resources = new PdfResourceEntryList(); _dataStream = new StreamBuffer(); _curStrokeColorSpace = null; _curNonStrokeColorSpace = null; _curStrokeColor = null; _curNonStrokeColor = null; _curLineWidth = new PdfDistance(-1); _curLineCap = PdfLineCapStyle.Unknown; _curLineJoin = PdfLineJoinStyle.Unknown; _curMiterLimit = -1; _curDashArray = null; _curDashPhase = new PdfDistance(-1); } private void _readContent(PdfObjectReader obj) { byte[] buf = new byte[4096]; using (Stream Source = obj.GetUncompressStream()) { int rsize; while ((rsize = Source.Read(buf, 0, buf.Length)) > 0) _dataStream.Write(buf, 0, rsize); } } private void _readPageResources(PdfDictionary page) { PdfValueList resources = page.ValueByName<PdfDictionary>("Resources", mandatory:false)?.Children; if (resources != null) { for (int resourceIdx = 0 ; resourceIdx < resources.Count ; ++resourceIdx) { if (resources[resourceIdx] is PdfName) { string cls = resources[resourceIdx].Cast<PdfName>().Value; try { if (++resourceIdx >= resources.Count) throw new PdfException("Resource dictionary corrupt."); switch(cls) { #if DEBUG_TEST case "ProcSet": System.Diagnostics.Debug.WriteLine("Resourse " + cls); break; case "Properties": { var resourceItems = resources[resourceIdx].Resolve<PdfDictionary>(); if ((resourceItems.Children.Count % 2) != 0) throw new PdfException("Resource dictionary corrupt."); for (int ItemIdx = 0 ; ItemIdx < resourceItems.Children.Count - 1 ; ItemIdx += 2) System.Diagnostics.Debug.WriteLine("Resourse " + cls + " " + resourceItems.Children[ItemIdx ].Cast<PdfName>().Value + " removed."); ++resourceIdx; } break; #else case "ProcSet": case "Properties": ++resourceIdx; break; #endif case "Font": case "XObject": case "ExtGState": case "ColorSpace": { var resourceItems = resources[resourceIdx].Resolve<PdfDictionary>(); if ((resourceItems.Children.Count % 2) != 0) throw new PdfException("Resource dictionary corrupt."); for (int ItemIdx = 0 ; ItemIdx < resourceItems.Children.Count - 1 ; ItemIdx += 2) { var value = resourceItems.Children[ItemIdx + 1]; if (cls == "Font") { var fontDic = value.Resolve<PdfDictionary>(); if (new PdfName("Type") .Equals(fontDic.Children[0]) && new PdfName("Font") .Equals(fontDic.Children[1]) && new PdfName("Subtype") .Equals(fontDic.Children[2]) && new PdfName("Type1") .Equals(fontDic.Children[3]) && new PdfName("BaseFont") .Equals(fontDic.Children[4]) && new PdfName("Encoding") .Equals(fontDic.Children[6]) && new PdfName("WinAnsiEncoding").Equals(fontDic.Children[7])) { var stdFont = PdfStandard.Standard.FindStandardFontByName(fontDic.Children[5].Cast<PdfName>().Value); if (stdFont != null) value = stdFont; } } _resources.Add(cls, resourceItems.Children[ItemIdx ].Cast<PdfName>().Value, value); } } break; } } catch(Exception err) { throw new PdfException("Processing resource '" + cls + "' failed.", err); } } } } } private void _readPageContent(PdfDictionary page) { var contents = page.ValueByName("Contents"); if (contents is PdfArray pdfArray) { var contentsArray = pdfArray.Children; PdfContent Parent = null; for (int i = 0 ; i < contentsArray.Count - 1 ; ++i) { if (!(contentsArray[i] is PdfReferenceReader)) throw new PdfException("Invalid content referecen."); Parent = new PdfContent(Parent, ((PdfReferenceReader)contentsArray[i]).Object); } if (!(contentsArray[contentsArray.Count - 1] is PdfReferenceReader)) throw new PdfException("Invalid content referecen."); _parent = Parent; _readContent(((PdfReferenceReader)contentsArray[contentsArray.Count - 1]).Object); } else if (contents is PdfReferenceReader pdfRR) { _readContent(pdfRR.Object); } else throw new PdfExceptionReader("Unknown Content " + contents.GetType().Name); } } }
42.524972
187
0.429779
[ "Apache-2.0" ]
jannesen/Jannesen.FileFormat.Pdf
Object/PdfContent.cs
38,317
C#
//////////////////////////////////////////////////////////////////////////////// //NUnit tests for "EF Core Provider for LCPI OLE DB" // IBProvider and Contributors. 05.04.2021. namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D3.Query.Operators.SET_002__AS_STR.Multiply.Complete.Int32.Int64{ //////////////////////////////////////////////////////////////////////////////// //class MasterValues static class MasterValues { public const string c_Result__min_min ="BLA-BLA-BLA"; public const string c_Result__max_max ="BLA-BLA-BLA"; public const string c_Result__min_max ="BLA-BLA-BLA"; public const string c_Result__max_min ="BLA-BLA-BLA"; };//class MasterValues //////////////////////////////////////////////////////////////////////////////// }//namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D3.Query.Operators.SET_002__AS_STR.Multiply.Complete.Int32.Int64
36.692308
135
0.562893
[ "MIT" ]
ibprovider/Lcpi.EFCore.LcpiOleDb
Tests/General/Source/Work/DBMS/Firebird/V03_0_0/D3/Query/Operators/SET_002__AS_STR/Multiply/Complete/Int32/Int64/MasterValues.cs
956
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework; using YogUILibrary.Managers; namespace YogUILibrary.Structs { public class NinePatch { public int leftMostPatch; public int rightMostPatch; public int topMostPatch; public int bottomMostPatch; public int leftWidth { get { return leftMostPatch - 1; } } public int rightWidth { get { if (texture != null) return texture.Width - (rightMostPatch + 1); return 0; } } public int topHeight { get { return topMostPatch - 1; } } public int bottomHeight { get { if (texture != null) return texture.Height - (bottomMostPatch + 1); return 0; } } public Texture2D texture; public NinePatch() { leftMostPatch = -1; rightMostPatch = -1; topMostPatch = -1; bottomMostPatch = -1; texture = null; } public static bool isAlreadyNinepatch(Texture2D texture) { Microsoft.Xna.Framework.Color[] data = new Microsoft.Xna.Framework.Color[texture.Width * texture.Height]; texture.GetData(data); for (int i = 0; i < texture.Width; i++) { Color curPixel = data[i]; int a = curPixel.A; int r = curPixel.R; int g = curPixel.G; int b = curPixel.B; if (a != 0 && (r != 0 || g != 0 || b != 0)) { //Is not black and is not transparent. return false; } } for (int i = data.Length - (texture.Width + 1); i < data.Length; i++) { Color curPixel = data[i]; int a = curPixel.A; int r = curPixel.R; int g = curPixel.G; int b = curPixel.B; if (a != 0 && (r != 0 || g != 0 || b != 0)) { //Is not black and is not transparent. return false; } } for (int i = 0; i < data.Length; i += texture.Width) { Color curPixel = data[i]; int a = curPixel.A; int r = curPixel.R; int g = curPixel.G; int b = curPixel.B; if (a != 0 && (r != 0 || g != 0 || b != 0)) { //Is not black and is not transparent. return false; } } for (int i = texture.Width - 1; i < data.Length; i += texture.Width) { Color curPixel = data[i]; int a = curPixel.A; int r = curPixel.R; int g = curPixel.G; int b = curPixel.B; if (a != 0 && (r != 0 || g != 0 || b != 0)) { //Is not black and is not transparent. return false; } } return true; } public void LoadFromTexture(Texture2D texture) { leftMostPatch = -1; rightMostPatch = -1; topMostPatch = -1; bottomMostPatch = -1; this.texture = texture; Microsoft.Xna.Framework.Color[] data = new Microsoft.Xna.Framework.Color[texture.Width * texture.Height]; texture.GetData(data); for (int i = 0; i < texture.Width; i++) { Color curPixel = data[i]; if (curPixel.A != 0) { if (leftMostPatch == -1) leftMostPatch = i; } if (curPixel.A != 0 && leftMostPatch != -1) { rightMostPatch = i; } if (curPixel.A == 0 && leftMostPatch != -1 && rightMostPatch != -1) break; } for (int i = 0; i < data.Length; i += texture.Width) { Color curPixel = data[i]; if (curPixel.A != 0) { if (topMostPatch == -1) topMostPatch = i / texture.Width; } if (curPixel.A != 0 && topMostPatch != -1) { bottomMostPatch = (i / texture.Width); } if (curPixel.A == 0 && topMostPatch != -1 && bottomMostPatch != -1) break; } } public void Draw(SpriteBatch sb, Vector2 position, int contentWidth, int contentHeight) { Rectangle topLeft = new Rectangle(1, 1, leftMostPatch - 1, topMostPatch - 1); Rectangle topMiddle = new Rectangle(leftMostPatch, 1, (rightMostPatch - leftMostPatch), topMostPatch - 1); Rectangle topRight = new Rectangle(rightMostPatch + 1, 1, (texture.Width - 1) - rightMostPatch, topMostPatch - 1); Rectangle Left = new Rectangle(1, topMostPatch, leftMostPatch - 1, (bottomMostPatch - topMostPatch)); Rectangle Middle = new Rectangle(leftMostPatch, topMostPatch, (rightMostPatch - leftMostPatch), (bottomMostPatch - topMostPatch)); Rectangle Right = new Rectangle(rightMostPatch + 1, topMostPatch, (texture.Width - 1) - rightMostPatch, (bottomMostPatch - topMostPatch)); Rectangle bottomLeft = new Rectangle(1, bottomMostPatch, leftMostPatch - 1, (texture.Height - 1) - bottomMostPatch); Rectangle bottomMiddle = new Rectangle(leftMostPatch, bottomMostPatch, (rightMostPatch - leftMostPatch), (texture.Height - 1) - bottomMostPatch); Rectangle bottomRight = new Rectangle(rightMostPatch + 1, bottomMostPatch, (texture.Width - 1) - rightMostPatch, (texture.Height - 1) - bottomMostPatch); int topMiddleWidth = topMiddle.Width; int leftMiddleHeight = Left.Height; float scaleMiddleByHorizontally = ((float)contentWidth / (float)topMiddleWidth); float scaleMiddleByVertically = ((float)contentHeight / (float)leftMiddleHeight); // if (scaleMiddleByVertically < 1) scaleMiddleByVertically = 1; // if (scaleMiddleByHorizontally < 1) scaleMiddleByHorizontally = 1; Vector2 drawTL = position; Vector2 drawT = drawTL + new Vector2(topLeft.Width, 0); Vector2 drawTR = drawT + new Vector2(topMiddle.Width * scaleMiddleByHorizontally, 0); Vector2 drawL = drawTL + new Vector2(0, topLeft.Height); Vector2 drawM = drawT + new Vector2(0, topMiddle.Height); Vector2 drawR = drawTR + new Vector2(0, topRight.Height); Vector2 drawBL = drawL + new Vector2(0, leftMiddleHeight * scaleMiddleByVertically); Vector2 drawBM = drawM + new Vector2(0, leftMiddleHeight * scaleMiddleByVertically); Vector2 drawBR = drawR + new Vector2(0, leftMiddleHeight * scaleMiddleByVertically); sb.Draw(texture, drawTL, topLeft, Color.White); sb.Draw(texture, drawT, topMiddle, Color.White, 0f, Vector2.Zero, new Vector2(scaleMiddleByHorizontally, 1), SpriteEffects.None, 0f); sb.Draw(texture, drawTR, topRight, Color.White); sb.Draw(texture, drawL, Left, Color.White, 0f, Vector2.Zero, new Vector2(1, scaleMiddleByVertically), SpriteEffects.None, 0f); sb.Draw(texture, drawM, Middle, Color.White, 0f, Vector2.Zero, new Vector2(scaleMiddleByHorizontally, scaleMiddleByVertically), SpriteEffects.None, 0f); sb.Draw(texture, drawR, Right, Color.White, 0f, Vector2.Zero, new Vector2(1, scaleMiddleByVertically), SpriteEffects.None, 0f); sb.Draw(texture, drawBL, bottomLeft, Color.White); sb.Draw(texture, drawBM, bottomMiddle, Color.White, 0f, Vector2.Zero, new Vector2(scaleMiddleByHorizontally, 1), SpriteEffects.None, 0f); sb.Draw(texture, drawBR, bottomRight, Color.White); } public void DrawContent(SpriteBatch sb, Vector2 position, int contentWidth, int contentHeight, Color drawColor) { Rectangle topLeft = new Rectangle(1, 1, leftMostPatch - 1, topMostPatch - 1); Rectangle topMiddle = new Rectangle(leftMostPatch, 1, (rightMostPatch - leftMostPatch), topMostPatch - 1); Rectangle Left = new Rectangle(1, topMostPatch, leftMostPatch - 1, (bottomMostPatch - topMostPatch)); Rectangle Middle = new Rectangle(leftMostPatch, topMostPatch, (rightMostPatch - leftMostPatch), (bottomMostPatch - topMostPatch)); int topMiddleWidth = topMiddle.Width; int leftMiddleHeight = Left.Height; float scaleMiddleByHorizontally = ((float)contentWidth / (float)topMiddleWidth); float scaleMiddleByVertically = ((float)contentHeight / (float)leftMiddleHeight); // if (scaleMiddleByVertically < 1) scaleMiddleByVertically = 1; // if (scaleMiddleByHorizontally < 1) scaleMiddleByHorizontally = 1; Vector2 drawTL = position; Vector2 drawT = drawTL + new Vector2(topLeft.Width, 0); Vector2 drawM = drawT + new Vector2(0, topMiddle.Height); Vector2 bottomRight = new Vector2(drawM.X + (Middle.Width * scaleMiddleByHorizontally), drawM.Y + (Middle.Height * scaleMiddleByVertically)); DrawManager.Draw_Box(drawM, bottomRight, drawColor, sb, 0f, 150); } public Vector2 getCenter(int contentWidth, int contentHeight) { Rectangle topLeft = new Rectangle(1, 1, leftMostPatch - 1, topMostPatch - 1); Rectangle topRight = new Rectangle(rightMostPatch + 1, 1, (texture.Width - 1) - rightMostPatch, topMostPatch - 1); Rectangle topMiddle = new Rectangle(leftMostPatch, 1, (rightMostPatch - leftMostPatch), topMostPatch - 1); Rectangle Left = new Rectangle(1, topMostPatch, leftMostPatch - 1, (bottomMostPatch - topMostPatch)); Rectangle Middle = new Rectangle(leftMostPatch, topMostPatch, (rightMostPatch - leftMostPatch), (bottomMostPatch - topMostPatch)); int topMiddleWidth = topMiddle.Width; int leftMiddleHeight = Left.Height; float scaleMiddleByHorizontally = ((float)contentWidth / (float)topMiddleWidth); float scaleMiddleByVertically = ((float)contentHeight / (float)leftMiddleHeight); if (scaleMiddleByVertically < 1) scaleMiddleByVertically = 1; if (scaleMiddleByHorizontally < 1) scaleMiddleByHorizontally = 1; Vector2 drawMMiddle = new Vector2(topLeft.Width, topLeft.Height); drawMMiddle += new Vector2(topMiddleWidth * (scaleMiddleByHorizontally / 2), leftMiddleHeight * (scaleMiddleByVertically / 2)); return drawMMiddle; } } }
44.176471
165
0.557745
[ "Unlicense" ]
YogurtFP/YogUI
YogUILibrary/YogUILibrary/Structs/NinePatch.cs
11,267
C#
#region -- License Terms -- // // MessagePack for CLI // // Copyright (C) 2010 FUJIWARA, Yusuke // // 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. // #endregion -- License Terms -- using System; using NUnit.Framework; namespace MsgPack.Rpc.Server.Dispatch { /// <summary> ///Tests the Invocation Helper /// </summary> [TestFixture()] public class InvocationHelperTest { [Test] public void TestFields() { Assert.That( InvocationHelper.HandleArgumentDeserializationExceptionMethod, Is.Not.Null ); } [Test] public void TestTrace_SuccessAtLeast() { var oldLevel = MsgPackRpcServerDispatchTrace.Source.Switch.Level; try { MsgPackRpcServerDispatchTrace.Source.Switch.Level = System.Diagnostics.SourceLevels.All; InvocationHelper.TraceInvocationResult<object>( 1, Rpc.Protocols.MessageType.Request, 1, "TracingTest", RpcErrorMessage.Success, null ); InvocationHelper.TraceInvocationResult<object>( 1, Rpc.Protocols.MessageType.Request, 1, "TracingTest", new RpcErrorMessage( RpcError.RemoteRuntimeError, "Description", "DebugInformation" ), null ); } finally { MsgPackRpcServerDispatchTrace.Source.Switch.Level = oldLevel; } } [Test()] public void TestHandleArgumentDeserializationException_NotNull_IsDebugMode_IncludesFullExceptionInfo() { var exception = new Exception( Guid.NewGuid().ToString() ); string parameterName = Guid.NewGuid().ToString(); var result = InvocationHelper.HandleArgumentDeserializationException( exception, parameterName, true ); Assert.That( result.IsSuccess, Is.False ); Assert.That( result.Error, Is.EqualTo( RpcError.ArgumentError ) ); Assert.That( result.Detail.AsDictionary()[ RpcException.MessageKeyUtf8 ].AsString(), Is.StringContaining( parameterName ) ); Assert.That( result.Detail.AsDictionary()[ RpcException.DebugInformationKeyUtf8 ].AsString(), Is.StringContaining( exception.Message ) ); } [Test()] public void TestHandleArgumentDeserializationException_NotNull_IsNotDebugMode_DoesNotIncludeFullExceptionInfo() { var exception = new Exception( Guid.NewGuid().ToString() ); string parameterName = Guid.NewGuid().ToString(); var result = InvocationHelper.HandleArgumentDeserializationException( exception, parameterName, false ); Assert.That( result.IsSuccess, Is.False ); Assert.That( result.Error, Is.EqualTo( RpcError.ArgumentError ) ); Assert.That( result.Detail.AsDictionary()[ RpcException.MessageKeyUtf8 ].AsString(), Is.StringContaining( parameterName ) ); Assert.That( result.Detail.AsDictionary().ContainsKey( RpcException.DebugInformationKeyUtf8 ), Is.False ); } [Test()] public void TestHandleArgumentDeserializationException_Null_IsDebugMode_DefaultString() { var result = InvocationHelper.HandleArgumentDeserializationException( null, null, true ); Assert.That( result.IsSuccess, Is.False ); Assert.That( result.Error, Is.EqualTo( RpcError.ArgumentError ) ); Assert.That( result.Detail.AsDictionary()[ RpcException.MessageKeyUtf8 ].AsString(), Is.Not.Null.And.Not.Empty ); Assert.That( result.Detail.AsDictionary().ContainsKey( RpcException.DebugInformationKeyUtf8 ), Is.False ); } [Test()] public void TestHandleArgumentDeserializationException_Null_IsNotDebugMode_DefaultString() { var result = InvocationHelper.HandleArgumentDeserializationException( null, null, false ); Assert.That( result.IsSuccess, Is.False ); Assert.That( result.Error, Is.EqualTo( RpcError.ArgumentError ) ); Assert.That( result.Detail.AsDictionary()[ RpcException.MessageKeyUtf8 ].AsString(), Is.Not.Null.And.Not.Empty ); Assert.That( result.Detail.AsDictionary().ContainsKey( RpcException.DebugInformationKeyUtf8 ), Is.False ); } [Test()] public void TestHandleInvocationException_NotNull_ArgumentException_IsDebugMode_AsArgumentError() { var exception = new ArgumentException( Guid.NewGuid().ToString(), Guid.NewGuid().ToString() ); var result = InvocationHelper.HandleInvocationException( exception, "Method", true ); Assert.That( result.Error, Is.EqualTo( RpcError.ArgumentError ) ); Assert.That( result.Detail.AsDictionary()[ RpcException.MessageKeyUtf8 ].AsString(), Is.StringContaining( exception.ParamName ) ); Assert.That( result.Detail.AsDictionary()[ RpcException.DebugInformationKeyUtf8 ].AsString(), Is.StringContaining( exception.Message ) ); } [Test()] public void TestHandleInvocationException_NotNull_ArgumentException_IsNotDebugMode_AsArgumentErrorWithoutDebugInformation() { var exception = new ArgumentException( Guid.NewGuid().ToString(), Guid.NewGuid().ToString() ); var result = InvocationHelper.HandleInvocationException( exception, "Method", false ); Assert.That( result.Error, Is.EqualTo( RpcError.ArgumentError ) ); Assert.That( result.Detail.AsDictionary()[ RpcException.MessageKeyUtf8 ].AsString(), Is.StringContaining( exception.ParamName ) ); Assert.That( result.Detail.AsDictionary().ContainsKey( RpcException.DebugInformationKeyUtf8 ), Is.False ); } [Test()] public void TestHandleInvocationException_NotNull_RpcException_IsDebugMode_AsCorrespondingError() { var exception = new RpcException( RpcError.MessageTooLargeError, Guid.NewGuid().ToString(), Guid.NewGuid().ToString() ); var result = InvocationHelper.HandleInvocationException( exception, "Method", true ); Assert.That( result.Error, Is.EqualTo( exception.RpcError ) ); Assert.That( result.Detail.AsDictionary()[ RpcException.MessageKeyUtf8 ].AsString(), Is.StringContaining( exception.Message ) ); Assert.That( result.Detail.AsDictionary()[ RpcException.DebugInformationKeyUtf8 ].AsString(), Is.StringContaining( exception.DebugInformation ) ); } [Test()] public void TestHandleInvocationException_NotNull_RpcException_IsDebugMode_AsCorrespondingErrorWithoutDebugInformation() { var exception = new RpcException( RpcError.MessageTooLargeError, Guid.NewGuid().ToString(), Guid.NewGuid().ToString() ); var result = InvocationHelper.HandleInvocationException( exception, "Method", false ); Assert.That( result.Error, Is.EqualTo( exception.RpcError ) ); Assert.That( result.Detail.AsDictionary()[ RpcException.MessageKeyUtf8 ].AsString(), Is.Not.Null.And.No.Empty.And.Not.StringContaining( exception.Message ).And.Not.StringContaining( exception.DebugInformation ) ); Assert.That( result.Detail.AsDictionary().ContainsKey( RpcException.DebugInformationKeyUtf8 ), Is.False ); } [Test()] public void TestHandleInvocationException_NotNull_OtherException_IsDebugMode_AsRemoteRuntimeError() { var exception = new Exception( Guid.NewGuid().ToString() ); var result = InvocationHelper.HandleInvocationException( exception, "Method", true ); Assert.That( result.Error, Is.EqualTo( RpcError.CallError ) ); Assert.That( result.Detail.AsDictionary()[ RpcException.MessageKeyUtf8 ].AsString(), Is.Not.Null.And.Not.Empty.And.StringContaining( exception.Message ) ); Assert.That( result.Detail.AsDictionary()[ RpcException.DebugInformationKeyUtf8 ].AsString(), Is.StringContaining( exception.Message ) ); } [Test()] public void TestHandleInvocationException_NotNull_OtherException_IsNotDebugMode_AsRemoteRuntimeError() { var exception = new Exception( Guid.NewGuid().ToString() ); var result = InvocationHelper.HandleInvocationException( exception, "Method", false ); Assert.That( result.Error, Is.EqualTo( RpcError.CallError ) ); Assert.That( result.Detail.AsDictionary()[ RpcException.MessageKeyUtf8 ].AsString(), Is.Not.Null.And.Not.Empty.And.No.StringContaining( exception.Message ) ); Assert.That( result.Detail.AsDictionary().ContainsKey( RpcException.DebugInformationKeyUtf8 ), Is.False ); } [Test()] public void TestHandleInvocationException_Null_IsDebugMode_AsRemoteRuntimeError() { var result = InvocationHelper.HandleInvocationException( null, "Method", false ); Assert.That( result.Error, Is.EqualTo( RpcError.CallError ) ); Assert.That( result.Detail.AsDictionary()[ RpcException.MessageKeyUtf8 ].AsString(), Is.Not.Null.And.Not.Empty ); Assert.That( result.Detail.AsDictionary().ContainsKey( RpcException.DebugInformationKeyUtf8 ), Is.False ); } [Test()] public void TestHandleInvocationException_Null_IsNotDebugMode_AsRemoteRuntimeError() { var result = InvocationHelper.HandleInvocationException( null, "Method", false ); Assert.That( result.Error, Is.EqualTo( RpcError.CallError ) ); Assert.That( result.Detail.AsDictionary()[ RpcException.MessageKeyUtf8 ].AsString(), Is.Not.Null.And.Not.Empty ); Assert.That( result.Detail.AsDictionary().ContainsKey( RpcException.DebugInformationKeyUtf8 ), Is.False ); } } }
46.908629
216
0.762363
[ "Apache-2.0" ]
Skydev0h/msgpack-rpc-cli
test/MsgPack.Rpc.Server.UnitTest/Rpc/Server/Dispatch/InvocationHelperTest.cs
9,243
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. using System.Text.Json; namespace Azure.Storage.Files { internal static class FileErrors { public static JsonException InvalidPermissionJson(string json) => throw new JsonException("Expected { \"permission\": \"...\" }, not " + json); } }
28.933333
89
0.68894
[ "MIT" ]
Only2125/azure-sdk-for-net
sdk/storage/Azure.Storage.Files/src/FileErrors.cs
436
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using DevExpress.ExpressApp; using DevExpress.ExpressApp.Security; using DevExpress.Persistent.BaseImpl.EF.PermissionPolicy; namespace Dtg.Module.BusinessObjects { [DefaultProperty(nameof(UserName))] public class ApplicationUser : PermissionPolicyUser, IObjectSpaceLink, ISecurityUserWithLoginInfo { public ApplicationUser() : base() { UserLogins = new List<ApplicationUserLoginInfo>(); } [Browsable(false)] [DevExpress.ExpressApp.DC.Aggregated] public virtual IList<ApplicationUserLoginInfo> UserLogins { get; set; } IEnumerable<ISecurityUserLoginInfo> IOAuthSecurityUser.UserLogins => UserLogins.OfType<ISecurityUserLoginInfo>(); ISecurityUserLoginInfo ISecurityUserWithLoginInfo.CreateUserLoginInfo(string loginProviderName, string providerUserKey) { ApplicationUserLoginInfo result = ((IObjectSpaceLink)this).ObjectSpace.CreateObject<ApplicationUserLoginInfo>(); result.LoginProviderName = loginProviderName; result.ProviderUserKey = providerUserKey; result.User = this; return result; } } }
41.466667
129
0.737942
[ "MIT" ]
kgreed/dtg
Dtg.Module/BusinessObjects/ApplicationUser.cs
1,246
C#
using System; using System.Reflection; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; // 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("AWSSDK.RAM")] #if BCL35 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - AWS Resource Access Manager. AWS Resource Access Manager (AWS RAM) enables you to share your resources with any AWS account or through AWS Organizations.")] #elif BCL45 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (4.5) - AWS Resource Access Manager. AWS Resource Access Manager (AWS RAM) enables you to share your resources with any AWS account or through AWS Organizations.")] #elif NETSTANDARD13 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (NetStandard 1.3) - AWS Resource Access Manager. AWS Resource Access Manager (AWS RAM) enables you to share your resources with any AWS account or through AWS Organizations.")] #elif NETSTANDARD20 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (NetStandard 2.0) - AWS Resource Access Manager. AWS Resource Access Manager (AWS RAM) enables you to share your resources with any AWS account or through AWS Organizations.")] #elif NETCOREAPP3_1 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (.NET Core 3.1) - AWS Resource Access Manager. AWS Resource Access Manager (AWS RAM) enables you to share your resources with any AWS account or through AWS Organizations.")] #else #error Unknown platform constant - unable to set correct AssemblyDescription #endif [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("Amazon Web Services SDK for .NET")] [assembly: AssemblyCompany("Amazon.com, Inc")] [assembly: AssemblyCopyright("Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.")] [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)] // 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("3.3")] [assembly: AssemblyFileVersion("3.5.0.12")] [assembly: System.CLSCompliant(true)] #if BCL [assembly: System.Security.AllowPartiallyTrustedCallers] #endif
52.792453
245
0.771265
[ "Apache-2.0" ]
joshongithub/aws-sdk-net
sdk/src/Services/RAM/Properties/AssemblyInfo.cs
2,798
C#
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using System.Text; using System.Threading.Tasks; using WhatsAPI.UniversalApps.Libs.Core.Exceptions; using Windows.Foundation; using Windows.Networking; using Windows.Networking.Sockets; using Windows.Storage.Streams; namespace WhatsAPI.UniversalApps.Libs.Core.Connection { public class Sockets { /// <summary> /// The time between sending and recieving /// </summary> private readonly int recvTimeout; /// <summary> /// The hostname of the whatsapp server /// </summary> private readonly string whatsHost; /// <summary> /// The port of the whatsapp server /// </summary> private readonly int whatsPort; /// <summary> /// A list of bytes for incomplete messages /// </summary> private List<byte> incomplete_message = new List<byte>(); /// <summary> /// A socket to connect to the whatsapp network /// </summary> private StreamSocket socket; private uint _transferredSize; private DataReader _readerPacket; private DataWriter _writePacket; private bool _isConnected; public bool IsConnected { get { return _isConnected; } set { _isConnected = value; } } /// <summary> /// Default class constructor /// </summary> /// <param name="whatsHost">The hostname of the whatsapp server</param> /// <param name="port">The port of the whatsapp server</param> /// <param name="timeout">Timeout for the connection</param> public Sockets(string whatsHost, int port, int timeout = 2000) { this.recvTimeout = timeout; this.whatsHost = whatsHost; this.whatsPort = port; this.incomplete_message = new List<byte>(); } /// <summary> /// Default class constructor /// </summary> /// <param name="timeout">Timeout for the connection</param> public Sockets(int timeout = 2000) { this.recvTimeout = timeout; this.whatsHost = Constants.Information.WhatsAppHost; this.whatsPort = Constants.Information.WhatsPort; this.incomplete_message = new List<byte>(); } private bool isTryingtoConnect = false; /// <summary> /// Connect to the whatsapp server /// </summary> public async Task Connect() { await Task.Run(async () => { try { isTryingtoConnect = true; this.socket = new StreamSocket(); this.socket.Control.KeepAlive = true; _writePacket = new DataWriter(this.socket.OutputStream); _readerPacket = new DataReader(this.socket.InputStream); _readerPacket.InputStreamOptions = InputStreamOptions.Partial; var endPoint = new HostName(this.whatsHost); await this.socket.ConnectAsync(endPoint, this.whatsPort.ToString()); //socket.UpgradeToSslAsync(SocketProtectionLevel.SslAllowNullEncryption, new HostName(this.whatsHost)); //HandleConnect(); _transferredSize = 0; IsConnected = true; isTryingtoConnect = false; } catch (Exception ex) { isTryingtoConnect = false; throw new ConnectionException("Cannot connect"); } }); } /// <summary> /// Disconnect from the whatsapp server /// </summary> public void Disconnect() { if (this.socket != null) { this.socket.Dispose(); IsConnected = false; } } private byte[] _readData; /// <summary> /// Read 1024 bytes /// </summary> /// <returns></returns> public async Task<byte[]> ReadData() { List<byte> buff = new List<byte>(); byte[] ret = await StartReceiving(1024); _transferredSize = 0; return ret; } /// <summary> /// Send data to the whatsapp server /// </summary> /// <param name="data">Data to be send as a string</param> public async Task SendData(string data) { var tmpBytes = System.Text.Encoding.GetEncoding(Constants.Information.ASCIIEncoding).GetBytes(data); await StartSending(tmpBytes); } /// <summary> /// Send data to the whatsapp server /// </summary> /// <param name="data">Data to be send as a byte array</param> public async Task SendData(byte[] data) { await StartSending(data); } /// <summary> /// Read in a message with a specific length /// </summary> /// <param name="length">The lengh of the message</param> /// <returns>The recieved data as a byte array</returns> private async Task<byte[]> Socket_read(int length) { if (!IsConnected) { throw new ConnectionException(); } var buff = new byte[length]; int receiveLength = 0; //try //{ var byteReceived = await StartReceiving((uint)length); receiveLength = byteReceived.Length; //receiveLength = socket.Receive(buff, 0, length, 0); //} //catch (Exception excpt) //{ // if (SocketError.GetStatus(excpt.HResult) == SocketErrorStatus.ConnectionTimedOut) // { // System.Diagnostics.Debug.WriteLine("Connect-TimeOut"); // return null; // } // else // { // throw new ConnectionException("Unknown error occured", excpt); // } //} while (receiveLength <= 0) ; byte[] tmpRet = new byte[receiveLength]; if (receiveLength > 0) System.Buffer.BlockCopy(buff, 0, tmpRet, 0, receiveLength); return tmpRet; } public async Task<byte[]> ReadData(int length = 1024) { return await StartReceiving((uint)length); } /// <summary> /// Sends data of a specific length to the server /// </summary> /// <param name="data">The data that needs to be send</param> /// <param name="length">The lenght of the data</param> /// <param name="flags">Optional flags</param> private void Socket_send(string data, int length, int flags) { var tmpBytes = System.Text.Encoding.GetEncoding(Constants.Information.ASCIIEncoding).GetBytes(data); SendMsg(tmpBytes); } /// <summary> /// Send data to the server /// </summary> /// <param name="data">The data that needs to be send as a byte array</param> private void Socket_send(byte[] data) { StartSending(data); } /// <summary> /// Returns the socket status. /// </summary> public bool SocketStatus { get { return IsConnected; } } private void HandleConnect() { try { if (!_isConnected) { } else { Task readTask = Task.Factory.StartNew(() => { StartReceiving(); }); } } catch (Exception ex) { } } private async Task<byte[]> StartReceiving(uint length = 1024) { return await Task.Run(async () => { try { if (!IsConnected) { await Connect(); } try { IAsyncOperation<uint> taskLoad = _readerPacket.LoadAsync(length); taskLoad.AsTask().Wait(); uint bytesRead = taskLoad.GetResults(); if (bytesRead == 0) return null; if (_readerPacket.UnconsumedBufferLength < length) { return await StartReceiving(length); } return HandleReceive(bytesRead, _readerPacket, (int)length); } catch (Exception ex) { WhatsAPI.UniversalApps.Libs.Utils.Logger.Log.WriteLog(ex.Message); throw ex; } } catch (Exception ex) { if (ex.Message.Contains("The operation identifier is not valid.")) { throw ex; } else { throw new ConnectionException("Connection Lost"); } } }); } private byte[] HandleReceive(uint bytesRead, DataReader readPacket, int length = 1024*1024*5) { var bufferSpace = length * 2; byte[] tmpRet = new byte[length]; Windows.Storage.Streams.IBuffer ibuffer = readPacket.ReadBuffer(readPacket.UnconsumedBufferLength); Byte[] convBuffer = WindowsRuntimeBufferExtensions.ToArray(ibuffer); if (bytesRead > 0) System.Buffer.BlockCopy(convBuffer, 0, tmpRet, (int)0, (int)length); _transferredSize += bytesRead; var kucing = System.Text.Encoding.UTF8.GetString(tmpRet, 0, tmpRet.Length); WhatsAPI.UniversalApps.Libs.Utils.Logger.Log.WriteLog("Receive Message => " + System.Text.Encoding.UTF8.GetString(tmpRet, 0, tmpRet.Length)); return tmpRet; } public void SendMsg(byte[] sendBytes) { if (!_isConnected) Connect(); Task.Run(async () => { await StartSending(sendBytes); }); } public async Task<byte[]> ReadNextNode() { byte[] nodeHeader = await this.ReadData(3); if (nodeHeader == null || nodeHeader.Length == 0) { //empty response return null; } if (nodeHeader.Length != 3) { throw new Exception("Failed to read node header"); } int nodeLength = 0; nodeLength = (int)((nodeHeader[0] & 0x0F) << 16); nodeLength |= (int)nodeHeader[1] << 8; nodeLength |= (int)nodeHeader[2] << 0; //buffered read int toRead = nodeLength; List<byte> nodeData = new List<byte>(); do { byte[] nodeBuff = await this.ReadData(toRead); nodeData.AddRange(nodeBuff); toRead -= nodeBuff.Length; } while (toRead > 0); if (nodeData.Count != nodeLength) { throw new Exception("Read Next Tree error"); } List<byte> buff = new List<byte>(); buff.AddRange(nodeHeader); buff.AddRange(nodeData.ToArray()); return buff.ToArray(); } //sending message private async Task StartSending(byte[] sendBytes) { await Task.Run(async () => { try { if (!IsConnected) { await Connect(); } WhatsAPI.UniversalApps.Libs.Utils.Logger.Log.WriteLog("Sending Data =>" + System.Text.Encoding.UTF8.GetString(sendBytes, 0, sendBytes.Length)); _writePacket.WriteBytes(sendBytes); await _writePacket.StoreAsync(); } catch (Exception ex) { } }); } } }
34.317136
163
0.461991
[ "MIT" ]
billyriantono/WhatsAPI-UniversalAppsLib
WhatsAPI.UniversalApps.Libs/Core/Connection/Sockets.cs
13,420
C#
using System; using System.Diagnostics.Contracts; using System.Diagnostics; using BIM = System.Numerics.BigInteger; namespace Microsoft.BaseTypes { /// <summary> /// A representation of decimal values. /// </summary> public struct BigDec { // the internal representation [Rep] internal readonly BIM mantissa; [Rep] internal readonly int exponent; public BIM Mantissa { get { return mantissa; } } public int Exponent { get { return exponent; } } public static readonly BigDec ZERO = FromInt(0); private static readonly BIM ten = new BIM(10); //////////////////////////////////////////////////////////////////////////// // Constructors [Pure] public static BigDec FromInt(int v) { return new BigDec(v, 0); } [Pure] public static BigDec FromBigInt(BIM v) { return new BigDec(v, 0); } [Pure] public static BigDec FromString(string v) { if (v == null) { throw new FormatException(); } BIM integral = BIM.Zero; BIM fraction = BIM.Zero; int exponent = 0; int len = v.Length; int i = v.IndexOf('e'); if (i >= 0) { if (i + 1 == v.Length) { throw new FormatException(); } exponent = Int32.Parse(v.Substring(i + 1, len - i - 1)); len = i; } int fractionLen = 0; i = v.IndexOf('.'); if (i >= 0) { if (i + 1 == v.Length) { throw new FormatException(); } fractionLen = len - i - 1; fraction = BIM.Parse(v.Substring(i + 1, fractionLen)); len = i; } integral = BIM.Parse(v.Substring(0, len)); if (!fraction.IsZero) { while (fractionLen > 0) { integral = integral * ten; exponent = exponent - 1; fractionLen = fractionLen - 1; } } if (integral.Sign == -1) { return new BigDec(integral - fraction, exponent); } else { return new BigDec(integral + fraction, exponent); } } internal BigDec(BIM mantissa, int exponent) { if (mantissa.IsZero) { this.mantissa = mantissa; this.exponent = 0; } else { while (mantissa % ten == BIM.Zero) { mantissa = mantissa / ten; exponent = exponent + 1; } this.mantissa = mantissa; this.exponent = exponent; } } //////////////////////////////////////////////////////////////////////////// // Basic object operations [Pure] [Reads(ReadsAttribute.Reads.Nothing)] public override bool Equals(object obj) { if (obj == null) { return false; } if (!(obj is BigDec)) { return false; } return (this == (BigDec) obj); } [Pure] public override int GetHashCode() { return this.mantissa.GetHashCode() * 13 + this.exponent.GetHashCode(); } [Pure] public override string /*!*/ ToString() { Contract.Ensures(Contract.Result<string>() != null); return String.Format("{0}e{1}", this.mantissa.ToString(), this.exponent.ToString()); } //////////////////////////////////////////////////////////////////////////// // Conversion operations // ``floor`` rounds towards negative infinity (like SMT-LIBv2's to_int). /// <summary> /// Computes the floor and ceiling of this BigDec. Note the choice of rounding towards negative /// infinity rather than zero for floor is because SMT-LIBv2's to_int function floors this way. /// </summary> /// <param name="floor">The Floor (rounded towards negative infinity)</param> /// <param name="ceiling">Ceiling (rounded towards positive infinity)</param> public void FloorCeiling(out BIM floor, out BIM ceiling) { BIM n = this.mantissa; int e = this.exponent; if (n.IsZero) { floor = ceiling = n; } else if (0 <= e) { // it's an integer for (; 0 < e; e--) { n = n * ten; } floor = ceiling = n; } else { // it's a non-zero integer, so the ceiling is one more than the floor for (; e < 0 && !n.IsZero; e++) { n = n / ten; // Division rounds towards negative infinity } if (this.mantissa >= 0) { floor = n; ceiling = n + 1; } else { ceiling = n; floor = n - 1; } } Debug.Assert(floor <= ceiling, "Invariant was not maintained"); } [Pure] public String ToDecimalString(int maxDigits) { string s = this.mantissa.ToString(); int digits = (this.mantissa >= 0) ? s.Length : s.Length - 1; BIM max = BIM.Pow(10, maxDigits); BIM min = -max; if (this.exponent >= 0) { if (maxDigits < digits || maxDigits - digits < this.exponent) { return String.Format("{0}.0", (this.mantissa >= 0) ? max.ToString() : min.ToString()); } else { return String.Format("{0}{1}.0", s, new string('0', this.exponent)); } } else { int exp = -this.exponent; if (exp < digits) { int intDigits = digits - exp; if (maxDigits < intDigits) { return String.Format("{0}.0", (this.mantissa >= 0) ? max.ToString() : min.ToString()); } else { int fracDigits = Math.Min(maxDigits, digits - intDigits); return String.Format("{0}.{1}", s.Substring(0, intDigits), s.Substring(intDigits, fracDigits)); } } else { int fracDigits = Math.Min(maxDigits, digits); return String.Format("0.{0}{1}", new string('0', exp - fracDigits), s.Substring(0, fracDigits)); } } } [Pure] public string ToDecimalString() { string m = this.mantissa.ToString(); var e = this.exponent; if (0 <= this.exponent) { return m + Zeros(e) + ".0"; } else { e = -e; // compute k to be the longest suffix of m consisting of all zeros (but no longer than e, and not the entire string) var maxK = e < m.Length ? e : m.Length - 1; var last = m.Length - 1; var k = 0; while (k < maxK && m[last - k] == '0') { k++; } if (0 < k) { // chop off the suffix of k zeros from m and adjust e accordingly m = m.Substring(0, m.Length - k); e -= k; } if (e == 0) { return m; } else if (e < m.Length) { var n = m.Length - e; return m.Substring(0, n) + "." + m.Substring(n); } else { return "0." + Zeros(e - m.Length) + m; } } } [Pure] public static string Zeros(int n) { Contract.Requires(0 <= n); if (n <= 10) { var tenZeros = "0000000000"; return tenZeros.Substring(0, n); } else { var d = n / 2; var s = Zeros(d); if (n % 2 == 0) { return s + s; } else { return s + s + "0"; } } } //////////////////////////////////////////////////////////////////////////// // Basic arithmetic operations [Pure] public BigDec Abs { get { return new BigDec(BIM.Abs(this.mantissa), this.exponent); } } [Pure] public BigDec Negate { get { return new BigDec(BIM.Negate(this.mantissa), this.exponent); } } [Pure] public static BigDec operator -(BigDec x) { return x.Negate; } [Pure] public static BigDec operator +(BigDec x, BigDec y) { BIM m1 = x.mantissa; int e1 = x.exponent; BIM m2 = y.mantissa; int e2 = y.exponent; if (e2 < e1) { m1 = y.mantissa; e1 = y.exponent; m2 = x.mantissa; e2 = x.exponent; } while (e2 > e1) { m2 = m2 * ten; e2 = e2 - 1; } return new BigDec(m1 + m2, e1); } [Pure] public static BigDec operator -(BigDec x, BigDec y) { return x + y.Negate; } [Pure] public static BigDec operator *(BigDec x, BigDec y) { return new BigDec(x.mantissa * y.mantissa, x.exponent + y.exponent); } //////////////////////////////////////////////////////////////////////////// // Some basic comparison operations public bool IsPositive { get { return (this.mantissa > BIM.Zero); } } public bool IsNegative { get { return (this.mantissa < BIM.Zero); } } public bool IsZero { get { return this.mantissa.IsZero; } } [Pure] public int CompareTo(BigDec that) { if (this.mantissa == that.mantissa && this.exponent == that.exponent) { return 0; } else { BigDec d = this - that; return d.IsNegative ? -1 : 1; } } [Pure] public static bool operator ==(BigDec x, BigDec y) { return x.CompareTo(y) == 0; } [Pure] public static bool operator !=(BigDec x, BigDec y) { return x.CompareTo(y) != 0; } [Pure] public static bool operator <(BigDec x, BigDec y) { return x.CompareTo(y) < 0; } [Pure] public static bool operator >(BigDec x, BigDec y) { return x.CompareTo(y) > 0; } [Pure] public static bool operator <=(BigDec x, BigDec y) { return x.CompareTo(y) <= 0; } [Pure] public static bool operator >=(BigDec x, BigDec y) { return x.CompareTo(y) >= 0; } } }
23.019868
125
0.458957
[ "MIT" ]
Anjiang-Wei/boogie
Source/BaseTypes/BigDec.cs
9,976
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the databrew-2017-07-25.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.GlueDataBrew.Model { /// <summary> /// Container for the parameters to the DescribeRecipe operation. /// Returns the definition of a specific DataBrew recipe corresponding to a particular /// version. /// </summary> public partial class DescribeRecipeRequest : AmazonGlueDataBrewRequest { private string _name; private string _recipeVersion; /// <summary> /// Gets and sets the property Name. /// <para> /// The name of the recipe to be described. /// </para> /// </summary> [AWSProperty(Required=true, Min=1, Max=255)] public string Name { get { return this._name; } set { this._name = value; } } // Check to see if Name property is set internal bool IsSetName() { return this._name != null; } /// <summary> /// Gets and sets the property RecipeVersion. /// <para> /// The recipe version identifier. If this parameter isn't specified, then the latest /// published version is returned. /// </para> /// </summary> [AWSProperty(Min=1, Max=16)] public string RecipeVersion { get { return this._recipeVersion; } set { this._recipeVersion = value; } } // Check to see if RecipeVersion property is set internal bool IsSetRecipeVersion() { return this._recipeVersion != null; } } }
30.037037
106
0.624332
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/GlueDataBrew/Generated/Model/DescribeRecipeRequest.cs
2,433
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.Web.V20210201 { public static class ListWebAppPublishingCredentialsSlot { /// <summary> /// User credentials used for publishing activity. /// </summary> public static Task<ListWebAppPublishingCredentialsSlotResult> InvokeAsync(ListWebAppPublishingCredentialsSlotArgs args, InvokeOptions? options = null) => Pulumi.Deployment.Instance.InvokeAsync<ListWebAppPublishingCredentialsSlotResult>("azure-native:web/v20210201:listWebAppPublishingCredentialsSlot", args ?? new ListWebAppPublishingCredentialsSlotArgs(), options.WithVersion()); } public sealed class ListWebAppPublishingCredentialsSlotArgs : Pulumi.InvokeArgs { /// <summary> /// Name of the app. /// </summary> [Input("name", required: true)] public string Name { get; set; } = null!; /// <summary> /// Name of the resource group to which the resource belongs. /// </summary> [Input("resourceGroupName", required: true)] public string ResourceGroupName { get; set; } = null!; /// <summary> /// Name of the deployment slot. If a slot is not specified, the API will get the publishing credentials for the production slot. /// </summary> [Input("slot", required: true)] public string Slot { get; set; } = null!; public ListWebAppPublishingCredentialsSlotArgs() { } } [OutputType] public sealed class ListWebAppPublishingCredentialsSlotResult { /// <summary> /// Resource Id. /// </summary> public readonly string Id; /// <summary> /// Kind of resource. /// </summary> public readonly string? Kind; /// <summary> /// Resource Name. /// </summary> public readonly string Name; /// <summary> /// Password used for publishing. /// </summary> public readonly string? PublishingPassword; /// <summary> /// Password hash used for publishing. /// </summary> public readonly string? PublishingPasswordHash; /// <summary> /// Password hash salt used for publishing. /// </summary> public readonly string? PublishingPasswordHashSalt; /// <summary> /// Username used for publishing. /// </summary> public readonly string PublishingUserName; /// <summary> /// Url of SCM site. /// </summary> public readonly string? ScmUri; /// <summary> /// Resource type. /// </summary> public readonly string Type; [OutputConstructor] private ListWebAppPublishingCredentialsSlotResult( string id, string? kind, string name, string? publishingPassword, string? publishingPasswordHash, string? publishingPasswordHashSalt, string publishingUserName, string? scmUri, string type) { Id = id; Kind = kind; Name = name; PublishingPassword = publishingPassword; PublishingPasswordHash = publishingPasswordHash; PublishingPasswordHashSalt = publishingPasswordHashSalt; PublishingUserName = publishingUserName; ScmUri = scmUri; Type = type; } } }
31.441667
241
0.601378
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/Web/V20210201/ListWebAppPublishingCredentialsSlot.cs
3,773
C#
using AnyRPG; using System; using System.Collections; using System.Collections.Generic; using TMPro; using UnityEngine; namespace AnyRPG { public class CharacterUnit : InteractableOptionComponent { public override event Action<InteractableOptionComponent> MiniMapStatusUpdateHandler = delegate { }; public event System.Action<UnitController> OnDespawn = delegate { }; protected float despawnDelay = 20f; private float hitBoxSize = 1.5f; private Coroutine despawnCoroutine = null; private BaseCharacter baseCharacter = null; public override string DisplayName { get => (BaseCharacter != null ? BaseCharacter.CharacterName : interactableOptionProps.GetInteractionPanelTitle()); } public BaseCharacter BaseCharacter { get => baseCharacter; } protected float MyDespawnDelay { get => despawnDelay; set => despawnDelay = value; } public float HitBoxSize { get => hitBoxSize; set => hitBoxSize = value; } public CharacterUnit(Interactable interactable, InteractableOptionProps interactableOptionProps) : base(interactable, interactableOptionProps) { if (interactable.Collider != null) { hitBoxSize = interactable.Collider.bounds.extents.y * 1.5f; } } public void SetBaseCharacter(BaseCharacter baseCharacter) { //Debug.Log(interactable.gameObject.name + ".CharacterUnit.SetBaseCharacter: " + baseCharacter.gameObject.name); this.baseCharacter = baseCharacter; } public static CharacterUnit GetCharacterUnit(Interactable searchInteractable) { if (searchInteractable == null) { //Debug.Log("CharacterUnit.GetCharacterUnit: searchInteractable is null"); return null; } return searchInteractable.CharacterUnit; } public void EnableCollider() { if (interactable.Collider != null) { interactable.Collider.enabled = true; } } public void DisableCollider() { if (interactable.Collider != null) { interactable.Collider.enabled = false; } } public void HandleReviveComplete() { // give chance to update minimap and put character indicator back on it HandlePrerequisiteUpdates(); } public void HandleDie(CharacterStats _characterStats) { // give a chance to blank out minimap indicator // when the engine is upgraded to support multiplayer, this may need to be revisited. // some logic to still show minimap icons for dead players in your group so you can find and res them could be necessary HandlePrerequisiteUpdates(); } public override bool ProcessFactionValue(float factionValue) { return (factionValue <= -1f ? true : false); } /// <summary> /// The default interaction on any character is to be attacked. Return true if the relationship is less than 0. /// </summary> /// <param name="targetCharacter"></param> /// <returns></returns> public override bool CanInteract(bool processRangeCheck = false, bool passedRangeCheck = false, float factionValue = 0f, bool processNonCombatCheck = true) { if (ProcessFactionValue(factionValue) == true && baseCharacter.CharacterStats.IsAlive == true) { //Debug.Log(source.name + " can interact with us!"); return true; } //Debug.Log(gameObject.name + ".CharacterUnit.CanInteract: " + source.name + " was unable to interact with (attack) us!"); return false; } public override bool Interact(CharacterUnit source, int optionIndex = 0) { //Debug.Log(interactable.gameObject.name + ".CharacterUnit.Interact(" + source.DisplayName + ")"); float relationValue = interactable.PerformFactionCheck(PlayerManager.MyInstance.MyCharacter); if (CanInteract(false, false, relationValue)) { base.Interact(source, optionIndex); //source.MyCharacter.MyCharacterCombat.Attack(baseCharacter); // attempt to put the caster in combat so it can unsheath bows, wands, etc // disabled for now since this is re-enabled inside ability cast // this isn't processed from an action button click so the code made more sense in a common pathway //source.baseCharacter.CharacterCombat.EnterCombat(baseCharacter.UnitController); source.BaseCharacter.CharacterCombat.Attack(baseCharacter, true); PopupWindowManager.MyInstance.interactionWindow.CloseWindow(); return true; } //return true; return false; } public override void StopInteract() { //Debug.Log(gameObject.name + ".CharacterUnit.StopInteract()"); base.StopInteract(); } public override bool HasMiniMapText() { if (baseCharacter.UnitController.UnitControllerMode == UnitControllerMode.Preview || baseCharacter.UnitController.UnitControllerMode == UnitControllerMode.Mount || baseCharacter.UnitController.UnitControllerMode == UnitControllerMode.Player) { return false; } return true; } public override bool HasMiniMapIcon() { if (baseCharacter.UnitController.UnitControllerMode == UnitControllerMode.Player) { return true; } return base.HasMiniMapIcon(); } public override bool SetMiniMapText(TextMeshProUGUI text) { //Debug.Log(gameObject.name + ".CharacterUnit.SetMiniMapText()"); if (!base.SetMiniMapText(text)) { text.text = ""; text.color = new Color32(0, 0, 0, 0); return false; } text.text = "o"; if (baseCharacter != null && baseCharacter.Faction != null) { text.color = Faction.GetFactionColor(PlayerManager.MyInstance.MyCharacter, baseCharacter); } return true; } public void Despawn(float despawnDelay = 0f, bool addSystemDefaultTime = true, bool forceDespawn = false) { //Debug.Log(gameObject.name + ".CharacterUnit.Despawn(" + despawnDelay + ", " + addSystemDefaultTime + ", " + forceDespawn + ")"); //gameObject.SetActive(false); // TEST ADDING A MANDATORY DELAY if (despawnCoroutine == null && interactable.gameObject.activeSelf == true && interactable.isActiveAndEnabled) { despawnCoroutine = interactable.StartCoroutine(PerformDespawnDelay(despawnDelay, addSystemDefaultTime, forceDespawn)); } } public IEnumerator PerformDespawnDelay(float despawnDelay, bool addSystemDefaultTime = true, bool forceDespawn = false) { //Debug.Log(gameObject.name + ".CharacterUnit.PerformDespawnDelay(" + despawnDelay + ", " + addSystemDefaultTime + ", " + forceDespawn + ")"); if (forceDespawn == false) { // add all possible delays together float extraTime = 0f; if (addSystemDefaultTime) { extraTime = SystemConfigurationManager.MyInstance.DefaultDespawnTimer; } float totalDelay = despawnDelay + this.despawnDelay + extraTime; while (totalDelay > 0f) { yield return null; totalDelay -= Time.deltaTime; } } if (baseCharacter.CharacterStats.IsAlive == false || forceDespawn == true) { //Debug.Log(gameObject.name + ".CharacterUnit.PerformDespawnDelay(" + despawnDelay + ", " + addSystemDefaultTime + ", " + forceDespawn + "): despawning"); // this character could have been ressed while waiting to despawn. don't let it despawn if that happened unless forceDesapwn is true (such as at the end of a patrol) // we are going to send this ondespawn call now to allow another unit to respawn from a spawn node without a long wait during events that require rapid mob spawning OnDespawn(baseCharacter.UnitController); UnityEngine.Object.Destroy(baseCharacter.UnitController.gameObject); } else { //Debug.Log(gameObject.name + ".CharacterUnit.PerformDespawnDelay(" + despawnDelay + ", " + addSystemDefaultTime + ", " + forceDespawn + "): unit is alive!! NOT DESPAWNING"); } } /* public override string GetDescription() { //Debug.Log(gameObject.name + ".CharacterUnit.GetDescription()"); if (interactionPanelTitle == null || interactionPanelTitle == string.Empty) { //Debug.Log(gameObject.name + ".CharacterUnit.GetDescription(): returning " + MyDisplayName); return DisplayName; } else { //Debug.Log(gameObject.name + ".CharacterUnit.GetDescription(): returning " + interactionPanelTitle); return interactionPanelTitle; } } */ // CHARACTER UNIT ALIVE IS ALWAYS VALID AND CURRENT TO ALLOW ATTACKS public override int GetValidOptionCount() { //Debug.Log(gameObject.name + ".CharacterUnit.GetValidOptionCount()"); return (BaseCharacter.CharacterStats.IsAlive == true ? 1 : 0); } public override int GetCurrentOptionCount() { //Debug.Log(gameObject.name + ".CharacterUnit.GetCurrentOptionCount()"); return GetValidOptionCount(); } public override void CallMiniMapStatusUpdateHandler() { MiniMapStatusUpdateHandler(this); } public override void HandlePlayerUnitSpawn() { base.HandlePlayerUnitSpawn(); MiniMapStatusUpdateHandler(this); } } }
46.095455
190
0.620156
[ "MIT" ]
Scott004948/AnyRPGCore
Assets/AnyRPG/Engine/Core/System/Scripts/Characters/BaseClasses/CharacterUnit.cs
10,141
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.AI; public class testpath_ : MonoBehaviour { private enum state_fakeagent { idle, patrol, hearing, hearing2, walk, run, attack , dopath, ignoreall}; public NavMeshAgent Agent; public AudioSource Audio; GameObject Player; Vector3 currentTarget; Collider[] CloseSounds; public Transform[] patrol; public AudioClip[] RandomChatter; public AudioClip[] Detecting; public AudioClip[] Found; public AudioClip[] Stop; public AudioClip Hit; Vector3 lookAt; bool Talk; public float ListeningRange, closeRange, walkSpeed, runSpeed, HearingTimer, Hearing2Timer, defIdle, defWalk, foundPlayer, foundPlayerRun, AttackCool = 1, AttackDistance; float Timer = 0, AttackTimer = 0, playerDistance, playerCheck; public int frame; public Animator Animator; public LayerMask SoundLayer, groundlayer; int SoundLevel = 0; int currentNode = 0, currentPatrol; public bool isDebuggin, debugSpeed, debugPlayerPos; public bool WorldSearch = false; bool foundTarget; bool destSet; bool stateSet, debugGameLoaded = false; bool checkPlayer = true; string soundlevel = "No sounds "; state_fakeagent state = state_fakeagent.idle; // Start is called before the first frame update void Start() { Agent.Warp(transform.position); } // Update is called once per frame void Update() { if (!debugGameLoaded) { if (GameController.instance.doGameplay) { Player = GameController.instance.player; debugGameLoaded = true; checkPlayer = true; } } else { switch (state) { case state_fakeagent.idle: { if (!stateSet) { playerCheck = foundPlayer; Animator.SetBool("move", false); Agent.isStopped = true; destSet = false; stateSet = true; Timer = Random.Range(defIdle, defIdle+3); if (isDebuggin) Debug.Log("Volviendo a Idle"); } break; } case state_fakeagent.dopath: { if (!stateSet) { playerCheck = foundPlayer; Animator.SetBool("move", true); Agent.isStopped = false; Agent.speed = walkSpeed; Agent.SetDestination(currentTarget); stateSet = true; if (isDebuggin) Debug.Log("Starting path"); } else if (!Agent.pathPending && Agent.hasPath && Agent.remainingDistance < 1) { state = state_fakeagent.ignoreall; Animator.SetBool("move", false); Timer = 45; stateSet = true; if (isDebuggin) Debug.Log("Ending path"); } Timer = 10; break; } case state_fakeagent.attack: { Animator.SetBool("move", true); Animator.SetTrigger("reset"); transform.rotation = Quaternion.Lerp(transform.rotation, Quaternion.LookRotation(lookAt), 5 * Time.deltaTime); playerCheck = foundPlayerRun; if (playerDistance < AttackDistance && GameController.instance.isAlive) { Audio.PlayOneShot(Hit); GameController.instance.playercache.Death(0); GameController.instance.deathmsg = Localization.GetString("deathStrings", "death_mtf"); Agent.isStopped = true; Animator.SetTrigger("attack" + Random.Range(1, 3)); } else { Agent.isStopped = false; Agent.speed = runSpeed; if (CheckPlayer()) Agent.SetDestination(Player.transform.position); } break; } case state_fakeagent.patrol: { if (!stateSet) { //PlayVoice(1); playerCheck = foundPlayer; Animator.SetBool("move", true); Agent.isStopped = false; Agent.speed = walkSpeed; if (!WorldSearch) Agent.SetDestination(patrol[currentNode].position); else Agent.SetDestination(GameController.instance.GetPatrol(transform.position, 6, 0)); Timer = Random.Range(defWalk, defWalk+3); if (!WorldSearch) Timer = Random.Range(1, defWalk - 2); stateSet = true; if (isDebuggin) Debug.Log("Caminata"); } else if (Agent.remainingDistance < 1) { if (!WorldSearch) { /*currentNode += 1; if (currentNode >= patrol.Length) currentNode = 0;*/ currentNode = Random.Range(0, patrol.Length); Agent.SetDestination(patrol[currentNode].position); //stateSet = false; } else Agent.SetDestination(GameController.instance.GetPatrol(transform.position, 6, 0)); } break; } case state_fakeagent.run: { if (destSet == false) { playerCheck = foundPlayerRun; Animator.SetBool("move", true); Agent.isStopped = false; Agent.speed = runSpeed; Agent.SetDestination(currentTarget); destSet = true; if (isDebuggin) Debug.Log(soundlevel + "Corro hacia el!"); PlayVoice(4); } else if (Agent.remainingDistance < 1) { destSet = false; foundTarget = false; state = state_fakeagent.idle; } break; } case state_fakeagent.walk: { if (destSet == false) { playerCheck = foundPlayer; PlayVoice(3); Animator.SetBool("move", true); Agent.isStopped = false; Agent.speed = walkSpeed; Agent.SetDestination(currentTarget); destSet = true; if (isDebuggin) Debug.Log(soundlevel + "Camino hacia el!"); } else if (Agent.remainingDistance < 1) { destSet = false; foundTarget = false; state = state_fakeagent.idle; } break; } case state_fakeagent.hearing: { transform.rotation = Quaternion.Lerp(transform.rotation, Quaternion.LookRotation(lookAt), 5 * Time.deltaTime); if (!stateSet) { Agent.isStopped = true; Animator.SetBool("move", false); Animator.SetTrigger("look"); destSet = false; Timer = HearingTimer; if (isDebuggin) Debug.Log(soundlevel + "Escuche algo?"); stateSet = true; } break; } case state_fakeagent.hearing2: { transform.rotation = Quaternion.Lerp(transform.rotation, Quaternion.LookRotation(lookAt), 5 * Time.deltaTime); if (!stateSet) { Agent.isStopped = true; Animator.SetBool("move", false); Animator.SetTrigger("vocal"); destSet = false; Timer = Hearing2Timer; if (isDebuggin) Debug.Log(soundlevel + "Si escuche!"); stateSet = true; PlayVoice(2); } break; } } Timer -= Time.deltaTime; AttackTimer -= Time.deltaTime; if ((state != state_fakeagent.run && state != state_fakeagent.walk && state != state_fakeagent.attack && state != state_fakeagent.dopath ) && Timer <= 0) { foundTarget = false; stateSet = false; switch (state) { case state_fakeagent.idle: { state = state_fakeagent.patrol; break; } case state_fakeagent.patrol: { state = state_fakeagent.idle; break; } case state_fakeagent.ignoreall: { state = state_fakeagent.patrol; break; } } } if (state == state_fakeagent.run || state == state_fakeagent.walk || state == state_fakeagent.patrol || state == state_fakeagent.attack || state == state_fakeagent.dopath) { if (Agent.isOnOffMeshLink) Animator.SetFloat("speed", 2); else Animator.SetFloat("speed", Agent.velocity.magnitude); if (debugSpeed) Debug.Log(Agent.velocity.magnitude); } if (foundTarget == false && state != state_fakeagent.attack && state != state_fakeagent.dopath && state != state_fakeagent.ignoreall) { CheckSounds(); if (foundTarget) { stateSet = false; if (SoundLevel == 0) { switch (state) { case state_fakeagent.hearing2: { state = state_fakeagent.walk; break; } case state_fakeagent.run: { state = state_fakeagent.hearing2; break; } case state_fakeagent.hearing: { state = state_fakeagent.hearing2; break; } default: { Debug.Log("Cambiando a hearing!"); state = state_fakeagent.hearing; break; } } } if (SoundLevel == 1) { switch (state) { case state_fakeagent.hearing2: { state = state_fakeagent.walk; break; } case state_fakeagent.hearing: { state = state_fakeagent.walk; break; } case state_fakeagent.run: { state = state_fakeagent.walk; break; } default: { state = state_fakeagent.hearing2; break; } } } if (SoundLevel > 1) { switch (state) { case state_fakeagent.hearing2: { state = state_fakeagent.run; break; } case state_fakeagent.run: { state = state_fakeagent.run; break; } default: { state = state_fakeagent.walk; break; } } } } else { if (state != state_fakeagent.idle && state != state_fakeagent.patrol) state = state_fakeagent.idle; } } if (checkPlayer) playerDistance = Vector3.Distance(Player.transform.position, transform.position); lookAt = new Vector3(Player.transform.position.x, transform.position.y, Player.transform.position.z) - transform.position; if (debugPlayerPos) Debug.Log("Producto dot " + Vector3.Dot(transform.forward, lookAt.normalized)); if (playerDistance < playerCheck) { if (state != state_fakeagent.attack && state != state_fakeagent.dopath && Vector3.Dot(transform.forward, lookAt.normalized) > 0.4f && CheckPlayer()) { foundTarget = false; stateSet = false; PlayVoice(4); if (state == state_fakeagent.run) Animator.SetTrigger("leap"); state = state_fakeagent.attack; } } else if (state == state_fakeagent.attack) state = state_fakeagent.idle; } } bool CheckPlayer() { Debug.DrawRay(Player.transform.position, (transform.position + new Vector3(0, 0.4f, 0)) - Player.transform.position); if (Time.frameCount % frame == 0) { if (!Physics.Raycast(Player.transform.position, (transform.position + new Vector3(0, 0.4f, 0)) - Player.transform.position, playerDistance, groundlayer)) { return true; } } return false; } void PlayVoice(int library) { if (!Audio.isPlaying) { Audio.Stop(); float delay = 0; if (library == 1) { Audio.clip = RandomChatter[Random.Range(0, RandomChatter.Length)]; delay = 0.5f; } if (library == 2) { Audio.clip = Detecting[Random.Range(0, Detecting.Length)]; delay = 2; } if (library == 3) { Audio.clip = Found[Random.Range(0, Found.Length)]; delay = 0.5f; } if (library == 4) { Audio.clip = Stop[Random.Range(0, Stop.Length)]; } Audio.PlayDelayed(delay); } } public void GoHere(Vector3 here) { Debug.Log("Doing Path", this); foundTarget = false; currentTarget = here; Timer = 100; state = state_fakeagent.dopath; stateSet = false; } public void StopThis() { Debug.Log("Stopping Path", this); currentTarget = transform.position; foundTarget = false; stateSet = false; state = state_fakeagent.idle; } void CheckSounds() { float lastdistance = 100f; SoundLevel = -1; float currdistance; int currentSoundLevel; foundTarget = false; WorldSound currentSound; CloseSounds = Physics.OverlapSphere(transform.position, ListeningRange, SoundLayer); if (CloseSounds.Length != 0) { for (int i = 0; i < CloseSounds.Length; i++) { currentSound = CloseSounds[i].gameObject.GetComponent<WorldSound>(); currentSoundLevel = currentSound.SoundLevel; currdistance = Vector3.Distance(transform.position, CloseSounds[i].transform.position); if (currdistance > closeRange) currentSoundLevel -= 1; if (SoundLevel < currentSoundLevel) { if (currdistance < lastdistance) { currentTarget = CloseSounds[i].gameObject.transform.position; SoundLevel = currentSoundLevel; soundlevel = "sonido " + SoundLevel + " distancia " + currdistance + " "; foundTarget = true; } } } } } /*private void OnTriggerStay(Collider other) { if (other.gameObject.CompareTag("Player") && AttackTimer <= 0) { if (GameController.instance.isAlive) { other.gameObject.GetComponent<Player_Control>().Health -= 25; AttackTimer = AttackCool; Audio.PlayOneShot(Hit); } else { checkPlayer = false; playerDistance = 100; debugGameLoaded = false; } } }*/ }
37.286778
183
0.393048
[ "MIT" ]
AestheticalZ/Faithful-SCP-Unity
Assets/Scripts/NPC/testpath_.cs
20,025
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the mgn-2020-02-26.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.Mgn.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.Mgn.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for ValidationExceptionField Object /// </summary> public class ValidationExceptionFieldUnmarshaller : IUnmarshaller<ValidationExceptionField, XmlUnmarshallerContext>, IUnmarshaller<ValidationExceptionField, JsonUnmarshallerContext> { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> ValidationExceptionField IUnmarshaller<ValidationExceptionField, XmlUnmarshallerContext>.Unmarshall(XmlUnmarshallerContext context) { throw new NotImplementedException(); } /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public ValidationExceptionField Unmarshall(JsonUnmarshallerContext context) { context.Read(); if (context.CurrentTokenType == JsonToken.Null) return null; ValidationExceptionField unmarshalledObject = new ValidationExceptionField(); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { if (context.TestExpression("message", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.Message = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("name", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.Name = unmarshaller.Unmarshall(context); continue; } } return unmarshalledObject; } private static ValidationExceptionFieldUnmarshaller _instance = new ValidationExceptionFieldUnmarshaller(); /// <summary> /// Gets the singleton. /// </summary> public static ValidationExceptionFieldUnmarshaller Instance { get { return _instance; } } } }
35.244898
185
0.63868
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/Mgn/Generated/Model/Internal/MarshallTransformations/ValidationExceptionFieldUnmarshaller.cs
3,454
C#
using System; using IdentityModel.Client; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.IdentityModel.Tokens; namespace Common.Auth { public static class ServicesExtensions { private const string IDENTITY_API_KEY_AUTHORITY = "IdentityApiKey"; private const string IDENTITY_AUTHORITY_CONFIG = "IdentityAuthority"; private const string NO_IDENTITY_AUTHORITY_CONFIG_MESSAGE = $"Required a valid ConnectionStrings:{IDENTITY_AUTHORITY_CONFIG}"; /// <summary> /// Adds Authentication configuration with Bearer token to API projects /// <para> /// Requires a ConnectionStrings:IdentityAuthority environment value /// </para> /// </summary> /// <exception cref="ArgumentNullException"></exception> public static void AddApiAuthentication(this WebApplicationBuilder builder) { var identityAuthority = builder.Configuration.GetConnectionString(IDENTITY_AUTHORITY_CONFIG) ?? throw new ArgumentNullException(NO_IDENTITY_AUTHORITY_CONFIG_MESSAGE); builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options => { options.Authority = identityAuthority; options.TokenValidationParameters = new TokenValidationParameters { ValidateAudience = false }; options.RequireHttpsMetadata = false; }); } /// <summary> /// Adds Authentication configuration with Bearer token to API Gateways projects /// <para> /// Requires a ConnectionStrings:IdentityAuthority environment value /// </para> /// </summary> /// <exception cref="ArgumentNullException"></exception> public static void AddApiGatewayAuthentication(this WebApplicationBuilder builder) { var identityAuthority = builder.Configuration.GetConnectionString(IDENTITY_AUTHORITY_CONFIG) ?? throw new ArgumentNullException(NO_IDENTITY_AUTHORITY_CONFIG_MESSAGE); builder.Services.AddAuthentication().AddJwtBearer(IDENTITY_API_KEY_AUTHORITY, options => { options.Authority = identityAuthority; options.TokenValidationParameters = new TokenValidationParameters { ValidateAudience = false }; options.RequireHttpsMetadata = false; }); } /// <summary> /// Adds Authentication configuration with Bearer token to API client projects. /// <para> /// This requires to additionally add <c>AuthenticationDelegatingHandler</c> to IHttpClientBuilder /// </para> /// <para> /// Requires a ConnectionStrings:IdentityAuthority environment value /// </para> /// </summary> /// <exception cref="ArgumentNullException"></exception> public static void AddApiClientAuthentication(this WebApplicationBuilder builder) { var identityAuthority = builder.Configuration.GetConnectionString(IDENTITY_AUTHORITY_CONFIG) ?? throw new ArgumentNullException(NO_IDENTITY_AUTHORITY_CONFIG_MESSAGE); builder.Services.AddTransient<AuthenticationDelegatingHandler>(); builder.Services.AddSingleton(new ClientCredentialsTokenRequest() { Address = "connect/token", ClientId = "api.client", ClientSecret = "api.secret", Scope = "api.scope" }); builder.Services.AddHttpClient<IIdentityService, IdentityService>(c => c.BaseAddress = new Uri(builder.Configuration.GetConnectionString(IDENTITY_AUTHORITY_CONFIG))); } /// <summary> /// Adds AuthenticationDelegatingHandler to manage httpClient authentication header /// <para> /// Requires the previous call of <c>AddApiClientAuthentication</c> only once /// </para> /// </summary> /// <returns><c>IHttpClientBuilder</c></returns> public static IHttpClientBuilder AddAuthenticationDelegatingHandler(this IHttpClientBuilder clientBuilder) { return clientBuilder.AddHttpMessageHandler<AuthenticationDelegatingHandler>(); } } }
42.1
134
0.649536
[ "MIT" ]
joadarpe/aspnet-microservices
src/building-blocks/Common/Auth/ServicesExtensions.cs
4,633
C#
// Author: Dominic Beger (Trade/ProgTrade) 2016 using System; using System.Windows.Forms; namespace nUpdate.Administration.UI.Dialogs { public partial class StatisticsServerEditDialog : BaseDialog { public StatisticsServerEditDialog() { InitializeComponent(); } /// <summary> /// The url of the SQL-host. /// </summary> public string WebUrl { get; set; } /// <summary> /// The name of the database to use. /// </summary> public string DatabaseName { get; set; } /// <summary> /// The username for the SQL-connection. /// </summary> public string Username { get; set; } private void StatisticsServerEditDialog_Load(object sender, EventArgs e) { Text = string.Format(Text, Program.VersionString); hostTextBox.Text = WebUrl; databaseTextBox.Text = DatabaseName; usernameTextBox.Text = Username; } private void saveButton_Click(object sender, EventArgs e) { WebUrl = hostTextBox.Text; DatabaseName = databaseTextBox.Text; Username = usernameTextBox.Text; DialogResult = DialogResult.OK; } } }
28.173913
80
0.575617
[ "MIT" ]
andmattia/nUpdate
nUpdate.Administration/UI/Dialogs/StatisticsServerEditDialog.cs
1,298
C#
using System.Windows.Input; using GalaSoft.MvvmLight.Command; using MichaelBrandonMorris.Extensions.PrimitiveExtensions; using Ookii.Dialogs.Wpf; namespace MichaelBrandonMorris.DynamicText { /// <summary> /// Class DynamicDirectoryPath. /// </summary> /// <seealso cref="DynamicText" /> /// TODO Edit XML Comment Template for DynamicDirectoryPath public class DynamicDirectoryPath : DynamicText { /// <summary> /// Gets the browse folder command. /// </summary> /// <value>The browse folder command.</value> /// TODO Edit XML Comment Template for BrowseFolderCommand public ICommand BrowseFolderCommand => new RelayCommand(BrowseFolder); /// <summary> /// Browses the folder. /// </summary> /// TODO Edit XML Comment Template for BrowseFolder private void BrowseFolder() { var folderDialog = new VistaFolderBrowserDialog(); folderDialog.ShowDialog(); if (!folderDialog.SelectedPath.IsNullOrWhiteSpace() && !folderDialog.SelectedPath.Equals(Text)) { Text = folderDialog.SelectedPath; } } } }
32.473684
78
0.617504
[ "MIT" ]
michaelbmorris/MichaelBrandonMorris.DynamicText
MichaelBrandonMorris.DynamicText/DynamicDirectoryPath.cs
1,236
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.18003 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Microsoft.IronPythonTools { 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", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class VSPackage { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal VSPackage() { } /// <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("Microsoft.IronPythonTools.VSPackage", typeof(VSPackage).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.59375
180
0.614337
[ "Apache-2.0" ]
113771169/PTVS
Python/Product/IronPython/VSPackage.Designer.cs
2,790
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 glue-2017-03-31.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.Glue.Model { /// <summary> /// This is the response object from the ListWorkflows operation. /// </summary> public partial class ListWorkflowsResponse : AmazonWebServiceResponse { private string _nextToken; private List<string> _workflows = new List<string>(); /// <summary> /// Gets and sets the property NextToken. /// <para> /// A continuation token, if not all workflow names have been returned. /// </para> /// </summary> public string NextToken { get { return this._nextToken; } set { this._nextToken = value; } } // Check to see if NextToken property is set internal bool IsSetNextToken() { return this._nextToken != null; } /// <summary> /// Gets and sets the property Workflows. /// <para> /// List of names of workflows in the account. /// </para> /// </summary> [AWSProperty(Min=1, Max=25)] public List<string> Workflows { get { return this._workflows; } set { this._workflows = value; } } // Check to see if Workflows property is set internal bool IsSetWorkflows() { return this._workflows != null && this._workflows.Count > 0; } } }
29.688312
102
0.619423
[ "Apache-2.0" ]
DetlefGolze/aws-sdk-net
sdk/src/Services/Glue/Generated/Model/ListWorkflowsResponse.cs
2,286
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.AVS.V20210101Preview { /// <summary> /// NSX Segment /// </summary> [AzureNativeResourceType("azure-native:avs/v20210101preview:WorkloadNetworkSegment")] public partial class WorkloadNetworkSegment : Pulumi.CustomResource { /// <summary> /// Gateway which to connect segment to. /// </summary> [Output("connectedGateway")] public Output<string?> ConnectedGateway { get; private set; } = null!; /// <summary> /// Display name of the segment. /// </summary> [Output("displayName")] public Output<string?> DisplayName { get; private set; } = null!; /// <summary> /// Resource name. /// </summary> [Output("name")] public Output<string> Name { get; private set; } = null!; /// <summary> /// Port Vif which segment is associated with. /// </summary> [Output("portVif")] public Output<ImmutableArray<Outputs.WorkloadNetworkSegmentPortVifResponse>> PortVif { get; private set; } = null!; /// <summary> /// The provisioning state /// </summary> [Output("provisioningState")] public Output<string> ProvisioningState { get; private set; } = null!; /// <summary> /// NSX revision number. /// </summary> [Output("revision")] public Output<double?> Revision { get; private set; } = null!; /// <summary> /// Segment status. /// </summary> [Output("status")] public Output<string> Status { get; private set; } = null!; /// <summary> /// Subnet which to connect segment to. /// </summary> [Output("subnet")] public Output<Outputs.WorkloadNetworkSegmentSubnetResponse?> Subnet { get; private set; } = null!; /// <summary> /// Resource type. /// </summary> [Output("type")] public Output<string> Type { get; private set; } = null!; /// <summary> /// Create a WorkloadNetworkSegment resource with the given unique name, arguments, and options. /// </summary> /// /// <param name="name">The unique name of the resource</param> /// <param name="args">The arguments used to populate this resource's properties</param> /// <param name="options">A bag of options that control this resource's behavior</param> public WorkloadNetworkSegment(string name, WorkloadNetworkSegmentArgs args, CustomResourceOptions? options = null) : base("azure-native:avs/v20210101preview:WorkloadNetworkSegment", name, args ?? new WorkloadNetworkSegmentArgs(), MakeResourceOptions(options, "")) { } private WorkloadNetworkSegment(string name, Input<string> id, CustomResourceOptions? options = null) : base("azure-native:avs/v20210101preview:WorkloadNetworkSegment", name, null, MakeResourceOptions(options, id)) { } private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id) { var defaultOptions = new CustomResourceOptions { Version = Utilities.Version, Aliases = { new Pulumi.Alias { Type = "azure-nextgen:avs/v20210101preview:WorkloadNetworkSegment"}, new Pulumi.Alias { Type = "azure-native:avs:WorkloadNetworkSegment"}, new Pulumi.Alias { Type = "azure-nextgen:avs:WorkloadNetworkSegment"}, new Pulumi.Alias { Type = "azure-native:avs/v20200717preview:WorkloadNetworkSegment"}, new Pulumi.Alias { Type = "azure-nextgen:avs/v20200717preview:WorkloadNetworkSegment"}, }, }; var merged = CustomResourceOptions.Merge(defaultOptions, options); // Override the ID if one was specified for consistency with other language SDKs. merged.Id = id ?? merged.Id; return merged; } /// <summary> /// Get an existing WorkloadNetworkSegment resource's state with the given name, ID, and optional extra /// properties used to qualify the lookup. /// </summary> /// /// <param name="name">The unique name of the resulting resource.</param> /// <param name="id">The unique provider ID of the resource to lookup.</param> /// <param name="options">A bag of options that control this resource's behavior</param> public static WorkloadNetworkSegment Get(string name, Input<string> id, CustomResourceOptions? options = null) { return new WorkloadNetworkSegment(name, id, options); } } public sealed class WorkloadNetworkSegmentArgs : Pulumi.ResourceArgs { /// <summary> /// Gateway which to connect segment to. /// </summary> [Input("connectedGateway")] public Input<string>? ConnectedGateway { get; set; } /// <summary> /// Display name of the segment. /// </summary> [Input("displayName")] public Input<string>? DisplayName { get; set; } /// <summary> /// Name of the private cloud /// </summary> [Input("privateCloudName", required: true)] public Input<string> PrivateCloudName { get; set; } = null!; /// <summary> /// The name of the resource group. The name is case insensitive. /// </summary> [Input("resourceGroupName", required: true)] public Input<string> ResourceGroupName { get; set; } = null!; /// <summary> /// NSX revision number. /// </summary> [Input("revision")] public Input<double>? Revision { get; set; } /// <summary> /// NSX Segment identifier. Generally the same as the Segment's display name /// </summary> [Input("segmentId")] public Input<string>? SegmentId { get; set; } /// <summary> /// Subnet which to connect segment to. /// </summary> [Input("subnet")] public Input<Inputs.WorkloadNetworkSegmentSubnetArgs>? Subnet { get; set; } public WorkloadNetworkSegmentArgs() { } } }
38.610465
160
0.594639
[ "Apache-2.0" ]
pulumi-bot/pulumi-azure-native
sdk/dotnet/AVS/V20210101Preview/WorkloadNetworkSegment.cs
6,641
C#
// Copyright (C) Microsoft Corporation. All rights reserved. namespace EndianBitConverter { /// <summary> /// A big-endian BitConverter that converts base data types to an array of bytes, and an array of bytes to base data types. All conversions are in /// big-endian format regardless of machine architecture. /// </summary> internal class BigEndianBitConverter : EndianBitConverter { // Instance available from EndianBitConverter.BigEndian internal BigEndianBitConverter() { } public override bool IsLittleEndian { get; } = false; public override bool IsMid { get; } = false; public override byte[] GetBytes(short value) { return new byte[] { (byte)(value >> 8), (byte)value }; } public override byte[] GetBytes(int value) { return new byte[] { (byte)(value >> 24), (byte)(value >> 16), (byte)(value >> 8), (byte)value }; } public override byte[] GetBytes(long value) { return new byte[] { (byte)(value >> 56), (byte)(value >> 48), (byte)(value >> 40), (byte)(value >> 32), (byte)(value >> 24), (byte)(value >> 16), (byte)(value >> 8), (byte)value }; } public override short ToInt16(byte[] value, int startIndex) { this.CheckArguments(value, startIndex, sizeof(short)); return (short)((value[startIndex] << 8) | (value[startIndex + 1])); } public override int ToInt32(byte[] value, int startIndex) { this.CheckArguments(value, startIndex, sizeof(int)); return (value[startIndex] << 24) | (value[startIndex + 1] << 16) | (value[startIndex + 2] << 8) | (value[startIndex + 3]); } public override long ToInt64(byte[] value, int startIndex) { this.CheckArguments(value, startIndex, sizeof(long)); int highBytes = (value[startIndex] << 24) | (value[startIndex + 1] << 16) | (value[startIndex + 2] << 8) | (value[startIndex + 3]); int lowBytes = (value[startIndex + 4] << 24) | (value[startIndex + 5] << 16) | (value[startIndex + 6] << 8) | (value[startIndex + 7]); return ((uint)lowBytes | ((long)highBytes << 32)); } } }
39.827586
150
0.57013
[ "MIT" ]
ovidiaconescu/BitConverter
EndianBitConverter/BigEndianBitConverter.cs
2,312
C#
// Copyright (c) 2016-2020 Alexander Ong // See LICENSE in project root for license information. using UnityEngine; using MoonscraperChartEditor.Song; public class InspectorSwitching : MonoBehaviour { [SerializeField] GameObject canvas; [SerializeField] NotePropertiesPanelController noteInspector; [SerializeField] StarpowerPropertiesPanelController spInspector; [SerializeField] SectionPropertiesPanelController sectionInspector; [SerializeField] BPMPropertiesPanelController bpmInspector; [SerializeField] TimesignaturePropertiesPanelController tsInspector; [SerializeField] EventPropertiesPanelController eventInspector; [SerializeField] GameObject groupSelectInspector; ChartEditor editor; GameObject currentPropertiesPanel = null; // Use this for initialization void Start () { noteInspector.gameObject.SetActive(false); spInspector.gameObject.SetActive(false); sectionInspector.gameObject.SetActive(false); bpmInspector.gameObject.SetActive(false); tsInspector.gameObject.SetActive(false); eventInspector.gameObject.SetActive(false); editor = ChartEditor.Instance; editor.events.groupMoveStart.Register(OnGroupMoveStart); } void OnGroupMoveStart() { // Disable to the panel immediately. Inconsistent update order may make current panel get updated for 1 frame after group move has started. if (currentPropertiesPanel) currentPropertiesPanel.SetActive(false); } // Update is called once per frame void Update() { if ((editor.toolManager.currentToolId == EditorObjectToolManager.ToolID.Cursor) && editor.selectedObjectsManager.currentSelectedObjects.Count > 1) { if (!currentPropertiesPanel || currentPropertiesPanel != groupSelectInspector) { if (currentPropertiesPanel) currentPropertiesPanel.SetActive(false); currentPropertiesPanel = groupSelectInspector; } if (currentPropertiesPanel && !currentPropertiesPanel.gameObject.activeSelf) currentPropertiesPanel.gameObject.SetActive(true); if (currentPropertiesPanel == groupSelectInspector) { groupSelectInspector.SetActive(Globals.viewMode == Globals.ViewMode.Chart); } } else if (editor.selectedObjectsManager.currentSelectedObject != null) { GameObject previousPanel = currentPropertiesPanel; switch (editor.selectedObjectsManager.currentSelectedObjects[0].classID) { case ((int)SongObject.ID.Note): noteInspector.currentNote = (Note)editor.selectedObjectsManager.currentSelectedObject; currentPropertiesPanel = noteInspector.gameObject; break; case ((int)SongObject.ID.Starpower): spInspector.currentSp = (Starpower)editor.selectedObjectsManager.currentSelectedObject; currentPropertiesPanel = spInspector.gameObject; break; case ((int)SongObject.ID.Section): sectionInspector.currentSection = (Section)editor.selectedObjectsManager.currentSelectedObject; currentPropertiesPanel = sectionInspector.gameObject; break; case ((int)SongObject.ID.BPM): bpmInspector.currentBPM = (BPM)editor.selectedObjectsManager.currentSelectedObject; currentPropertiesPanel = bpmInspector.gameObject; break; case ((int)SongObject.ID.TimeSignature): tsInspector.currentTS = (TimeSignature)editor.selectedObjectsManager.currentSelectedObject; currentPropertiesPanel = tsInspector.gameObject; break; case ((int)SongObject.ID.Event): eventInspector.currentEvent = (MoonscraperChartEditor.Song.Event)editor.selectedObjectsManager.currentSelectedObject; currentPropertiesPanel = eventInspector.gameObject; break; case ((int)SongObject.ID.ChartEvent): eventInspector.currentChartEvent = (ChartEvent)editor.selectedObjectsManager.currentSelectedObject; currentPropertiesPanel = eventInspector.gameObject; break; default: currentPropertiesPanel = null; break; } if (currentPropertiesPanel != previousPanel) { if (previousPanel) { previousPanel.SetActive(false); } } if (currentPropertiesPanel != null && !currentPropertiesPanel.gameObject.activeSelf) { currentPropertiesPanel.gameObject.SetActive(true); } } else if (currentPropertiesPanel) { currentPropertiesPanel.gameObject.SetActive(false); currentPropertiesPanel = null; } if (!currentPropertiesPanel) { canvas.SetActive(false); } else { bool applicationModeNotPlaying = editor.currentState != ChartEditor.State.Playing; if (canvas.activeSelf != applicationModeNotPlaying) { canvas.SetActive(applicationModeNotPlaying); } } if (currentPropertiesPanel && editor.services.IsLyricEditorActive) { currentPropertiesPanel.SetActive(false); } } }
40.445205
155
0.614903
[ "BSD-3-Clause" ]
Ahriana/PeakAmplitude
Moonscraper Chart Editor/Assets/Scripts/Game/UI/InspectorSwitching.cs
5,907
C#
namespace CloudConfVarnaEdition4._0_RestAPI.Areas.HelpPage { /// <summary> /// Indicates whether the sample is used for request or response /// </summary> public enum SampleDirection { Request = 0, Response } }
22.727273
68
0.64
[ "MIT" ]
dimitardanailov/cloud_conf_varna_edition_rest_api
CloudConfVarnaEdition4.0-RestAPI/Areas/HelpPage/SampleGeneration/SampleDirection.cs
250
C#
using ProjectEvent.UI.Controls.Base; using System; using System.Collections.Generic; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; namespace ProjectEvent.UI.Controls.IconSelection { public class IconSelection : Control { public IconTypes SelectedIcon { get { return (IconTypes)GetValue(SelectedIconProperty); } set { SetValue(SelectedIconProperty, value); } } public static readonly DependencyProperty SelectedIconProperty = DependencyProperty.Register("SelectedIcon", typeof(IconTypes), typeof(IconSelection)); private Popup popup; private WrapPanel iconsPanel; private Button button; public IconSelection() { DefaultStyleKey = typeof(IconSelection); } public override void OnApplyTemplate() { base.OnApplyTemplate(); popup = GetTemplateChild("Popup") as Popup; button = GetTemplateChild("Button") as Button; iconsPanel = GetTemplateChild("IconsPanel") as WrapPanel; Init(); } private void Init() { button.Click += (e, c) => { popup.IsOpen = true; }; //导入图标 foreach (IconTypes icon in Enum.GetValues(typeof(IconTypes))) { if(icon!= IconTypes.None) { var iconBtn = new Button(); iconBtn.Width = 50; iconBtn.Height = 50; iconBtn.FontSize = 12; iconBtn.Style = FindResource("Icon") as Style; iconBtn.Content = new Icon() { IconType = icon }; iconBtn.Click += (e, c) => { SelectedIcon = icon; popup.IsOpen = false; }; iconsPanel.Children.Add(iconBtn); } } } } }
31.246377
98
0.505566
[ "MIT" ]
Planshit/ProjectEvent
src/ProjectEvent.UI/Controls/IconSelection/IconSelection.cs
2,166
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _11.Real_Number_Types { class Program { static void Main(string[] args) { byte countOfDigitsAfterDecimalPoint = byte.Parse(Console.ReadLine()); decimal number = decimal.Parse(Console.ReadLine()); Console.WriteLine($"{Math.Round(number,countOfDigitsAfterDecimalPoint)}"); } } }
25.105263
86
0.668763
[ "MIT" ]
bobo4aces/02.SoftUni-TechModule
01. PF - 04. Data Types and Variables - Lab/11. Real Number Types/11. Real Number Types.cs
479
C#
using ColossalFramework.UI; using NodeMarkup.Manager; using NodeMarkup.Utils; using System; using System.Linq; using UnityEngine; namespace NodeMarkup.UI.Editors { public abstract class HeaderPanel : EditorItem { public static UITextureAtlas ButtonAtlas { get; } = GetStylesIcons(); private static UITextureAtlas GetStylesIcons() { var spriteNames = new string[] { "Hovered", "_", "AddTemplate", "ApplyTemplate", "Copy", "Paste", "SetDefault", "UnsetDefault", }; var atlas = TextureUtil.GetAtlas(nameof(ButtonAtlas)); if (atlas == UIView.GetAView().defaultAtlas) { atlas = TextureUtil.CreateTextureAtlas("Buttons.png", nameof(ButtonAtlas), 25, 25, spriteNames, new RectOffset(2,2,2,2)); } return atlas; } public event Action OnDelete; protected UIPanel Content { get; set; } protected UIButton DeleteButton { get; set; } public HeaderPanel() { AddDeleteButton(); AddContent(); } public virtual void Init(float height = defaultHeight, bool isDeletable = true) { base.Init(height); DeleteButton.enabled = isDeletable; } protected override void OnSizeChanged() { base.OnSizeChanged(); Content.size = new Vector2(DeleteButton.enabled ? width - DeleteButton.width - 10 : width, height); Content.autoLayout = true; Content.autoLayout = false; DeleteButton.relativePosition = new Vector2(width - DeleteButton.width - 5, (height - DeleteButton.height) / 2); foreach (var item in Content.components) item.relativePosition = new Vector2(item.relativePosition.x, (Content.height - item.height) / 2); } private void AddContent() { Content = AddUIComponent<UIPanel>(); Content.relativePosition = new Vector2(0, 0); Content.autoLayoutDirection = LayoutDirection.Horizontal; Content.autoLayoutPadding = new RectOffset(0, 5, 0, 0); } private void AddDeleteButton() { DeleteButton = AddUIComponent<UIButton>(); DeleteButton.atlas = TextureUtil.InGameAtlas; DeleteButton.normalBgSprite = "buttonclose"; DeleteButton.hoveredBgSprite = "buttonclosehover"; DeleteButton.pressedBgSprite = "buttonclosepressed"; DeleteButton.size = new Vector2(20, 20); DeleteButton.eventClick += DeleteClick; } private void DeleteClick(UIComponent component, UIMouseEventParameter eventParam) => OnDelete?.Invoke(); protected UIButton AddButton(string sprite, string text = null, MouseEventHandler onClick = null) { var button = Content.AddUIComponent<UIButton>(); button.hoveredBgSprite = "Hovered"; button.pressedBgSprite = "Hovered"; button.size = new Vector2(25, 25); button.atlas = ButtonAtlas; button.hoveredColor = Color.black; button.pressedColor = new Color32(32, 32, 32, 255); button.tooltip = text; if (onClick != null) button.eventClick += onClick; var panel = button.AddUIComponent<UIPanel>(); panel.size = button.size; panel.atlas = button.atlas; panel.relativePosition = Vector2.zero; SetSprite(button, sprite); return button; } protected void SetSprite(UIButton button, string sprite) => (button.components.First() as UIPanel).backgroundSprite = sprite; } public class StyleHeaderPanel : HeaderPanel { public event Action OnSaveTemplate; public event Action<StyleTemplate> OnSelectTemplate; public event Action OnCopy; public event Action OnPaste; Style.StyleType StyleGroup { get; set; } TemplateSelectPanel Popup { get; set; } UIButton SaveTemplate { get; set; } UIButton ApplyTemplate { get; set; } UIButton Copy { get; set; } UIButton Paste { get; set; } public StyleHeaderPanel() { SaveTemplate = AddButton("AddTemplate", NodeMarkup.Localize.HeaderPanel_SaveAsTemplate, SaveTemplateClick); ApplyTemplate = AddButton("ApplyTemplate", NodeMarkup.Localize.HeaderPanel_ApplyTemplate, ApplyTemplateClick); Copy = AddButton("Copy", NodeMarkup.Localize.LineEditor_StyleCopy, CopyClick); Paste = AddButton("Paste", NodeMarkup.Localize.LineEditor_StylePaste, PasteClick); } public void Init(Style.StyleType styleGroup, bool isDeletable = true) { base.Init(35, isDeletable); StyleGroup = styleGroup & Style.StyleType.GroupMask; } protected override void OnVisibilityChanged() { base.OnVisibilityChanged(); if(!isVisible) ClosePopup(); } private void SaveTemplateClick(UIComponent component, UIMouseEventParameter eventParam) => OnSaveTemplate?.Invoke(); private void ApplyTemplateClick(UIComponent component, UIMouseEventParameter eventParam) { if (Popup == null) OpenPopup(); else ClosePopup(); } private void OnPopupLostFocus(UIComponent component, UIFocusEventParameter eventParam) { var uiView = Popup.GetUIView(); var mouse = uiView.ScreenPointToGUI(Input.mousePosition / uiView.inputScale); var popupRect = new Rect(Popup.absolutePosition, Popup.size); var buttonRect = new Rect(ApplyTemplate.absolutePosition, ApplyTemplate.size); if (!popupRect.Contains(mouse) && !buttonRect.Contains(mouse)) ClosePopup(); else Popup.Focus(); } private void OnTemplateSelect(StyleTemplate template) { OnSelectTemplate?.Invoke(template); ClosePopup(); } private void OpenPopup() { var root = GetRootContainer(); Popup = root.AddUIComponent<TemplateSelectPanel>(); Popup.Init(StyleGroup); Popup.OnSelect += OnTemplateSelect; Popup.eventLostFocus += OnPopupLostFocus; SetPopupPosition(); Popup.Focus(); Popup.parent.eventPositionChanged += SetPopupPosition; } private void ClosePopup() { if (Popup != null) { Popup.parent.eventPositionChanged -= SetPopupPosition; Popup.OnSelect -= OnTemplateSelect; Popup.eventLostFocus -= OnPopupLostFocus; Popup.parent.RemoveUIComponent(Popup); Destroy(Popup.gameObject); Popup = null; } } private void SetPopupPosition(UIComponent component = null, Vector2 value = default) { if (Popup != null) { UIView uiView = Popup.GetUIView(); var screen = uiView.GetScreenResolution(); var position = ApplyTemplate.absolutePosition + new Vector3(0, ApplyTemplate.height); position.x = MathPos(position.x, Popup.width, screen.x); position.y = MathPos(position.y, Popup.height, screen.y); Popup.relativePosition = position - Popup.parent.absolutePosition; } float MathPos(float pos, float size, float screen) => pos + size > screen ? (screen - size < 0 ? 0 : screen - size) : Mathf.Max(pos, 0); } private void CopyClick(UIComponent component, UIMouseEventParameter eventParam) => OnCopy?.Invoke(); private void PasteClick(UIComponent component, UIMouseEventParameter eventParam) => OnPaste?.Invoke(); public class TemplateSelectPanel : UIPanel { public event Action<StyleTemplate> OnSelect; private static float MaxContentHeight { get; } = 200; protected UIScrollablePanel ScrollableContent { get; private set; } private float Padding => 2f; private float _width = 250f; public float Width { get => _width; set { _width = value; FitContentChildren(); } } public Vector2 MaxSize { get => ScrollableContent.maximumSize; set => ScrollableContent.maximumSize = value; } public TemplateSelectPanel() { isVisible = true; canFocus = true; isInteractive = true; color = new Color32(58, 88, 104, 255); atlas = TextureUtil.InGameAtlas; backgroundSprite = "OptionsDropboxListbox"; } public void Init(Style.StyleType styleGroup) { AddPanel(); styleGroup &= Style.StyleType.GroupMask; Fill(styleGroup); ContentSizeChanged(); ScrollableContent.eventSizeChanged += ContentSizeChanged; } private void AddPanel() { ScrollableContent = AddUIComponent<UIScrollablePanel>(); ScrollableContent.autoLayout = true; ScrollableContent.autoLayoutDirection = LayoutDirection.Vertical; ScrollableContent.autoLayoutPadding = new RectOffset(0, 0, 0, 0); ScrollableContent.clipChildren = true; ScrollableContent.builtinKeyNavigation = true; ScrollableContent.scrollWheelDirection = UIOrientation.Vertical; ScrollableContent.maximumSize = new Vector2(250, 500); ScrollableContent.relativePosition = new Vector2(Padding, Padding); UIUtils.AddScrollbar(this, ScrollableContent); ScrollableContent.eventComponentAdded += (UIComponent container, UIComponent child) => { child.eventVisibilityChanged += (UIComponent component, bool value) => FitContentChildren(); child.eventSizeChanged += (UIComponent component, Vector2 value) => FitContentChildren(); }; FitContentChildren(); } private void Fill(Style.StyleType styleGroup) { var templates = TemplateManager.GetTemplates(styleGroup).ToArray(); if(!templates.Any()) { var emptyLabel = ScrollableContent.AddUIComponent<UILabel>(); emptyLabel.text = NodeMarkup.Localize.HeaderPanel_NoTemplates; emptyLabel.textScale = 0.8f; emptyLabel.autoSize = false; emptyLabel.width = ScrollableContent.width; emptyLabel.autoHeight = true; emptyLabel.textAlignment = UIHorizontalAlignment.Center; emptyLabel.padding = new RectOffset(0, 0, 5, 5); return; } foreach (var template in templates) { var item = ScrollableContent.AddUIComponent<TemplateItem>(); item.Init(true, false); item.name = template.ToString(); item.Object = template; item.eventClick += ItemClick; } } private void ItemClick(UIComponent component, UIMouseEventParameter eventParam) { if (component is TemplateItem item) OnSelect?.Invoke(item.Object); } private void FitContentChildren() { ScrollableContent.FitChildrenVertically(); ScrollableContent.width = ScrollableContent.verticalScrollbar.isVisible ? Width - ScrollableContent.verticalScrollbar.width : Width; } private void ContentSizeChanged(UIComponent component = null, Vector2 value = default) { if (ScrollableContent != null) { size = ScrollableContent.size + new Vector2(Padding * 2, Padding * 2); ScrollableContent.verticalScrollbar.relativePosition = ScrollableContent.relativePosition + new Vector3(ScrollableContent.width, 0); ScrollableContent.verticalScrollbar.height = ScrollableContent.height; foreach (var item in ScrollableContent.components) item.width = ScrollableContent.width; } } } } public class TemplateHeaderPanel : HeaderPanel { public event Action OnSetAsDefault; UIButton SetAsDefaultButton { get; set; } public TemplateHeaderPanel() { SetAsDefaultButton = AddButton(string.Empty, onClick: SetAsDefaultClick); } public void Init(bool isDefault) { base.Init(isDeletable: false); SetSprite(SetAsDefaultButton, isDefault ? "UnsetDefault" : "SetDefault"); SetAsDefaultButton.tooltip = isDefault ? NodeMarkup.Localize.HeaderPanel_UnsetAsDefault : NodeMarkup.Localize.HeaderPanel_SetAsDefault; } protected override void OnSizeChanged() { base.OnSizeChanged(); SetAsDefaultButton.relativePosition = new Vector2(5, (height - SetAsDefaultButton.height) / 2); } private void SetAsDefaultClick(UIComponent component, UIMouseEventParameter eventParam) => OnSetAsDefault?.Invoke(); } }
39.392157
152
0.579464
[ "MIT" ]
garethhubball/NodeMarkup
NodeMarkup/UI/Property panels/HeaderPanel.cs
14,065
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. #if FEATURE_METADATA_READER using Microsoft.Scripting.Metadata; #endif using TypeInfo = System.Type; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Security; using System.Text; using Microsoft.Scripting.Generation; using Microsoft.Scripting.Runtime; namespace Microsoft.Scripting.Utils { public static class ReflectionUtils { #region Accessibility public static readonly BindingFlags AllMembers = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic; public static bool IsPublic(this PropertyInfo property) { return property.GetGetMethod(nonPublic: false) != null || property.GetSetMethod(nonPublic: false) != null; } public static bool IsStatic(this PropertyInfo property) { var getter = property.GetGetMethod(nonPublic: true); var setter = property.GetSetMethod(nonPublic: true); return getter != null && getter.IsStatic || setter != null && setter.IsStatic; } public static bool IsStatic(this EventInfo evnt) { var add = evnt.GetAddMethod(nonPublic: true); var remove = evnt.GetRemoveMethod(nonPublic: true); return add != null && add.IsStatic || remove != null && remove.IsStatic; } public static bool IsPrivate(this PropertyInfo property) { var getter = property.GetGetMethod(nonPublic: true); var setter = property.GetSetMethod(nonPublic: true); return (getter == null || getter.IsPrivate) && (setter == null || setter.IsPrivate); } public static bool IsPrivate(this EventInfo evnt) { var add = evnt.GetAddMethod(nonPublic: true); var remove = evnt.GetRemoveMethod(nonPublic: true); return (add == null || add.IsPrivate) && (remove == null || remove.IsPrivate); } private static bool MatchesFlags(ConstructorInfo member, BindingFlags flags) { return ((member.IsPublic ? BindingFlags.Public : BindingFlags.NonPublic) & flags) != 0 && ((member.IsStatic ? BindingFlags.Static : BindingFlags.Instance) & flags) != 0; } private static bool MatchesFlags(MethodInfo member, BindingFlags flags) { return ((member.IsPublic ? BindingFlags.Public : BindingFlags.NonPublic) & flags) != 0 && ((member.IsStatic ? BindingFlags.Static : BindingFlags.Instance) & flags) != 0; } private static bool MatchesFlags(FieldInfo member, BindingFlags flags) { return ((member.IsPublic ? BindingFlags.Public : BindingFlags.NonPublic) & flags) != 0 && ((member.IsStatic ? BindingFlags.Static : BindingFlags.Instance) & flags) != 0; } private static bool MatchesFlags(PropertyInfo member, BindingFlags flags) { return ((member.IsPublic() ? BindingFlags.Public : BindingFlags.NonPublic) & flags) != 0 && ((member.IsStatic() ? BindingFlags.Static : BindingFlags.Instance) & flags) != 0; } private static bool MatchesFlags(EventInfo member, BindingFlags flags) { var add = member.GetAddMethod(); var remove = member.GetRemoveMethod(); var raise = member.GetRaiseMethod(); bool isPublic = add != null && add.IsPublic || remove != null && remove.IsPublic || raise != null && raise.IsPublic; bool isStatic = add != null && add.IsStatic || remove != null && remove.IsStatic || raise != null && raise.IsStatic; return ((isPublic ? BindingFlags.Public : BindingFlags.NonPublic) & flags) != 0 && ((isStatic ? BindingFlags.Static : BindingFlags.Instance) & flags) != 0; } private static bool MatchesFlags(TypeInfo member, BindingFlags flags) { // Static/Instance are ignored return (((member.IsPublic || member.IsNestedPublic) ? BindingFlags.Public : BindingFlags.NonPublic) & flags) != 0; } private static bool MatchesFlags(MemberInfo member, BindingFlags flags) { ConstructorInfo ctor; MethodInfo method; FieldInfo field; EventInfo evnt; PropertyInfo property; if ((method = member as MethodInfo) != null) { return MatchesFlags(method, flags); } if ((field = member as FieldInfo) != null) { return MatchesFlags(field, flags); } if ((ctor = member as ConstructorInfo) != null) { return MatchesFlags(ctor, flags); } if ((evnt = member as EventInfo) != null) { return MatchesFlags(evnt, flags); } if ((property = member as PropertyInfo) != null) { return MatchesFlags(property, flags); } return MatchesFlags((TypeInfo)member, flags); } private static IEnumerable<T> WithBindingFlags<T>(this IEnumerable<T> members, Func<T, BindingFlags, bool> matchFlags, BindingFlags flags) where T : MemberInfo { return members.Where(member => matchFlags(member, flags)); } public static IEnumerable<MemberInfo> WithBindingFlags(this IEnumerable<MemberInfo> members, BindingFlags flags) { return members.WithBindingFlags(MatchesFlags, flags); } public static IEnumerable<MethodInfo> WithBindingFlags(this IEnumerable<MethodInfo> members, BindingFlags flags) { return members.WithBindingFlags(MatchesFlags, flags); } public static IEnumerable<ConstructorInfo> WithBindingFlags(this IEnumerable<ConstructorInfo> members, BindingFlags flags) { return members.WithBindingFlags(MatchesFlags, flags); } public static IEnumerable<FieldInfo> WithBindingFlags(this IEnumerable<FieldInfo> members, BindingFlags flags) { return members.WithBindingFlags(MatchesFlags, flags); } public static IEnumerable<PropertyInfo> WithBindingFlags(this IEnumerable<PropertyInfo> members, BindingFlags flags) { return members.WithBindingFlags(MatchesFlags, flags); } public static IEnumerable<EventInfo> WithBindingFlags(this IEnumerable<EventInfo> members, BindingFlags flags) { return members.WithBindingFlags(MatchesFlags, flags); } public static IEnumerable<TypeInfo> WithBindingFlags(this IEnumerable<TypeInfo> members, BindingFlags flags) { return members.WithBindingFlags(MatchesFlags, flags); } public static MemberInfo WithBindingFlags(this MemberInfo member, BindingFlags flags) { return member != null && MatchesFlags(member, flags) ? member : null; } public static MethodInfo WithBindingFlags(this MethodInfo member, BindingFlags flags) { return member != null && MatchesFlags(member, flags) ? member : null; } public static ConstructorInfo WithBindingFlags(this ConstructorInfo member, BindingFlags flags) { return member != null && MatchesFlags(member, flags) ? member : null; } public static FieldInfo WithBindingFlags(this FieldInfo member, BindingFlags flags) { return member != null && MatchesFlags(member, flags) ? member : null; } public static PropertyInfo WithBindingFlags(this PropertyInfo member, BindingFlags flags) { return member != null && MatchesFlags(member, flags) ? member : null; } public static EventInfo WithBindingFlags(this EventInfo member, BindingFlags flags) { return member != null && MatchesFlags(member, flags) ? member : null; } public static TypeInfo WithBindingFlags(this TypeInfo member, BindingFlags flags) { return member != null && MatchesFlags(member, flags) ? member : null; } #endregion #region Signatures public static IEnumerable<MethodInfo> WithSignature(this IEnumerable<MethodInfo> members, Type[] parameterTypes) { return members.Where(c => { var ps = c.GetParameters(); if (ps.Length != parameterTypes.Length) { return false; } for (int i = 0; i < ps.Length; i++) { if (parameterTypes[i] != ps[i].ParameterType) { return false; } } return true; }); } public static IEnumerable<ConstructorInfo> WithSignature(this IEnumerable<ConstructorInfo> members, Type[] parameterTypes) { return members.Where(c => { var ps = c.GetParameters(); if (ps.Length != parameterTypes.Length) { return false; } for (int i = 0; i < ps.Length; i++) { if (parameterTypes[i] != ps[i].ParameterType) { return false; } } return true; }); } #endregion #region Member Inheritance // CLI specification, partition I, 8.10.4: Hiding, overriding, and layout // ---------------------------------------------------------------------- // While hiding applies to all members of a type, overriding deals with object layout and is applicable only to instance fields // and virtual methods. The CTS provides two forms of member overriding, new slot and expect existing slot. A member of a derived // type that is marked as a new slot will always get a new slot in the object's layout, guaranteeing that the base field or method // is available in the object by using a qualified reference that combines the name of the base type with the name of the member // and its type or signature. A member of a derived type that is marked as expect existing slot will re-use (i.e., share or override) // a slot that corresponds to a member of the same kind (field or method), name, and type if one already exists from the base type; // if no such slot exists, a new slot is allocated and used. // // The general algorithm that is used for determining the names in a type and the layout of objects of the type is roughly as follows: // - Flatten the inherited names (using the hide by name or hide by name-and-signature rule) ignoring accessibility rules. // - For each new member that is marked "expect existing slot", look to see if an exact match on kind (i.e., field or method), // name, and signature exists and use that slot if it is found, otherwise allocate a new slot. // - After doing this for all new members, add these new member-kind/name/signatures to the list of members of this type // - Finally, remove any inherited names that match the new members based on the hide by name or hide by name-and-signature rules. // NOTE: Following GetXxx only implement overriding, not hiding specified by hide-by-name or hide-by-name-and-signature flags. public static IEnumerable<MethodInfo> GetInheritedMethods(this Type type, string name = null, bool flattenHierarchy = false) { while (type.IsGenericParameter) { type = type.BaseType; } var baseDefinitions = new HashSet<MethodInfo>(ReferenceEqualityComparer<MethodInfo>.Instance); foreach (var ancestor in type.Ancestors()) { foreach (var declaredMethod in ancestor.GetDeclaredMethods(name)) { if (declaredMethod != null && IncludeMethod(declaredMethod, type, baseDefinitions, flattenHierarchy)) { yield return declaredMethod; } } } } private static bool IncludeMethod(MethodInfo member, Type reflectedType, HashSet<MethodInfo> baseDefinitions, bool flattenHierarchy) { if (member.IsVirtual) { if (baseDefinitions.Add(RuntimeReflectionExtensions.GetRuntimeBaseDefinition(member))) { return true; } } else if (member.DeclaringType == reflectedType) { return true; } else if (!member.IsPrivate && (!member.IsStatic || flattenHierarchy)) { return true; } return false; } public static IEnumerable<PropertyInfo> GetInheritedProperties(this Type type, string name = null, bool flattenHierarchy = false) { while (type.IsGenericParameter) { type = type.BaseType; } var baseDefinitions = new HashSet<MethodInfo>(ReferenceEqualityComparer<MethodInfo>.Instance); foreach (var ancestor in type.Ancestors()) { if (name != null) { var declaredProperty = ancestor.GetDeclaredProperty(name); if (declaredProperty != null && IncludeProperty(declaredProperty, type, baseDefinitions, flattenHierarchy)) { yield return declaredProperty; } } else { foreach (var declaredProperty in ancestor.GetDeclaredProperties()) { if (IncludeProperty(declaredProperty, type, baseDefinitions, flattenHierarchy)) { yield return declaredProperty; } } } } } // CLI spec 22.34 Properties // ------------------------- // [Note: The CLS (see Partition I) refers to instance, virtual, and static properties. // The signature of a property (from the Type column) can be used to distinguish a static property, // since instance and virtual properties will have the "HASTHIS" bit set in the signature (§23.2.1) // while a static property will not. The distinction between an instance and a virtual property // depends on the signature of the getter and setter methods, which the CLS requires to be either // both virtual or both instance. end note] private static bool IncludeProperty(PropertyInfo member, Type reflectedType, HashSet<MethodInfo> baseDefinitions, bool flattenHierarchy) { var getter = member.GetGetMethod(nonPublic: true); var setter = member.GetSetMethod(nonPublic: true); MethodInfo virtualAccessor; if (getter != null && getter.IsVirtual) { virtualAccessor = getter; } else if (setter != null && setter.IsVirtual) { virtualAccessor = setter; } else { virtualAccessor = null; } if (virtualAccessor != null) { if (baseDefinitions.Add(RuntimeReflectionExtensions.GetRuntimeBaseDefinition(virtualAccessor))) { return true; } } else if (member.DeclaringType == reflectedType) { return true; } else if (!member.IsPrivate() && (!member.IsStatic() || flattenHierarchy)) { return true; } return false; } public static IEnumerable<EventInfo> GetInheritedEvents(this Type type, string name = null, bool flattenHierarchy = false) { while (type.IsGenericParameter) { type = type.BaseType; } var baseDefinitions = new HashSet<MethodInfo>(ReferenceEqualityComparer<MethodInfo>.Instance); foreach (var ancestor in type.Ancestors()) { if (name != null) { var declaredEvent = ancestor.GetDeclaredEvent(name); if (declaredEvent != null && IncludeEvent(declaredEvent, type, baseDefinitions, flattenHierarchy)) { yield return declaredEvent; } } else { foreach (var declaredEvent in ancestor.GetDeclaredEvents()) { if (IncludeEvent(declaredEvent, type, baseDefinitions, flattenHierarchy)) { yield return declaredEvent; } } } } } private static bool IncludeEvent(EventInfo member, Type reflectedType, HashSet<MethodInfo> baseDefinitions, bool flattenHierarchy) { var add = member.GetAddMethod(nonPublic: true); var remove = member.GetRemoveMethod(nonPublic: true); // TOOD: fire method? MethodInfo virtualAccessor; if (add != null && add.IsVirtual) { virtualAccessor = add; } else if (remove != null && remove.IsVirtual) { virtualAccessor = remove; } else { virtualAccessor = null; } if (virtualAccessor != null) { if (baseDefinitions.Add(RuntimeReflectionExtensions.GetRuntimeBaseDefinition(virtualAccessor))) { return true; } } else if (member.DeclaringType == reflectedType) { return true; } else if (!member.IsPrivate() && (!member.IsStatic() || flattenHierarchy)) { return true; } return false; } public static IEnumerable<FieldInfo> GetInheritedFields(this Type type, string name = null, bool flattenHierarchy = false) { while (type.IsGenericParameter) { type = type.BaseType; } foreach (var ancestor in type.Ancestors()) { if (name != null) { var declaredField = ancestor.GetDeclaredField(name); if (declaredField != null && IncludeField(declaredField, type, flattenHierarchy)) { yield return declaredField; } } else { foreach (var declaredField in ancestor.GetDeclaredFields()) { if (IncludeField(declaredField, type, flattenHierarchy)) { yield return declaredField; } } } } } private static bool IncludeField(FieldInfo member, Type reflectedType, bool flattenHierarchy) { if (member.DeclaringType == reflectedType) { return true; } if (!member.IsPrivate && (!member.IsStatic || flattenHierarchy)) { return true; } return false; } public static IEnumerable<MemberInfo> GetInheritedMembers(this Type type, string name = null, bool flattenHierarchy = false) { var result = type.GetInheritedMethods(name, flattenHierarchy).Cast<MethodInfo, MemberInfo>().Concat( type.GetInheritedProperties(name, flattenHierarchy).Cast<PropertyInfo, MemberInfo>().Concat( type.GetInheritedEvents(name, flattenHierarchy).Cast<EventInfo, MemberInfo>().Concat( type.GetInheritedFields(name, flattenHierarchy).Cast<FieldInfo, MemberInfo>()))); if (name == null) { return result.Concat<MemberInfo>( type.GetDeclaredConstructors().Cast<ConstructorInfo, MemberInfo>().Concat( type.GetDeclaredNestedTypes().Cast<TypeInfo, MemberInfo>())); } var nestedType = type.GetDeclaredNestedType(name); return (nestedType != null) ? result.Concat(new[] { nestedType }) : result; } #endregion #region Declared Members public static IEnumerable<ConstructorInfo> GetDeclaredConstructors(this Type type) { return type.GetConstructors(BindingFlags.DeclaredOnly | AllMembers); } public static IEnumerable<MethodInfo> GetDeclaredMethods(this Type type, string name = null) { if (name == null) { return type.GetMethods(BindingFlags.DeclaredOnly | AllMembers); } return type.GetMember(name, MemberTypes.Method, BindingFlags.DeclaredOnly | AllMembers).OfType<MethodInfo>(); } public static IEnumerable<PropertyInfo> GetDeclaredProperties(this Type type) { return type.GetProperties(BindingFlags.DeclaredOnly | AllMembers); } public static PropertyInfo GetDeclaredProperty(this Type type, string name) { Debug.Assert(name != null); return type.GetProperty(name, BindingFlags.DeclaredOnly | AllMembers); } public static IEnumerable<EventInfo> GetDeclaredEvents(this Type type) { return type.GetEvents(BindingFlags.DeclaredOnly | AllMembers); } public static EventInfo GetDeclaredEvent(this Type type, string name) { Debug.Assert(name != null); return type.GetEvent(name, BindingFlags.DeclaredOnly | AllMembers); } public static IEnumerable<FieldInfo> GetDeclaredFields(this Type type) { return type.GetFields(BindingFlags.DeclaredOnly | AllMembers); } public static FieldInfo GetDeclaredField(this Type type, string name) { Debug.Assert(name != null); return type.GetField(name, BindingFlags.DeclaredOnly | AllMembers); } public static IEnumerable<TypeInfo> GetDeclaredNestedTypes(this Type type) { return type.GetNestedTypes(BindingFlags.DeclaredOnly | AllMembers); } public static TypeInfo GetDeclaredNestedType(this Type type, string name) { Debug.Assert(name != null); return type.GetNestedType(name, BindingFlags.DeclaredOnly | AllMembers); } public static IEnumerable<MemberInfo> GetDeclaredMembers(this Type type, string name = null) { if (name == null) { return type.GetMembers(BindingFlags.DeclaredOnly | AllMembers); } return type.GetMember(name, BindingFlags.DeclaredOnly | AllMembers); } #endregion public static Type[] GetGenericTypeArguments(this Type type) { return type.IsGenericType && !type.IsGenericTypeDefinition ? type.GetGenericArguments() : null; } public static Type[] GetGenericTypeParameters(this Type type) { return type.IsGenericTypeDefinition ? type.GetGenericArguments() : null; } [Obsolete("Use Assembly.GetModules directly instead.")] public static IEnumerable<Module> GetModules(this Assembly assembly) { return assembly.GetModules(); } [Obsolete("Use Type.GetInterfaces directly instead.")] public static IEnumerable<Type> GetImplementedInterfaces(this Type type) { return type.GetInterfaces(); } public static TypeCode GetTypeCode(this Type type) { return Type.GetTypeCode(type); } [Obsolete("Use Delegate.GetMethodInfo directly instead.")] public static MethodInfo GetMethod(this Delegate d) { return d.GetMethodInfo(); } public static bool IsDefined(this Assembly assembly, Type attributeType) { return assembly.IsDefined(attributeType, false); } public static T GetCustomAttribute<T>(this Assembly assembly, bool inherit = false) where T : Attribute { return (T)Attribute.GetCustomAttribute(assembly, typeof(T), inherit); } public static T GetCustomAttribute<T>(this MemberInfo member, bool inherit = false) where T : Attribute { return (T)Attribute.GetCustomAttribute(member, typeof(T), inherit); } [Obsolete("Use Type.ContainsGenericParameters directly instead.")] public static bool ContainsGenericParameters(this Type type) { return type.ContainsGenericParameters; } [Obsolete("Use Type.IsInterface directly instead.")] public static bool IsInterface(this Type type) { return type.IsInterface; } [Obsolete("Use Type.IsClass directly instead.")] public static bool IsClass(this Type type) { return type.IsClass; } [Obsolete("Use Type.IsGenericType directly instead.")] public static bool IsGenericType(this Type type) { return type.IsGenericType; } [Obsolete("Use Type.IsGenericTypeDefinition directly instead.")] public static bool IsGenericTypeDefinition(this Type type) { return type.IsGenericTypeDefinition; } [Obsolete("Use Type.IsSealed directly instead.")] public static bool IsSealed(this Type type) { return type.IsSealed; } [Obsolete("Use Type.IsAbstract directly instead.")] public static bool IsAbstract(this Type type) { return type.IsAbstract; } [Obsolete("Use Type.IsPublic directly instead.")] public static bool IsPublic(this Type type) { return type.IsPublic; } [Obsolete("Use Type.IsVisible directly instead.")] public static bool IsVisible(this Type type) { return type.IsVisible; } [Obsolete("Use Type.BaseType directly instead.")] public static Type GetBaseType(this Type type) { return type.BaseType; } [Obsolete("Use Type.IsValueType directly instead.")] public static bool IsValueType(this Type type) { return type.IsValueType; } [Obsolete("Use Type.IsEnum directly instead.")] public static bool IsEnum(this Type type) { return type.IsEnum; } [Obsolete("Use Type.IsPrimitive directly instead.")] public static bool IsPrimitive(this Type type) { return type.IsPrimitive; } [Obsolete("Use Type.GenericParameterAttributes directly instead.")] public static GenericParameterAttributes GetGenericParameterAttributes(this Type type) { return type.GenericParameterAttributes; } public static readonly Type[] EmptyTypes = new Type[0]; public static object GetRawConstantValue(this FieldInfo field) { if (!field.IsLiteral) { throw new ArgumentException(field + " not a literal."); } object value = field.GetValue(null); return field.FieldType.IsEnum ? UnwrapEnumValue(value) : value; } /// <summary> /// Converts a boxed enum value to the underlying integer value. /// </summary> public static object UnwrapEnumValue(object value) { if (value == null) { throw new ArgumentNullException(nameof(value)); } switch (value.GetType().GetTypeCode()) { case TypeCode.Byte: return Convert.ToByte(value); case TypeCode.Int16: return Convert.ToInt16(value); case TypeCode.Int32: return Convert.ToInt32(value); case TypeCode.Int64: return Convert.ToInt64(value); case TypeCode.SByte: return Convert.ToSByte(value); case TypeCode.UInt16: return Convert.ToUInt16(value); case TypeCode.UInt32: return Convert.ToUInt32(value); case TypeCode.UInt64: return Convert.ToUInt64(value); default: throw new ArgumentException("Value must be a boxed enum.", nameof(value)); } } #if FEATURE_REFEMIT #if FEATURE_ASSEMBLYBUILDER_DEFINEDYNAMICASSEMBLY public static AssemblyBuilder DefineDynamicAssembly(AssemblyName name, AssemblyBuilderAccess access) { return AssemblyBuilder.DefineDynamicAssembly(name, access); } #else public static AssemblyBuilder DefineDynamicAssembly(AssemblyName name, AssemblyBuilderAccess access) { return AppDomain.CurrentDomain.DefineDynamicAssembly(name, access); } #endif #if !FEATURE_PDBEMIT public static ModuleBuilder DefineDynamicModule(this AssemblyBuilder assembly, string name, bool emitDebugInfo) { // ignore the flag return assembly.DefineDynamicModule(name); } #endif #endif #region Signature and Type Formatting // Generic type names have the arity (number of generic type paramters) appended at the end. // For eg. the mangled name of System.List<T> is "List`1". This mangling is done to enable multiple // generic types to exist as long as they have different arities. public const char GenericArityDelimiter = '`'; public static StringBuilder FormatSignature(StringBuilder result, MethodBase method) { return FormatSignature(result, method, t => t.FullName); } public static StringBuilder FormatSignature(StringBuilder result, MethodBase method, Func<Type, string> nameDispenser) { ContractUtils.RequiresNotNull(result, nameof(result)); ContractUtils.RequiresNotNull(method, nameof(method)); ContractUtils.RequiresNotNull(nameDispenser, nameof(nameDispenser)); MethodInfo methodInfo = method as MethodInfo; if (methodInfo != null) { FormatTypeName(result, methodInfo.ReturnType, nameDispenser); result.Append(' '); } #if FEATURE_REFEMIT && FEATURE_REFEMIT_FULL MethodBuilder builder = method as MethodBuilder; if (builder != null) { result.Append(builder.Signature); return result; } ConstructorBuilder cb = method as ConstructorBuilder; if (cb != null) { result.Append(cb.Signature); return result; } #endif FormatTypeName(result, method.DeclaringType, nameDispenser); result.Append("::"); result.Append(method.Name); if (!method.IsConstructor) { FormatTypeArgs(result, method.GetGenericArguments(), nameDispenser); } result.Append("("); if (!method.ContainsGenericParameters) { ParameterInfo[] ps = method.GetParameters(); for (int i = 0; i < ps.Length; i++) { if (i > 0) result.Append(", "); FormatTypeName(result, ps[i].ParameterType, nameDispenser); if (!System.String.IsNullOrEmpty(ps[i].Name)) { result.Append(" "); result.Append(ps[i].Name); } } } else { result.Append("?"); } result.Append(")"); return result; } public static StringBuilder FormatTypeName(StringBuilder result, Type type) { return FormatTypeName(result, type, t => t.FullName); } public static StringBuilder FormatTypeName(StringBuilder result, Type type, Func<Type, string> nameDispenser) { ContractUtils.RequiresNotNull(result, nameof(result)); ContractUtils.RequiresNotNull(type, nameof(type)); ContractUtils.RequiresNotNull(nameDispenser, nameof(nameDispenser)); if (type.IsGenericType) { Type genType = type.GetGenericTypeDefinition(); string genericName = nameDispenser(genType).Replace('+', '.'); int tickIndex = genericName.IndexOf('`'); result.Append(tickIndex != -1 ? genericName.Substring(0, tickIndex) : genericName); Type[] typeArgs = type.GetGenericArguments(); if (type.IsGenericTypeDefinition) { result.Append('<'); result.Append(',', typeArgs.Length - 1); result.Append('>'); } else { FormatTypeArgs(result, typeArgs, nameDispenser); } } else if (type.IsGenericParameter) { result.Append(type.Name); } else { // cut namespace off: result.Append(nameDispenser(type).Replace('+', '.')); } return result; } public static StringBuilder FormatTypeArgs(StringBuilder result, Type[] types) { return FormatTypeArgs(result, types, (t) => t.FullName); } public static StringBuilder FormatTypeArgs(StringBuilder result, Type[] types, Func<Type, string> nameDispenser) { ContractUtils.RequiresNotNull(result, nameof(result)); ContractUtils.RequiresNotNullItems(types, nameof(types)); ContractUtils.RequiresNotNull(nameDispenser, nameof(nameDispenser)); if (types.Length > 0) { result.Append("<"); for (int i = 0; i < types.Length; i++) { if (i > 0) result.Append(", "); FormatTypeName(result, types[i], nameDispenser); } result.Append(">"); } return result; } internal static string ToValidTypeName(string str) { if (String.IsNullOrEmpty(str)) { return "_"; } StringBuilder sb = new StringBuilder(str); for (int i = 0; i < str.Length; i++) { if (str[i] == '\0' || str[i] == '.' || str[i] == '*' || str[i] == '+' || str[i] == '[' || str[i] == ']' || str[i] == '\\') { sb[i] = '_'; } } return sb.ToString(); } public static string GetNormalizedTypeName(Type type) { string name = type.Name; if (type.IsGenericType) { return GetNormalizedTypeName(name); } return name; } public static string GetNormalizedTypeName(string typeName) { Debug.Assert(typeName.IndexOf('.') == -1); // This is the simple name, not the full name int backtick = typeName.IndexOf(GenericArityDelimiter); if (backtick != -1) return typeName.Substring(0, backtick); return typeName; } #endregion #region Delegates and Dynamic Methods /// <summary> /// Creates an open delegate for the given (dynamic)method. /// </summary> public static Delegate CreateDelegate(this MethodInfo methodInfo, Type delegateType) { return CreateDelegate(methodInfo, delegateType, null); } /// <summary> /// Creates a closed delegate for the given (dynamic)method. /// </summary> public static Delegate CreateDelegate(this MethodInfo methodInfo, Type delegateType, object target) { #if FEATURE_LCG if (methodInfo is DynamicMethod dm) { return dm.CreateDelegate(delegateType, target); } #endif return Delegate.CreateDelegate(delegateType, target, methodInfo); } #if FEATURE_LCG public static bool IsDynamicMethod(MethodBase method) => IsDynamicMethodInternal(method); [MethodImpl(MethodImplOptions.NoInlining)] private static bool IsDynamicMethodInternal(MethodBase method) { return method is DynamicMethod; } #else public static bool IsDynamicMethod(MethodBase method) { return false; } #endif public static void GetDelegateSignature(Type delegateType, out ParameterInfo[] parameterInfos, out ParameterInfo returnInfo) { ContractUtils.RequiresNotNull(delegateType, nameof(delegateType)); MethodInfo invokeMethod = delegateType.GetMethod("Invoke"); ContractUtils.Requires(invokeMethod != null, nameof(delegateType), Strings.InvalidDelegate); parameterInfos = invokeMethod.GetParameters(); returnInfo = invokeMethod.ReturnParameter; } /// <summary> /// Gets a Func of CallSite, object * paramCnt, object delegate type /// that's suitable for use in a non-strongly typed call site. /// </summary> public static Type GetObjectCallSiteDelegateType(int paramCnt) { switch (paramCnt) { case 0: return typeof(Func<CallSite, object, object>); case 1: return typeof(Func<CallSite, object, object, object>); case 2: return typeof(Func<CallSite, object, object, object, object>); case 3: return typeof(Func<CallSite, object, object, object, object, object>); case 4: return typeof(Func<CallSite, object, object, object, object, object, object>); case 5: return typeof(Func<CallSite, object, object, object, object, object, object, object>); case 6: return typeof(Func<CallSite, object, object, object, object, object, object, object, object>); case 7: return typeof(Func<CallSite, object, object, object, object, object, object, object, object, object>); case 8: return typeof(Func<CallSite, object, object, object, object, object, object, object, object, object, object>); case 9: return typeof(Func<CallSite, object, object, object, object, object, object, object, object, object, object, object>); case 10: return typeof(Func<CallSite, object, object, object, object, object, object, object, object, object, object, object, object>); case 11: return typeof(Func<CallSite, object, object, object, object, object, object, object, object, object, object, object, object, object>); case 12: return typeof(Func<CallSite, object, object, object, object, object, object, object, object, object, object, object, object, object, object>); case 13: return typeof(Func<CallSite, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object>); case 14: return typeof(Func<CallSite, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object>); default: #if FEATURE_REFEMIT Type[] paramTypes = new Type[paramCnt + 2]; paramTypes[0] = typeof(CallSite); paramTypes[1] = typeof(object); for (int i = 0; i < paramCnt; i++) { paramTypes[i + 2] = typeof(object); } return Snippets.Shared.DefineDelegate("InvokeDelegate" + paramCnt, typeof(object), paramTypes); #else throw new NotSupportedException("Signature not supported on this platform."); #endif } } #if FEATURE_LCG [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Portability", "CA1903:UseOnlyApiFromTargetedFramework")] internal static DynamicMethod RawCreateDynamicMethod(string name, Type returnType, Type[] parameterTypes) { // // WARNING: we set restrictedSkipVisibility == true (last parameter) // setting this bit will allow accessing nonpublic members // for more information see http://msdn.microsoft.com/en-us/library/bb348332.aspx // return new DynamicMethod(name, returnType, parameterTypes, true); } #endif #endregion #region Methods and Parameters public static MethodBase[] GetMethodInfos(MemberInfo[] members) { return ArrayUtils.ConvertAll<MemberInfo, MethodBase>( members, delegate (MemberInfo inp) { return (MethodBase)inp; }); } public static Type[] GetParameterTypes(ParameterInfo[] parameterInfos) { return GetParameterTypes((IList<ParameterInfo>)parameterInfos); } public static Type[] GetParameterTypes(IList<ParameterInfo> parameterInfos) { Type[] result = new Type[parameterInfos.Count]; for (int i = 0; i < result.Length; i++) { result[i] = parameterInfos[i].ParameterType; } return result; } public static Type GetReturnType(this MethodBase mi) { return (mi.IsConstructor) ? mi.DeclaringType : ((MethodInfo)mi).ReturnType; } public static bool SignatureEquals(MethodInfo method, params Type[] requiredSignature) { ContractUtils.RequiresNotNull(method, nameof(method)); Type[] actualTypes = GetParameterTypes(method.GetParameters()); Debug.Assert(actualTypes.Length == requiredSignature.Length - 1); int i = 0; while (i < actualTypes.Length) { if (actualTypes[i] != requiredSignature[i]) return false; i++; } return method.ReturnType == requiredSignature[i]; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] public static bool IsExtension(this MemberInfo member) { var dlrExtension = typeof(ExtensionAttribute); if (member.IsDefined(dlrExtension, false)) { return true; } return false; } public static bool IsOutParameter(this ParameterInfo pi) { // not using IsIn/IsOut properties as they are not available in Silverlight: return pi.ParameterType.IsByRef && (pi.Attributes & (ParameterAttributes.Out | ParameterAttributes.In)) == ParameterAttributes.Out; } /// <summary> /// Returns <c>true</c> if the specified parameter is mandatory, i.e. is not optional and doesn't have a default value. /// </summary> public static bool IsMandatory(this ParameterInfo pi) { return (pi.Attributes & ParameterAttributes.Optional) == 0 && !pi.HasDefaultValue(); } public static bool HasDefaultValue(this ParameterInfo pi) { return (pi.Attributes & ParameterAttributes.HasDefault) != 0; } public static bool ProhibitsNull(this ParameterInfo parameter) { return parameter.IsDefined(typeof(NotNullAttribute), false); } public static bool ProhibitsNullItems(this ParameterInfo parameter) { return parameter.IsDefined(typeof(NotNullItemsAttribute), false); } public static bool IsParamArray(this ParameterInfo parameter) { return parameter.IsDefined(typeof(ParamArrayAttribute), false); } public static bool IsParamDictionary(this ParameterInfo parameter) { return parameter.IsDefined(typeof(ParamDictionaryAttribute), false); } public static bool IsParamsMethod(MethodBase method) { return IsParamsMethod(method.GetParameters()); } public static bool IsParamsMethod(ParameterInfo[] pis) { foreach (ParameterInfo pi in pis) { if (pi.IsParamArray() || pi.IsParamDictionary()) return true; } return false; } public static object GetDefaultValue(this ParameterInfo info) { return info.DefaultValue; } #endregion #region Types /// <summary> /// Yields all ancestors of the given type including the type itself. /// Does not include implemented interfaces. /// </summary> public static IEnumerable<Type> Ancestors(this Type type) { do { yield return type; type = type.BaseType; } while (type != null); } /// <summary> /// Like Type.GetInterfaces, but only returns the interfaces implemented by this type /// and not its parents. /// </summary> public static List<Type> GetDeclaredInterfaces(Type type) { IEnumerable<Type> baseInterfaces = (type.BaseType != null) ? type.BaseType.GetInterfaces() : EmptyTypes; List<Type> interfaces = new List<Type>(); foreach (Type iface in type.GetInterfaces()) { if (!baseInterfaces.Contains(iface)) { interfaces.Add(iface); } } return interfaces; } internal static IEnumerable<TypeInfo> GetAllTypesFromAssembly(Assembly asm) { // TODO: WP7, SL5 foreach (Module module in asm.GetModules()) { Type[] moduleTypes; try { moduleTypes = module.GetTypes(); } catch (ReflectionTypeLoadException e) { moduleTypes = e.Types; } foreach (var type in moduleTypes) { if (type != null) { yield return type; } } } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] internal static IEnumerable<TypeInfo> GetAllTypesFromAssembly(Assembly assembly, bool includePrivateTypes) { ContractUtils.RequiresNotNull(assembly, nameof(assembly)); if (includePrivateTypes) { return GetAllTypesFromAssembly(assembly); } try { var exportedTypes = assembly.GetExportedTypes(); #if FEATURE_ASSEMBLY_GETFORWARDEDTYPES try { var forwardedTypes = assembly.GetForwardedTypes(); return Enumerable.Concat(exportedTypes, forwardedTypes); } catch (ReflectionTypeLoadException ex) { // GetForwardedTypes can throw if an assembly failed to load. In this case add the types // which successfully loaded. Note that Types may include null so we need to filter it out. return Enumerable.Concat(exportedTypes, ex.Types.OfType<Type>()); } #else return exportedTypes; #endif } catch (NotSupportedException) { // GetExportedTypes does not work with dynamic assemblies } catch (Exception) { // Some type loads may cause exceptions. Unfortunately, there is no way to ask GetExportedTypes // for just the list of types that we successfully loaded. } return GetAllTypesFromAssembly(assembly).Where(type => type.IsPublic); } #endregion #region Type Builder #if FEATURE_REFEMIT private const MethodAttributes MethodAttributesToEraseInOveride = MethodAttributes.Abstract | MethodAttributes.ReservedMask; public static MethodBuilder DefineMethodOverride(TypeBuilder tb, MethodAttributes extra, MethodInfo decl) { MethodAttributes finalAttrs = (decl.Attributes & ~MethodAttributesToEraseInOveride) | extra; if (!decl.DeclaringType.IsInterface) { finalAttrs &= ~MethodAttributes.NewSlot; } if ((extra & MethodAttributes.MemberAccessMask) != 0) { // remove existing member access, add new member access finalAttrs &= ~MethodAttributes.MemberAccessMask; finalAttrs |= extra; } MethodBuilder impl = tb.DefineMethod(decl.Name, finalAttrs, decl.CallingConvention); CopyMethodSignature(decl, impl, false); return impl; } public static void CopyMethodSignature(MethodInfo from, MethodBuilder to, bool substituteDeclaringType) { ParameterInfo[] paramInfos = from.GetParameters(); Type[] parameterTypes = new Type[paramInfos.Length]; Type[][] parameterRequiredModifiers = null, parameterOptionalModifiers = null; Type[] returnRequiredModifiers = null, returnOptionalModifiers = null; returnRequiredModifiers = from.ReturnParameter.GetRequiredCustomModifiers(); returnOptionalModifiers = from.ReturnParameter.GetOptionalCustomModifiers(); for (int i = 0; i < paramInfos.Length; i++) { if (substituteDeclaringType && paramInfos[i].ParameterType == from.DeclaringType) { parameterTypes[i] = to.DeclaringType; } else { parameterTypes[i] = paramInfos[i].ParameterType; } var mods = paramInfos[i].GetRequiredCustomModifiers(); if (mods.Length > 0) { if (parameterRequiredModifiers == null) { parameterRequiredModifiers = new Type[paramInfos.Length][]; } parameterRequiredModifiers[i] = mods; } mods = paramInfos[i].GetOptionalCustomModifiers(); if (mods.Length > 0) { if (parameterOptionalModifiers == null) { parameterOptionalModifiers = new Type[paramInfos.Length][]; } parameterOptionalModifiers[i] = mods; } } to.SetSignature( from.ReturnType, returnRequiredModifiers, returnOptionalModifiers, parameterTypes, parameterRequiredModifiers, parameterOptionalModifiers ); CopyGenericMethodAttributes(from, to); for (int i = 0; i < paramInfos.Length; i++) { var parameterBuilder = to.DefineParameter(i + 1, paramInfos[i].Attributes, paramInfos[i].Name); try { // ParameterBuilder.SetConstant is buggy and may fail on Mono if (paramInfos[i].HasDefaultValue) parameterBuilder.SetConstant(paramInfos[i].RawDefaultValue); } catch { } } } private static void CopyGenericMethodAttributes(MethodInfo from, MethodBuilder to) { if (from.IsGenericMethodDefinition) { Type[] args = from.GetGenericArguments(); string[] names = new string[args.Length]; for (int i = 0; i < args.Length; i++) { names[i] = args[i].Name; } var builders = to.DefineGenericParameters(names); for (int i = 0; i < args.Length; i++) { // Copy template parameter attributes builders[i].SetGenericParameterAttributes(args[i].GenericParameterAttributes); // Copy template parameter constraints Type[] constraints = args[i].GetGenericParameterConstraints(); List<Type> interfaces = new List<Type>(constraints.Length); foreach (Type constraint in constraints) { if (constraint.IsInterface) { interfaces.Add(constraint); } else { builders[i].SetBaseTypeConstraint(constraint); } } if (interfaces.Count > 0) { builders[i].SetInterfaceConstraints(interfaces.ToArray()); } } } } #endif #endregion #region Extension Methods public static IEnumerable<MethodInfo> GetVisibleExtensionMethods(Assembly assembly) { #if FEATURE_METADATA_READER if (!assembly.IsDynamic && AppDomain.CurrentDomain.IsFullyTrusted) { try { return GetVisibleExtensionMethodsFast(assembly); } catch (SecurityException) { // full-demand can still fail if there is a partial trust domain on the stack } } #endif return GetVisibleExtensionMethodsSlow(assembly); } #if FEATURE_METADATA_READER [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2116:AptcaMethodsShouldOnlyCallAptcaMethods")] [MethodImpl(MethodImplOptions.NoInlining)] private static IEnumerable<MethodInfo> GetVisibleExtensionMethodsFast(Assembly assembly) { // Security: link demand return MetadataServices.GetVisibleExtensionMethodInfos(assembly); } #endif // TODO: make internal // TODO: handle type load exceptions public static IEnumerable<MethodInfo> GetVisibleExtensionMethodsSlow(Assembly assembly) { var ea = typeof(ExtensionAttribute); if (assembly.IsDefined(ea)) { foreach (TypeInfo type in GetAllTypesFromAssembly(assembly)) { if ((type.IsPublic || type.IsNestedPublic) && type.IsAbstract && type.IsSealed && type.IsDefined(ea, false)) { foreach (MethodInfo method in type.GetDeclaredMethods()) { if (method.IsPublic && method.IsStatic && method.IsDefined(ea, false)) { yield return method; } } } } } } // Value is null if there are no extension methods in the assembly. private static Dictionary<Assembly, Dictionary<string, List<ExtensionMethodInfo>>> _extensionMethodsCache; /// <summary> /// Enumerates extension methods in given assembly. Groups the methods by declaring namespace. /// Uses a global cache if <paramref name="useCache"/> is true. /// </summary> public static IEnumerable<KeyValuePair<string, IEnumerable<ExtensionMethodInfo>>> GetVisibleExtensionMethodGroups(Assembly/*!*/ assembly, bool useCache) { #if FEATURE_REFEMIT useCache &= !assembly.IsDynamic; #endif if (useCache) { if (_extensionMethodsCache == null) { _extensionMethodsCache = new Dictionary<Assembly, Dictionary<string, List<ExtensionMethodInfo>>>(); } lock (_extensionMethodsCache) { if (_extensionMethodsCache.TryGetValue(assembly, out Dictionary<string, List<ExtensionMethodInfo>> existing)) { return EnumerateExtensionMethods(existing); } } } Dictionary<string, List<ExtensionMethodInfo>> result = null; foreach (MethodInfo method in GetVisibleExtensionMethodsSlow(assembly)) { if (method.DeclaringType == null || method.DeclaringType.IsGenericTypeDefinition) { continue; } var parameters = method.GetParameters(); if (parameters.Length == 0) { continue; } Type type = parameters[0].ParameterType; if (type.IsByRef || type.IsPointer) { continue; } string ns = method.DeclaringType.Namespace ?? string.Empty; if (result == null) { result = new Dictionary<string, List<ExtensionMethodInfo>>(); } if (!result.TryGetValue(ns, out List<ExtensionMethodInfo> extensions)) { result.Add(ns, extensions = new List<ExtensionMethodInfo>()); } extensions.Add(new ExtensionMethodInfo(type, method)); } if (useCache) { lock (_extensionMethodsCache) { _extensionMethodsCache[assembly] = result; } } return EnumerateExtensionMethods(result); } // TODO: GetVisibleExtensionMethods(Hashset<string> namespaces, Type type, string methodName) : IEnumerable<MethodInfo> {} private static IEnumerable<KeyValuePair<string, IEnumerable<ExtensionMethodInfo>>> EnumerateExtensionMethods(Dictionary<string, List<ExtensionMethodInfo>> dict) { if (dict != null) { foreach (var entry in dict) { yield return new KeyValuePair<string, IEnumerable<ExtensionMethodInfo>>(entry.Key, new ReadOnlyCollection<ExtensionMethodInfo>(entry.Value)); } } } #endregion #region Generic Types internal static Dictionary<Type, Type> BindGenericParameters(Type/*!*/ openType, Type/*!*/ closedType, bool ignoreUnboundParameters) { var binding = new Dictionary<Type, Type>(); BindGenericParameters(openType, closedType, (parameter, type) => { if (binding.TryGetValue(parameter, out Type existing)) { return type == existing; } binding[parameter] = type; return true; }); return ConstraintsViolated(binding, ignoreUnboundParameters) ? null : binding; } /// <summary> /// Binds occurances of generic parameters in <paramref name="openType"/> against corresponding types in <paramref name="closedType"/>. /// Invokes <paramref name="binder"/>(parameter, type) for each such binding. /// Returns false if the <paramref name="openType"/> is structurally different from <paramref name="closedType"/> or if the binder returns false. /// </summary> internal static bool BindGenericParameters(Type/*!*/ openType, Type/*!*/ closedType, Func<Type, Type, bool>/*!*/ binder) { if (openType.IsGenericParameter) { return binder(openType, closedType); } if (openType.IsArray) { if (!closedType.IsArray) { return false; } return BindGenericParameters(openType.GetElementType(), closedType.GetElementType(), binder); } if (!openType.IsGenericType || !closedType.IsGenericType) { return openType == closedType; } if (openType.GetGenericTypeDefinition() != closedType.GetGenericTypeDefinition()) { return false; } Type[] closedArgs = closedType.GetGenericArguments(); Type[] openArgs = openType.GetGenericArguments(); for (int i = 0; i < openArgs.Length; i++) { if (!BindGenericParameters(openArgs[i], closedArgs[i], binder)) { return false; } } return true; } internal static bool ConstraintsViolated(Dictionary<Type, Type>/*!*/ binding, bool ignoreUnboundParameters) { foreach (var entry in binding) { if (ConstraintsViolated(entry.Key, entry.Value, binding, ignoreUnboundParameters)) { return true; } } return false; } internal static bool ConstraintsViolated(Type/*!*/ genericParameter, Type/*!*/ closedType, Dictionary<Type, Type>/*!*/ binding, bool ignoreUnboundParameters) { if ((genericParameter.GenericParameterAttributes & GenericParameterAttributes.ReferenceTypeConstraint) != 0 && closedType.IsValueType) { // value type to parameter type constrained as class return true; } if ((genericParameter.GenericParameterAttributes & GenericParameterAttributes.NotNullableValueTypeConstraint) != 0 && (!closedType.IsValueType || (closedType.IsGenericType && closedType.GetGenericTypeDefinition() == typeof(Nullable<>)))) { // nullable<T> or class/interface to parameter type constrained as struct return true; } if ((genericParameter.GenericParameterAttributes & GenericParameterAttributes.DefaultConstructorConstraint) != 0 && (!closedType.IsValueType && closedType.GetConstructor(EmptyTypes) == null)) { // reference type w/o a default constructor to type constrianed as new() return true; } Type[] constraints = genericParameter.GetGenericParameterConstraints(); for (int i = 0; i < constraints.Length; i++) { Type instantiation = InstantiateConstraint(constraints[i], binding); if (instantiation == null) { if (ignoreUnboundParameters) { continue; } return true; } if (!instantiation.IsAssignableFrom(closedType)) { return true; } } return false; } internal static Type InstantiateConstraint(Type/*!*/ constraint, Dictionary<Type, Type>/*!*/ binding) { Debug.Assert(!constraint.IsArray && !constraint.IsByRef && !constraint.IsGenericTypeDefinition); if (!constraint.ContainsGenericParameters) { return constraint; } Type closedType; if (constraint.IsGenericParameter) { return binding.TryGetValue(constraint, out closedType) ? closedType : null; } Type[] args = constraint.GetGenericArguments(); for (int i = 0; i < args.Length; i++) { if ((args[i] = InstantiateConstraint(args[i], binding)) == null) { return null; } } return constraint.GetGenericTypeDefinition().MakeGenericType(args); } #endregion } public struct ExtensionMethodInfo : IEquatable<ExtensionMethodInfo> { private readonly Type/*!*/ _extendedType; // cached type of the first parameter private readonly MethodInfo/*!*/ _method; internal ExtensionMethodInfo(Type/*!*/ extendedType, MethodInfo/*!*/ method) { Assert.NotNull(extendedType, method); _extendedType = extendedType; _method = method; } public Type/*!*/ ExtendedType { get { return _extendedType; } } public MethodInfo/*!*/ Method { get { return _method; } } public override bool Equals(object obj) => obj is ExtensionMethodInfo info && Equals(info); public bool Equals(ExtensionMethodInfo other) => _method.Equals(other._method); public static bool operator ==(ExtensionMethodInfo self, ExtensionMethodInfo other) => self.Equals(other); public static bool operator !=(ExtensionMethodInfo self, ExtensionMethodInfo other) => !self.Equals(other); public override int GetHashCode() { return _method.GetHashCode(); } /// <summary> /// Determines if a given type matches the type that the method extends. /// The match might be non-trivial if the extended type is an open generic type with constraints. /// </summary> public bool IsExtensionOf(Type/*!*/ type) { ContractUtils.RequiresNotNull(type, nameof(type)); #if FEATURE_TYPE_EQUIVALENCE if (type.IsEquivalentTo(ExtendedType)) { return true; } #else if (type == _extendedType) { return true; } #endif if (!_extendedType.ContainsGenericParameters) { return false; } // // Ignores constraints that can't be instantiated given the information we have (type of the first parameter). // // For example, // void Foo<S, T>(this S x, T y) where S : T; // // We make such methods available on all types. // If they are not called with arguments that satisfy the constraint the overload resolver might fail. // return ReflectionUtils.BindGenericParameters(_extendedType, type, true) != null; } } }
42.866007
183
0.592021
[ "Apache-2.0" ]
pyrevitlabs/dlr
Src/Microsoft.Dynamic/Utils/ReflectionUtils.cs
64,943
C#
using System; using Windows.UI.Xaml; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Media; namespace Chartreuse.Today.App.Tools.Converter { public class TaskForegroundConverter : IValueConverter { private static SolidColorBrush normalBrush; private static SolidColorBrush completedBrush; public object Convert(object value, Type targetType, object parameter, string language) { if (normalBrush == null) { normalBrush = Application.Current.Resources["TaskTitleForegroundBrush"] as SolidColorBrush; completedBrush = Application.Current.Resources["TaskTitleCompletedForegroundBrush"] as SolidColorBrush; } if (value is bool && (bool) value) return completedBrush; else return normalBrush; } public object ConvertBack(object value, Type targetType, object parameter, string language) { throw new NotImplementedException(); } } }
31.666667
119
0.64689
[ "MIT" ]
2DayApp/2day
src/2Day.App/Tools/Converter/TaskForegroundConverter.cs
1,047
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Extensions.DependencyInjection; namespace Microsoft.AspNetCore.Mvc.Controllers; /// <summary> /// A <see cref="IControllerActivator"/> that retrieves controllers as services from the request's /// <see cref="IServiceProvider"/>. /// </summary> public class ServiceBasedControllerActivator : IControllerActivator { /// <inheritdoc /> public object Create(ControllerContext actionContext) { if (actionContext == null) { throw new ArgumentNullException(nameof(actionContext)); } var controllerType = actionContext.ActionDescriptor.ControllerTypeInfo.AsType(); return actionContext.HttpContext.RequestServices.GetRequiredService(controllerType); } /// <inheritdoc /> public virtual void Release(ControllerContext context, object controller) { } }
30.8125
98
0.72211
[ "MIT" ]
3ejki/aspnetcore
src/Mvc/Mvc.Core/src/Controllers/ServiceBasedControllerActivator.cs
986
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; namespace ImageWizard.Analytics.Pages { public class StatsModel : PageModel { public StatsModel(IAnalyticsData analyticsData) { AnalyticsData = analyticsData; } public IAnalyticsData AnalyticsData { get; } public void OnGet() { } } }
20.375
55
0.670757
[ "MIT" ]
usercode/ImageWizard
src/ImageWizard.Analytics/Pages/Stats.cshtml.cs
489
C#
using System.Collections.ObjectModel; using System.Threading.Tasks; namespace twitch_tv_viewer.Repositories.Interfaces { public interface ISettingsRepository { string Quality { get; set; } bool UserAlert { get; set; } int SortBy { get; set; } string SortName { get; } int Width { get; set; } int Height { get; set; } bool PlayPromotedSound { get; set; } ObservableCollection<string> Usernames { get; set; } ObservableCollection<string> Important { get; set; } Task Save(); } }
20
60
0.612069
[ "MIT" ]
dukemiller/twitch-tv-viewer
twitch-tv-viewer/Repositories/Interfaces/ISettingsRepository.cs
582
C#
using System; using Adguard.Dns.Api.DnsProxyServer.Configs; using Adguard.Dns.DnsProxyServer; using Adguard.Dns.Exceptions; using Adguard.Dns.Logging; using Adguard.Dns.Utils; namespace Adguard.Dns.Api { /// <summary> /// Main API Facade object, which implements <see cref="IDnsApi"/>, /// and provides full functionality of Core Libs windows adapter /// </summary> public class DnsApi : IDnsApi { private static readonly ILog LOG = LogProvider.For<DnsApi>(); private static readonly object SYNC_ROOT = new object(); private IDnsProxyServer m_DnsProxyServer; private static readonly Lazy<IDnsApi> LAZY = new Lazy<IDnsApi> (() => new DnsApi()); private DnsProxySettings m_CurrentDnsProxySettings; #region Singleton /// <summary> /// Gets a singleton instance of <see cref="DnsApi"/> object /// </summary> public static IDnsApi Instance { get { return LAZY.Value; } } #endregion #region Filtering /// <summary> /// Starts DNS filtering /// </summary> /// <param name="dnsApiConfiguration">Dns proxy configuration /// (<seealso cref="DnsApiConfiguration"/>)</param> /// <exception cref="NotSupportedException">Thrown /// if current API version is not supported</exception> /// <exception cref="ArgumentNullException">Thrown, /// if <see cref="dnsApiConfiguration"/> is not specified</exception> /// <exception cref="InvalidOperationException">Thrown, if cannot starting the proxy server /// for any reason</exception> public void StartDnsFiltering(DnsApiConfiguration dnsApiConfiguration) { lock (SYNC_ROOT) { try { if (dnsApiConfiguration == null) { throw new ArgumentNullException( "dnsApiConfiguration", "dnsApiConfiguration is not specified"); } if (!dnsApiConfiguration.IsEnabled) { LOG.InfoFormat("DNS filtering is disabled, doing nothing"); return; } LOG.InfoFormat("Starting the DNS filtering"); m_DnsProxyServer = new Dns.DnsProxyServer.DnsProxyServer( dnsApiConfiguration.DnsProxySettings, dnsApiConfiguration.DnsProxyServerCallbackConfiguration); m_CurrentDnsProxySettings = dnsApiConfiguration.DnsProxySettings; m_DnsProxyServer.Start(); LOG.InfoFormat("Starting the DNS filtering has been successfully completed"); } catch (Exception ex) { LOG.ErrorFormat("Starting the DNS filtering failed with an error", ex); throw; } } } /// <summary> /// Stops the dns filtering /// If it is not started yet, does nothing. /// </summary> /// <exception cref="InvalidOperationException">Thrown, if cannot closing the proxy server /// for any reason</exception> public void StopDnsFiltering() { lock (SYNC_ROOT) { try { LOG.InfoFormat("Stopping the DNS filtering"); if (m_DnsProxyServer == null) { return; } m_DnsProxyServer.Stop(); m_DnsProxyServer = null; LOG.InfoFormat("Stopping the DNS filtering has been successfully completed"); } catch (Exception ex) { LOG.ErrorFormat("Stopping the DNS filtering failed with an error", ex); throw; } } } /// <summary> /// Reloads DNS filtering /// <param name="newDnsApiConfiguration">Dns proxy configuration /// (<seealso cref="DnsApiConfiguration"/>)</param> /// <param name="force">Determines, whether the DNS filtering must be reloaded, /// independently of whether configuration changed or not</param> /// <exception cref="ArgumentNullException">Thrown, if <see cref="newDnsApiConfiguration"/> /// is not specified</exception> /// <exception cref="ArgumentException">Thrown, if <see cref="DnsProxySettings"/> /// is not specified within the <see cref="newDnsApiConfiguration"/></exception> /// <exception cref="NotSupportedException">Thrown /// if current API version is not supported</exception> /// <exception cref="InvalidOperationException">Thrown, if cannot starting the proxy server /// for any reason</exception> /// <exception cref="InvalidOperationException">Thrown, if cannot closing the proxy server /// for any reason</exception> /// </summary> public void ReloadDnsFiltering(DnsApiConfiguration newDnsApiConfiguration, bool force) { lock (SYNC_ROOT) { IDnsProxyServer newDnsProxyServer = null; try { LOG.InfoFormat("Reloading the DNS filtering"); if (m_DnsProxyServer == null || m_CurrentDnsProxySettings == null) { LOG.InfoFormat( "Start DNS filtering, because the DNS server is not started and/or configurations are not set"); StartDnsFiltering(newDnsApiConfiguration); return; } if (newDnsApiConfiguration == null) { throw new ArgumentNullException( "newDnsApiConfiguration", "newDnsApiConfiguration is not specified"); } if (newDnsApiConfiguration.DnsProxySettings == null) { throw new ArgumentException( "DnsProxySettings is not initialized", "newDnsApiConfiguration"); } bool isConfigurationChanged = !m_CurrentDnsProxySettings.Equals(newDnsApiConfiguration.DnsProxySettings); if (!force && !isConfigurationChanged) { LOG.InfoFormat("The DNS server configuration hasn't been changed, no need to reload"); return; } newDnsProxyServer = new Dns.DnsProxyServer.DnsProxyServer( newDnsApiConfiguration.DnsProxySettings, newDnsApiConfiguration.DnsProxyServerCallbackConfiguration); m_DnsProxyServer.Stop(); m_DnsProxyServer = newDnsProxyServer; if (newDnsApiConfiguration.IsEnabled) { LOG.InfoFormat("DNS filtering is enabled, starting DNS proxy server"); m_DnsProxyServer.Start(); } m_CurrentDnsProxySettings = newDnsApiConfiguration.DnsProxySettings; LOG.InfoFormat("Reloading the DNS filtering has been successfully completed"); } catch (Exception ex) { LOG.ErrorFormat("Reloading the DNS filtering failed with an error", ex); if (newDnsProxyServer != null && newDnsProxyServer.IsStarted) { // if the new DNS proxy server has been already started we should stop it, // otherwise - let the existed proxy server works StopDnsFiltering(); } throw; } } } /// <summary> /// Gets the current DNS proxy settings as a <see cref="DnsProxySettings"/> object /// </summary> /// <returns>Current DNS proxy settings /// (<seealso cref="DnsProxySettings"/>)</returns> /// <exception cref="InvalidOperationException">Thrown, /// if cannot get the current dns proxy settings via native method</exception> public DnsProxySettings GetCurrentDnsProxySettings() { lock (SYNC_ROOT) { try { LOG.InfoFormat("Getting current DNS proxy settings"); if (m_DnsProxyServer == null) { return null; } DnsProxySettings dnsProxySettings = m_DnsProxyServer.GetCurrentDnsProxySettings(); LOG.InfoFormat("Getting current DNS proxy settings has been successfully completed"); return dnsProxySettings; } catch (Exception ex) { LOG.ErrorFormat("Getting current DNS proxy settings failed with an error", ex); throw; } } } /// <summary> /// Gets the default DNS proxy settings as a <see cref="DnsProxySettings"/> object /// </summary> /// <returns>Current DNS proxy settings /// (<seealso cref="DnsProxySettings"/>)</returns> /// <exception cref="InvalidOperationException">Thrown, /// if cannot get the default dns proxy settings via native method</exception> public DnsProxySettings GetDefaultDnsProxySettings() { lock (SYNC_ROOT) { try { LOG.InfoFormat("Getting default DNS proxy settings"); DnsProxySettings dnsProxySettings = Dns.DnsProxyServer.DnsProxyServer.GetDefaultDnsProxySettings(); LOG.InfoFormat("Getting default DNS proxy settings has been successfully completed"); return dnsProxySettings; } catch (Exception ex) { LOG.ErrorFormat("Getting default DNS proxy settings failed with an error", ex); throw; } } } #endregion #region DnsUtils /// <summary> /// Parses a specified DNS stamp string (<seealso cref="dnsStampStr"/>) /// </summary> /// <param name="dnsStampStr">DNS stamp string</param> /// <returns>DNS stamp as a <see cref="DnsStamp"/> instance</returns> public DnsStamp ParseDnsStamp(string dnsStampStr) { lock (SYNC_ROOT) { try { LOG.InfoFormat("Parsing DNS stamp"); DnsStamp dnsStamp = DnsUtils.ParseDnsStamp(dnsStampStr); LOG.InfoFormat("Parsing DNS stamp has been successfully completed"); return dnsStamp; } catch (Exception ex) { LOG.ErrorFormat("Parsing DNS stamp failed with an error", ex); return null; } } } /// <summary> /// Checks if upstream is valid and available /// </summary> /// <param name="upstreamOptions">Upstream options /// (<seealso cref="UpstreamOptions"/>)</param> /// <exception cref="InvalidOperationException"></exception> /// <returns>True, if test has completed successfully, /// otherwise false</returns> public bool TestUpstream(UpstreamOptions upstreamOptions) { lock (SYNC_ROOT) { try { LOG.InfoFormat("Testing upstream"); bool result = DnsUtils.TestUpstream(upstreamOptions); LOG.InfoFormat("Testing upstream has been successfully completed"); return result; } catch (Exception ex) { LOG.ErrorFormat("Testing upstream failed with an error", ex); return false; } } } /// <summary> /// Gets current DNS proxy version /// </summary> /// <returns></returns> public string GetDnsProxyVersion() { string dnsProxyVersion = DnsUtils.GetDnsProxyVersion(); return dnsProxyVersion; } #endregion #region Logging /// <summary> /// Initializes the DnsLoggerAdapter with the specified log level /// </summary> /// <param name="logLevel">Log level you'd like to use</param> public void InitLogger(LogLevel logLevel) { lock (SYNC_ROOT) { DnsLoggerAdapter.Init(logLevel); DnsLoggerAdapter.SetLogger(); } } #endregion #region Crash reporting /// <summary> /// Sets an unhandled exception configuration /// (<seealso cref="IUnhandledExceptionConfiguration"/>) /// </summary> /// <param name="unhandledExceptionConfiguration"> /// Callbacks configuration to execute when native and/or managed exception occurred</param> public void SetUnhandledExceptionConfiguration( IUnhandledExceptionConfiguration unhandledExceptionConfiguration) { lock (SYNC_ROOT) { try { LOG.InfoFormat("Setting unhandled exception configuration"); DnsExceptionHandler.Init(unhandledExceptionConfiguration); DnsExceptionHandler.SetUnhandledExceptionConfiguration(); LOG.InfoFormat("Setting unhandled exception configuration has been successfully completed"); } catch (Exception ex) { LOG.ErrorFormat("Setting unhandled exception configuration failed with an error", ex); } } } #endregion } }
39.136364
125
0.523673
[ "Apache-2.0" ]
sfionov/DnsLibs
platform/windows/cs/Adguard.Dns/Adguard.Dns/Api/DnsApi.cs
14,639
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. using System; using System.Diagnostics; using System.Collections; using System.Threading; namespace OpenLiveWriter.CoreServices { /// <summary> /// A helper object that assists with processing tasks using the .NET ThreadPool without /// overloading its 25 thread limit. /// </summary> public class BackgroundWorkerQueue { /// <summary> /// Creates a new BackgroundWorkerQueue that be restricted in the number of background threads /// it will be allowed to consume. /// </summary> /// <param name="maxConcurrency">the maximum number of threads from the .NET ThreadPool this queue /// will use concurrently when processing workers.</param> public BackgroundWorkerQueue(int maxConcurrency) { MaxConcurrency = maxConcurrency; } /// <summary> /// Adds a worker method into the processing queue. /// </summary> /// <param name="callback"></param> /// <param name="state"></param> public void AddWorker(WaitCallback callback, object state) { lock (this) { BackgroundWorker worker = new BackgroundWorker(callback, state); queue.Enqueue(worker); while (activeWorkerCount < Math.Min(queue.Count, MaxConcurrency)) LaunchBackgroundWorker(); } } /// <summary> /// Returns true if this queue currently has work scheduled and/or executing. /// </summary> /// <returns></returns> public bool HasPendingWork() { return activeWorkerCount > 0 || queue.Count > 0; } /// <summary> /// Consume a new background worker thread from the .NET thread pool. /// </summary> private void LaunchBackgroundWorker() { lock (this) { try { ThreadPool.QueueUserWorkItem(new WaitCallback(ProcessQueue)); activeWorkerCount++; } catch (Exception e) { Trace.Assert(activeWorkerCount > 0, "could not launch any background workers: " + e.Message); if (activeWorkerCount == 0) { //no worker background threads were available to process the worker, so launch a //standard thread to process the queue. Thread th = new Thread(new ThreadStart(ProcessQueue)); th.IsBackground = true; th.Start(); } //else, there's at least one background thread processing the queue, so we'll eventually //get through the work in the queue. } } } /// <summary> /// A WaitCallback-compatible method for processing the items in the queue. /// </summary> /// <param name="param"></param> private void ProcessQueue(object param) { ProcessQueue(); } /// <summary> /// Loops until all of the workers in the queue have been executed. /// </summary> private void ProcessQueue() { //Thread.CurrentThread.Name = QueueName; BackgroundWorker worker = DequeueWorker(); while (worker != null) { try { worker.Callback(worker.State); } catch (Exception e) { Trace.Fail("Background worker threw an exception: " + e.Message, e.StackTrace); } worker = DequeueWorker(); } } /// <summary> /// Dequeues the next BackgroundWorker in the queue. /// </summary> /// <returns></returns> private BackgroundWorker DequeueWorker() { BackgroundWorker worker = null; lock (queue) { if (queue.Count > 0) worker = queue.Dequeue() as BackgroundWorker; if (worker == null) activeWorkerCount--; } return worker; } Queue queue = new Queue(); int activeWorkerCount; int MaxConcurrency; /// <summary> /// Utility class for associating a WaitCallback delegate with its assigned state. /// </summary> internal class BackgroundWorker { internal BackgroundWorker(WaitCallback callback, Object state) { Callback = callback; State = state; } internal WaitCallback Callback; internal Object State; } } }
33.993243
113
0.520771
[ "MIT" ]
BobinYang/OpenLiveWriter
src/managed/OpenLiveWriter.CoreServices/BackgroundWorkerQueue.cs
5,031
C#
using BTCPayServer.Controllers; using System.Linq; using BTCPayServer.Models.AccountViewModels; using BTCPayServer.Models.StoreViewModels; using BTCPayServer.Services.Invoices; using Microsoft.AspNetCore.Mvc; using NBitcoin; using NBitpayClient; using System; using System.Collections.Generic; using System.Net.Http; using System.Text; using System.Threading.Tasks; using Amazon.S3.Model; using Xunit; using NBXplorer.DerivationStrategy; using BTCPayServer.Payments; using BTCPayServer.Payments.Lightning; using BTCPayServer.Tests.Logging; using BTCPayServer.Lightning; using BTCPayServer.Lightning.CLightning; using BTCPayServer.Data; using Microsoft.AspNetCore.Identity; using NBXplorer.Models; using BTCPayServer.Client; using BTCPayServer.Events; using BTCPayServer.Services; using BTCPayServer.Services.Stores; using BTCPayServer.Services.Wallets; using NBitcoin.Payment; using Newtonsoft.Json.Linq; namespace BTCPayServer.Tests { public class TestAccount { ServerTester parent; public TestAccount(ServerTester parent) { this.parent = parent; BitPay = new Bitpay(new Key(), parent.PayTester.ServerUri); } public void GrantAccess(bool isAdmin = false) { GrantAccessAsync(isAdmin).GetAwaiter().GetResult(); } public async Task MakeAdmin(bool isAdmin = true) { var userManager = parent.PayTester.GetService<UserManager<ApplicationUser>>(); var u = await userManager.FindByIdAsync(UserId); if (isAdmin) await userManager.AddToRoleAsync(u, Roles.ServerAdmin); else await userManager.RemoveFromRoleAsync(u, Roles.ServerAdmin); IsAdmin = true; } public Task<BTCPayServerClient> CreateClient() { return Task.FromResult(new BTCPayServerClient(parent.PayTester.ServerUri, RegisterDetails.Email, RegisterDetails.Password)); } public async Task<BTCPayServerClient> CreateClient(params string[] permissions) { var manageController = parent.PayTester.GetController<ManageController>(UserId, StoreId, IsAdmin); var x = Assert.IsType<RedirectToActionResult>(await manageController.AddApiKey( new ManageController.AddApiKeyViewModel() { PermissionValues = permissions.Select(s => new ManageController.AddApiKeyViewModel.PermissionValueItem() { Permission = s, Value = true }).ToList() })); var statusMessage = manageController.TempData.GetStatusMessageModel(); Assert.NotNull(statusMessage); var str = "<code class='alert-link'>"; var apiKey = statusMessage.Html.Substring(statusMessage.Html.IndexOf(str) + str.Length); apiKey = apiKey.Substring(0, apiKey.IndexOf("</code>")); return new BTCPayServerClient(parent.PayTester.ServerUri, apiKey); } public void Register(bool isAdmin = false) { RegisterAsync(isAdmin).GetAwaiter().GetResult(); } public async Task GrantAccessAsync(bool isAdmin = false) { await RegisterAsync(isAdmin); await CreateStoreAsync(); var store = this.GetController<StoresController>(); var pairingCode = BitPay.RequestClientAuthorization("test", Facade.Merchant); Assert.IsType<ViewResult>(await store.RequestPairing(pairingCode.ToString())); await store.Pair(pairingCode.ToString(), StoreId); } public BTCPayServerClient CreateClientFromAPIKey(string apiKey) { return new BTCPayServerClient(parent.PayTester.ServerUri, apiKey); } public void CreateStore() { CreateStoreAsync().GetAwaiter().GetResult(); } public void SetNetworkFeeMode(NetworkFeeMode mode) { ModifyStore((store) => { store.NetworkFeeMode = mode; }); } public void ModifyStore(Action<StoreViewModel> modify) { var storeController = GetController<StoresController>(); StoreViewModel store = (StoreViewModel)((ViewResult)storeController.UpdateStore()).Model; modify(store); storeController.UpdateStore(store).GetAwaiter().GetResult(); } public T GetController<T>(bool setImplicitStore = true) where T : Controller { var controller = parent.PayTester.GetController<T>(UserId, setImplicitStore ? StoreId : null, IsAdmin); return controller; } public async Task CreateStoreAsync() { var store = this.GetController<UserStoresController>(); await store.CreateStore(new CreateStoreViewModel() {Name = "Test Store"}); StoreId = store.CreatedStoreId; parent.Stores.Add(StoreId); } public BTCPayNetwork SupportedNetwork { get; set; } public WalletId RegisterDerivationScheme(string crytoCode, ScriptPubKeyType segwit = ScriptPubKeyType.Legacy, bool importKeysToNBX = false) { return RegisterDerivationSchemeAsync(crytoCode, segwit, importKeysToNBX).GetAwaiter().GetResult(); } public async Task<WalletId> RegisterDerivationSchemeAsync(string cryptoCode, ScriptPubKeyType segwit = ScriptPubKeyType.Legacy, bool importKeysToNBX = false) { SupportedNetwork = parent.NetworkProvider.GetNetwork<BTCPayNetwork>(cryptoCode); var store = parent.PayTester.GetController<StoresController>(UserId, StoreId); GenerateWalletResponseV = await parent.ExplorerClient.GenerateWalletAsync(new GenerateWalletRequest() { ScriptPubKeyType = segwit, SavePrivateKeys = importKeysToNBX, }); await store.AddDerivationScheme(StoreId, new DerivationSchemeViewModel() { Enabled = true, CryptoCode = cryptoCode, Network = SupportedNetwork, RootFingerprint = GenerateWalletResponseV.AccountKeyPath.MasterFingerprint.ToString(), RootKeyPath = SupportedNetwork.GetRootKeyPath(), Source = "NBXplorer", AccountKey = GenerateWalletResponseV.AccountHDKey.Neuter().ToWif(), DerivationSchemeFormat = "BTCPay", KeyPath = GenerateWalletResponseV.AccountKeyPath.KeyPath.ToString(), DerivationScheme = DerivationScheme.ToString(), Confirmation = true }, cryptoCode); return new WalletId(StoreId, cryptoCode); } public async Task EnablePayJoin() { var storeController = parent.PayTester.GetController<StoresController>(UserId, StoreId); var storeVM = Assert.IsType<StoreViewModel>(Assert .IsType<ViewResult>(storeController.UpdateStore()).Model); storeVM.PayJoinEnabled = true; Assert.Equal(nameof(storeController.UpdateStore), Assert.IsType<RedirectToActionResult>( await storeController.UpdateStore(storeVM)).ActionName); } public GenerateWalletResponse GenerateWalletResponseV { get; set; } public DerivationStrategyBase DerivationScheme { get { return GenerateWalletResponseV.DerivationScheme; } } private async Task RegisterAsync(bool isAdmin = false) { var account = parent.PayTester.GetController<AccountController>(); RegisterDetails = new RegisterViewModel() { Email = Guid.NewGuid() + "@toto.com", ConfirmPassword = "Kitten0@", Password = "Kitten0@", IsAdmin = isAdmin }; await account.Register(RegisterDetails); UserId = account.RegisteredUserId; IsAdmin = account.RegisteredAdmin; } public RegisterViewModel RegisterDetails { get; set; } public Bitpay BitPay { get; set; } public string UserId { get; set; } public string StoreId { get; set; } public bool IsAdmin { get; internal set; } public void RegisterLightningNode(string cryptoCode, LightningConnectionType connectionType) { RegisterLightningNodeAsync(cryptoCode, connectionType).GetAwaiter().GetResult(); } public async Task RegisterLightningNodeAsync(string cryptoCode, LightningConnectionType connectionType) { var storeController = this.GetController<StoresController>(); string connectionString = null; if (connectionType == LightningConnectionType.Charge) connectionString = "type=charge;server=" + parent.MerchantCharge.Client.Uri.AbsoluteUri; else if (connectionType == LightningConnectionType.CLightning) connectionString = "type=clightning;server=" + ((CLightningClient)parent.MerchantLightningD).Address.AbsoluteUri; else if (connectionType == LightningConnectionType.LndREST) connectionString = $"type=lnd-rest;server={parent.MerchantLnd.Swagger.BaseUrl};allowinsecure=true"; else throw new NotSupportedException(connectionType.ToString()); await storeController.AddLightningNode(StoreId, new LightningNodeViewModel() {ConnectionString = connectionString, SkipPortTest = true}, "save", "BTC"); if (storeController.ModelState.ErrorCount != 0) Assert.False(true, storeController.ModelState.FirstOrDefault().Value.Errors[0].ErrorMessage); } public async Task<Coin> ReceiveUTXO(Money value, BTCPayNetwork network) { var cashCow = parent.ExplorerNode; var btcPayWallet = parent.PayTester.GetService<BTCPayWalletProvider>().GetWallet(network); var address = (await btcPayWallet.ReserveAddressAsync(this.DerivationScheme)).Address; await parent.WaitForEvent<NewOnChainTransactionEvent>(async () => { await cashCow.SendToAddressAsync(address, value); }); int i = 0; while (i <30) { var result = (await btcPayWallet.GetUnspentCoins(DerivationScheme)) .FirstOrDefault(c => c.ScriptPubKey == address.ScriptPubKey)?.Coin; if (result != null) { return result; } await Task.Delay(1000); i++; } Assert.False(true); return null; } public async Task<BitcoinAddress> GetNewAddress(BTCPayNetwork network) { var cashCow = parent.ExplorerNode; var btcPayWallet = parent.PayTester.GetService<BTCPayWalletProvider>().GetWallet(network); var address = (await btcPayWallet.ReserveAddressAsync(this.DerivationScheme)).Address; return address; } public async Task<PSBT> Sign(PSBT psbt) { var btcPayWallet = parent.PayTester.GetService<BTCPayWalletProvider>() .GetWallet(psbt.Network.NetworkSet.CryptoCode); var explorerClient = parent.PayTester.GetService<ExplorerClientProvider>() .GetExplorerClient(psbt.Network.NetworkSet.CryptoCode); psbt = (await explorerClient.UpdatePSBTAsync(new UpdatePSBTRequest() { DerivationScheme = DerivationScheme, PSBT = psbt })).PSBT; return psbt.SignAll(this.DerivationScheme, GenerateWalletResponseV.AccountHDKey, GenerateWalletResponseV.AccountKeyPath); } public async Task<PSBT> SubmitPayjoin(Invoice invoice, PSBT psbt, string expectedError = null, bool senderError= false) { var endpoint = GetPayjoinEndpoint(invoice, psbt.Network); if (endpoint == null) { return null; } var pjClient = parent.PayTester.GetService<PayjoinClient>(); var storeRepository = parent.PayTester.GetService<StoreRepository>(); var store = await storeRepository.FindStore(StoreId); var settings = store.GetSupportedPaymentMethods(parent.NetworkProvider).OfType<DerivationSchemeSettings>() .First(); Logs.Tester.LogInformation($"Proposing {psbt.GetGlobalTransaction().GetHash()}"); if (expectedError is null && !senderError) { var proposed = await pjClient.RequestPayjoin(endpoint, settings, psbt, default); Logs.Tester.LogInformation($"Proposed payjoin is {proposed.GetGlobalTransaction().GetHash()}"); Assert.NotNull(proposed); return proposed; } else { if (senderError) { await Assert.ThrowsAsync<PayjoinSenderException>(async () => await pjClient.RequestPayjoin(endpoint, settings, psbt, default)); } else { var ex = await Assert.ThrowsAsync<PayjoinReceiverException>(async () => await pjClient.RequestPayjoin(endpoint, settings, psbt, default)); Assert.Equal(expectedError, ex.ErrorCode); } return null; } } public async Task<Transaction> SubmitPayjoin(Invoice invoice, Transaction transaction, BTCPayNetwork network, string expectedError = null) { var response = await SubmitPayjoinCore(transaction.ToHex(), invoice, network.NBitcoinNetwork, expectedError); if (response == null) return null; var signed = Transaction.Parse(await response.Content.ReadAsStringAsync(), network.NBitcoinNetwork); return signed; } async Task<HttpResponseMessage> SubmitPayjoinCore(string content, Invoice invoice, Network network, string expectedError) { var endpoint = GetPayjoinEndpoint(invoice, network); var response = await parent.PayTester.HttpClient.PostAsync(endpoint, new StringContent(content, Encoding.UTF8, "text/plain")); if (expectedError != null) { Assert.False(response.IsSuccessStatusCode); var error = JObject.Parse(await response.Content.ReadAsStringAsync()); Assert.Equal(expectedError, error["errorCode"].Value<string>()); return null; } else { if (!response.IsSuccessStatusCode) { var error = JObject.Parse(await response.Content.ReadAsStringAsync()); Assert.True(false, $"Error: {error["errorCode"].Value<string>()}: {error["message"].Value<string>()}"); } } return response; } private static Uri GetPayjoinEndpoint(Invoice invoice, Network network) { var parsedBip21 = new BitcoinUrlBuilder( invoice.CryptoInfo.First(c => c.CryptoCode == network.NetworkSet.CryptoCode).PaymentUrls.BIP21, network); return parsedBip21.UnknowParameters.TryGetValue($"{PayjoinClient.BIP21EndpointKey}", out var uri) ? new Uri(uri, UriKind.Absolute) : null; } } }
40.895674
158
0.609321
[ "MIT" ]
ketominer/btcpayserver
BTCPayServer.Tests/TestAccount.cs
16,074
C#
using System.ComponentModel.DataAnnotations; using System.Collections.Generic; namespace Api.Models { public class Cart { [Key] public int Id { get; } public List<int> CartItemIds { get; } public PriceRule PriceRule { get; set; } } }
19.928571
48
0.630824
[ "MIT" ]
deanagan/ShoppingWebApiDemo
Api/Models/Cart.cs
279
C#
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.DotNet.Interactive.Commands; using Microsoft.DotNet.Interactive.Connection; using Microsoft.DotNet.Interactive.Events; using Microsoft.DotNet.Interactive.Server; namespace Microsoft.DotNet.Interactive { public class KernelHost : IDisposable { private readonly CancellationTokenSource _cancellationTokenSource = new (); private readonly CompositeKernel _kernel; private readonly IKernelCommandAndEventSender _defaultSender; private readonly MultiplexingKernelCommandAndEventReceiver _defaultReceiver; private Task<Task> _runningLoop; private IDisposable _kernelEventSubscription; private readonly Dictionary<Kernel, KernelInfo> _kernelInfos = new(); private readonly Dictionary<Uri,Kernel> _destinationUriToKernel = new (); private readonly KernelConnectorBase _defaultConnector; private readonly Dictionary<Uri, Kernel> _originUriToKernel = new(); public KernelHost(CompositeKernel kernel, IKernelCommandAndEventSender defaultSender, MultiplexingKernelCommandAndEventReceiver defaultReceiver, Uri hostUri) { _kernel = kernel; _defaultSender = defaultSender; _defaultReceiver = defaultReceiver; _defaultConnector = new DefaultKernelConnector(_defaultSender, _defaultReceiver); Uri = hostUri; _kernel.SetHost(this); } public KernelHost(CompositeKernel kernel,IKernelCommandAndEventSender defaultSender, MultiplexingKernelCommandAndEventReceiver defaultReceiver) : this(kernel, defaultSender, defaultReceiver, new Uri("kernel://dotnet", UriKind.Absolute)) { } public static KernelHost InProcess(CompositeKernel kernel) { // QUESTION: (InProcess) does this need to be here? the implementation looks incomplete. var receiver = new MultiplexingKernelCommandAndEventReceiver(new InProcessCommandAndEventReceiver()); var sender = new InProcessCommandAndEventSender(); return new KernelHost(kernel, sender, receiver); } private class DefaultKernelConnector : KernelConnectorBase { private readonly IKernelCommandAndEventSender _defaultSender; private readonly MultiplexingKernelCommandAndEventReceiver _defaultReceiver; public DefaultKernelConnector(IKernelCommandAndEventSender defaultSender, MultiplexingKernelCommandAndEventReceiver defaultReceiver) { _defaultSender = defaultSender; _defaultReceiver = defaultReceiver; } public override Task<Kernel> ConnectKernelAsync(KernelInfo kernelInfo) { var proxy = new ProxyKernel(kernelInfo.LocalName, _defaultReceiver.CreateChildReceiver(), _defaultSender); var _ = proxy.StartAsync(); return Task.FromResult((Kernel)proxy); } public void Dispose() { _defaultReceiver.Dispose(); } } public async Task ConnectAsync() { if (_runningLoop is { }) { throw new InvalidOperationException("The host is already connected."); } _kernelEventSubscription = _kernel.KernelEvents.Subscribe(e => { if (e is ReturnValueProduced { Value: DisplayedValue }) { return; } var _ = _defaultSender.SendAsync(e, _cancellationTokenSource.Token); }); _runningLoop = Task.Factory.StartNew(async () => { await foreach (var commandOrEvent in _defaultReceiver.CommandsAndEventsAsync(_cancellationTokenSource.Token)) { if (commandOrEvent.IsParseError) { var _ = _defaultSender.SendAsync(commandOrEvent.Event, _cancellationTokenSource.Token); } else if (commandOrEvent.Command is { }) { var kernel = GetKernel(commandOrEvent.Command); var _ = kernel.SendAsync(commandOrEvent.Command, _cancellationTokenSource.Token); } } }, _cancellationTokenSource.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default); await _defaultSender.NotifyIsReadyAsync(_cancellationTokenSource.Token); } private Kernel GetKernel(KernelCommand command) { // QUESTION: (GetKernel) coverage indicates we can delete some of this? if (command.DestinationUri is { } && TryGetKernelByOriginUri(command.DestinationUri, out var kernel)) { return kernel; } if (command.DestinationUri is { } && TryGetKernelByDestinationUri(command.DestinationUri, out kernel)) { return kernel; } if (command.OriginUri is { } && TryGetKernelByOriginUri(command.DestinationUri, out kernel)) { return kernel; } return _kernel; } public async Task ConnectAndWaitAsync() { await ConnectAsync(); await _runningLoop; } public void Dispose() { _kernelEventSubscription?.Dispose(); _cancellationTokenSource.Cancel(); _cancellationTokenSource.Dispose(); } public bool TryGetKernelInfo(Kernel kernel, out KernelInfo kernelInfo) { return _kernelInfos.TryGetValue(kernel, out kernelInfo); } internal void AddKernelInfo(Kernel kernel, KernelInfo kernelInfo) { kernelInfo.OriginUri = new Uri(Uri, kernel.Name); _kernelInfos.Add(kernel,kernelInfo); _originUriToKernel[kernelInfo.OriginUri] = kernel; } public Uri Uri { get; } private class InProcessCommandAndEventSender : IKernelCommandAndEventSender { // QUESTION: (InProcessCommandAndEventSender) does this need to be tested for compliance with other implementations? private Func<CommandOrEvent, Task> _onSendAsync; public Task SendAsync(KernelCommand kernelCommand, CancellationToken cancellationToken) { _onSendAsync?.Invoke(new CommandOrEvent(KernelCommandEnvelope.Deserialize(KernelCommandEnvelope.Serialize(kernelCommand)).Command)); return Task.CompletedTask; } public Task SendAsync(KernelEvent kernelEvent, CancellationToken cancellationToken) { _onSendAsync?.Invoke(new CommandOrEvent(KernelEventEnvelope.Deserialize(KernelEventEnvelope.Serialize(kernelEvent)).Event)); return Task.CompletedTask; } public void OnSend(Action<CommandOrEvent> onSend) { _onSendAsync = commandOrEvent => { onSend(commandOrEvent); return Task.CompletedTask; }; } public void OnSend(Func<CommandOrEvent, Task> onSendAsync) { _onSendAsync = onSendAsync; } } private class InProcessCommandAndEventReceiver : KernelCommandAndEventReceiverBase { // QUESTION: (InProcessCommandAndEventReceiver) does this need to be tested for compliance with other implementations? private readonly BlockingCollection<CommandOrEvent> _commandsOrEvents; public InProcessCommandAndEventReceiver() { _commandsOrEvents = new BlockingCollection<CommandOrEvent>(); } public void Write(CommandOrEvent commandOrEvent) { if (commandOrEvent.Command is { }) { _commandsOrEvents.Add(new CommandOrEvent(KernelCommandEnvelope .Deserialize(KernelCommandEnvelope.Serialize(commandOrEvent.Command)).Command)); } else if (commandOrEvent.Event is { }) { _commandsOrEvents.Add(new CommandOrEvent(KernelEventEnvelope .Deserialize(KernelEventEnvelope.Serialize(commandOrEvent.Event)).Event)); } } protected override Task<CommandOrEvent> ReadCommandOrEventAsync(CancellationToken cancellationToken) { return Task.FromResult(_commandsOrEvents.Take(cancellationToken)); } } internal void RegisterDestinationUriForProxy(ProxyKernel proxyKernel, Uri destinationUri) { if (proxyKernel == null) { throw new ArgumentNullException(nameof(proxyKernel)); } if (destinationUri == null) { throw new ArgumentNullException(nameof(destinationUri)); } if (TryGetKernelInfo(proxyKernel, out var kernelInfo)) { if (kernelInfo.DestinationUri is { }) { _destinationUriToKernel.Remove(kernelInfo.DestinationUri); } kernelInfo.DestinationUri = destinationUri; _destinationUriToKernel[kernelInfo.DestinationUri] = proxyKernel; } else { throw new ArgumentException($"Unknown kernel name : {proxyKernel.Name}"); } } internal void RegisterDestinationUriForProxy(string proxyLocalKernelName, Uri destinationUri) { var childKernel = _kernel.FindKernel(proxyLocalKernelName); if (childKernel is ProxyKernel proxyKernel) { RegisterDestinationUriForProxy(proxyKernel, destinationUri); } else { throw new ArgumentException($"Cannot find Kernel {proxyLocalKernelName} or it is not a valid ProxyKernel"); } } public async Task<ProxyKernel> CreateProxyKernelOnDefaultConnectorAsync(KernelInfo kernelInfo) { var childKernel = await CreateProxyKernelOnConnectorAsync(kernelInfo,_defaultConnector); return childKernel; } public async Task<ProxyKernel> CreateProxyKernelOnConnectorAsync(KernelInfo kernelInfo, KernelConnectorBase kernelConnectorBase ) { var childKernel = await kernelConnectorBase.ConnectKernelAsync(kernelInfo) as ProxyKernel; _kernel.Add(childKernel, kernelInfo.Aliases); RegisterDestinationUriForProxy(kernelInfo.LocalName, kernelInfo.DestinationUri); return childKernel; } public bool TryGetKernelByDestinationUri(Uri destinationUri, out Kernel kernel) { return _destinationUriToKernel.TryGetValue(destinationUri, out kernel); } public bool TryGetKernelByOriginUri(Uri originUri, out Kernel kernel) { return _originUriToKernel.TryGetValue(originUri, out kernel); } } }
40.121107
244
0.625442
[ "MIT" ]
tesar-tech/interactive
src/Microsoft.DotNet.Interactive/KernelHost.cs
11,597
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from um/dcomp.h in the Windows SDK for Windows 10.0.19041.0 // Original source is Copyright © Microsoft. All rights reserved. using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace TerraFX.Interop { [Guid("4D93059D-097B-4651-9A60-F0F25116E2F3")] [NativeTypeName("struct IDCompositionVisual : IUnknown")] public unsafe partial struct IDCompositionVisual { public void** lpVtbl; [MethodImpl(MethodImplOptions.AggressiveInlining)] [return: NativeTypeName("HRESULT")] public int QueryInterface([NativeTypeName("const IID &")] Guid* riid, [NativeTypeName("void **")] void** ppvObject) { return ((delegate* unmanaged<IDCompositionVisual*, Guid*, void**, int>)(lpVtbl[0]))((IDCompositionVisual*)Unsafe.AsPointer(ref this), riid, ppvObject); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [return: NativeTypeName("ULONG")] public uint AddRef() { return ((delegate* unmanaged<IDCompositionVisual*, uint>)(lpVtbl[1]))((IDCompositionVisual*)Unsafe.AsPointer(ref this)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [return: NativeTypeName("ULONG")] public uint Release() { return ((delegate* unmanaged<IDCompositionVisual*, uint>)(lpVtbl[2]))((IDCompositionVisual*)Unsafe.AsPointer(ref this)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [return: NativeTypeName("HRESULT")] public int SetOffsetX(float offsetX) { return ((delegate* unmanaged<IDCompositionVisual*, float, int>)(lpVtbl[3]))((IDCompositionVisual*)Unsafe.AsPointer(ref this), offsetX); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [return: NativeTypeName("HRESULT")] public int SetOffsetX([NativeTypeName("IDCompositionAnimation *")] IDCompositionAnimation* animation) { return ((delegate* unmanaged<IDCompositionVisual*, IDCompositionAnimation*, int>)(lpVtbl[4]))((IDCompositionVisual*)Unsafe.AsPointer(ref this), animation); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [return: NativeTypeName("HRESULT")] public int SetOffsetY(float offsetY) { return ((delegate* unmanaged<IDCompositionVisual*, float, int>)(lpVtbl[5]))((IDCompositionVisual*)Unsafe.AsPointer(ref this), offsetY); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [return: NativeTypeName("HRESULT")] public int SetOffsetY([NativeTypeName("IDCompositionAnimation *")] IDCompositionAnimation* animation) { return ((delegate* unmanaged<IDCompositionVisual*, IDCompositionAnimation*, int>)(lpVtbl[6]))((IDCompositionVisual*)Unsafe.AsPointer(ref this), animation); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [return: NativeTypeName("HRESULT")] public int SetTransform([NativeTypeName("const D2D_MATRIX_3X2_F &")] D2D_MATRIX_3X2_F* matrix) { return ((delegate* unmanaged<IDCompositionVisual*, D2D_MATRIX_3X2_F*, int>)(lpVtbl[7]))((IDCompositionVisual*)Unsafe.AsPointer(ref this), matrix); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [return: NativeTypeName("HRESULT")] public int SetTransform([NativeTypeName("IDCompositionTransform *")] IDCompositionTransform* transform) { return ((delegate* unmanaged<IDCompositionVisual*, IDCompositionTransform*, int>)(lpVtbl[8]))((IDCompositionVisual*)Unsafe.AsPointer(ref this), transform); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [return: NativeTypeName("HRESULT")] public int SetTransformParent([NativeTypeName("IDCompositionVisual *")] IDCompositionVisual* visual) { return ((delegate* unmanaged<IDCompositionVisual*, IDCompositionVisual*, int>)(lpVtbl[9]))((IDCompositionVisual*)Unsafe.AsPointer(ref this), visual); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [return: NativeTypeName("HRESULT")] public int SetEffect([NativeTypeName("IDCompositionEffect *")] IDCompositionEffect* effect) { return ((delegate* unmanaged<IDCompositionVisual*, IDCompositionEffect*, int>)(lpVtbl[10]))((IDCompositionVisual*)Unsafe.AsPointer(ref this), effect); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [return: NativeTypeName("HRESULT")] public int SetBitmapInterpolationMode(DCOMPOSITION_BITMAP_INTERPOLATION_MODE interpolationMode) { return ((delegate* unmanaged<IDCompositionVisual*, DCOMPOSITION_BITMAP_INTERPOLATION_MODE, int>)(lpVtbl[11]))((IDCompositionVisual*)Unsafe.AsPointer(ref this), interpolationMode); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [return: NativeTypeName("HRESULT")] public int SetBorderMode(DCOMPOSITION_BORDER_MODE borderMode) { return ((delegate* unmanaged<IDCompositionVisual*, DCOMPOSITION_BORDER_MODE, int>)(lpVtbl[12]))((IDCompositionVisual*)Unsafe.AsPointer(ref this), borderMode); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [return: NativeTypeName("HRESULT")] public int SetClip([NativeTypeName("const D2D_RECT_F &")] D2D_RECT_F* rect) { return ((delegate* unmanaged<IDCompositionVisual*, D2D_RECT_F*, int>)(lpVtbl[13]))((IDCompositionVisual*)Unsafe.AsPointer(ref this), rect); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [return: NativeTypeName("HRESULT")] public int SetClip([NativeTypeName("IDCompositionClip *")] IDCompositionClip* clip) { return ((delegate* unmanaged<IDCompositionVisual*, IDCompositionClip*, int>)(lpVtbl[14]))((IDCompositionVisual*)Unsafe.AsPointer(ref this), clip); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [return: NativeTypeName("HRESULT")] public int SetContent([NativeTypeName("IUnknown *")] IUnknown* content) { return ((delegate* unmanaged<IDCompositionVisual*, IUnknown*, int>)(lpVtbl[15]))((IDCompositionVisual*)Unsafe.AsPointer(ref this), content); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [return: NativeTypeName("HRESULT")] public int AddVisual([NativeTypeName("IDCompositionVisual *")] IDCompositionVisual* visual, [NativeTypeName("BOOL")] int insertAbove, [NativeTypeName("IDCompositionVisual *")] IDCompositionVisual* referenceVisual) { return ((delegate* unmanaged<IDCompositionVisual*, IDCompositionVisual*, int, IDCompositionVisual*, int>)(lpVtbl[16]))((IDCompositionVisual*)Unsafe.AsPointer(ref this), visual, insertAbove, referenceVisual); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [return: NativeTypeName("HRESULT")] public int RemoveVisual([NativeTypeName("IDCompositionVisual *")] IDCompositionVisual* visual) { return ((delegate* unmanaged<IDCompositionVisual*, IDCompositionVisual*, int>)(lpVtbl[17]))((IDCompositionVisual*)Unsafe.AsPointer(ref this), visual); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [return: NativeTypeName("HRESULT")] public int RemoveAllVisuals() { return ((delegate* unmanaged<IDCompositionVisual*, int>)(lpVtbl[18]))((IDCompositionVisual*)Unsafe.AsPointer(ref this)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [return: NativeTypeName("HRESULT")] public int SetCompositeMode(DCOMPOSITION_COMPOSITE_MODE compositeMode) { return ((delegate* unmanaged<IDCompositionVisual*, DCOMPOSITION_COMPOSITE_MODE, int>)(lpVtbl[19]))((IDCompositionVisual*)Unsafe.AsPointer(ref this), compositeMode); } } }
51.025157
221
0.691236
[ "MIT" ]
Perksey/terrafx.interop.windows
sources/Interop/Windows/um/dcomp/IDCompositionVisual.cs
8,115
C#
namespace CEdit { partial class Form1 { /// <summary> /// 必要なデザイナー変数です。 /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// 使用中のリソースをすべてクリーンアップします。 /// </summary> /// <param name="disposing">マネージ リソースが破棄される場合 true、破棄されない場合は false です。</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows フォーム デザイナーで生成されたコード /// <summary> /// デザイナー サポートに必要なメソッドです。このメソッドの内容を /// コード エディターで変更しないでください。 /// </summary> private void InitializeComponent() { this.menuStrip1 = new System.Windows.Forms.MenuStrip(); this.statusStrip1 = new System.Windows.Forms.StatusStrip(); this.Mnu_ファイル = new System.Windows.Forms.ToolStripMenuItem(); this.richTextBox1 = new System.Windows.Forms.RichTextBox(); this.Mnu_編集 = new System.Windows.Forms.ToolStripMenuItem(); this.Mnu_Refresh = new System.Windows.Forms.ToolStripMenuItem(); this.menuStrip1.SuspendLayout(); this.SuspendLayout(); // // menuStrip1 // this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.Mnu_ファイル, this.Mnu_編集}); this.menuStrip1.Location = new System.Drawing.Point(0, 0); this.menuStrip1.Name = "menuStrip1"; this.menuStrip1.Size = new System.Drawing.Size(491, 26); this.menuStrip1.TabIndex = 0; this.menuStrip1.Text = "menuStrip1"; // // statusStrip1 // this.statusStrip1.Location = new System.Drawing.Point(0, 412); this.statusStrip1.Name = "statusStrip1"; this.statusStrip1.Size = new System.Drawing.Size(491, 22); this.statusStrip1.TabIndex = 1; this.statusStrip1.Text = "statusStrip1"; // // Mnu_ファイル // this.Mnu_ファイル.Name = "Mnu_ファイル"; this.Mnu_ファイル.Size = new System.Drawing.Size(85, 22); this.Mnu_ファイル.Text = "ファイル(&F)"; // // richTextBox1 // this.richTextBox1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.richTextBox1.Font = new System.Drawing.Font("Courier New", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.richTextBox1.Location = new System.Drawing.Point(0, 29); this.richTextBox1.Name = "richTextBox1"; this.richTextBox1.ScrollBars = System.Windows.Forms.RichTextBoxScrollBars.Vertical; this.richTextBox1.Size = new System.Drawing.Size(491, 380); this.richTextBox1.TabIndex = 2; this.richTextBox1.Text = ""; // // Mnu_編集 // this.Mnu_編集.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.Mnu_Refresh}); this.Mnu_編集.Name = "Mnu_編集"; this.Mnu_編集.Size = new System.Drawing.Size(61, 22); this.Mnu_編集.Text = "編集(&E)"; // // Mnu_Refresh // this.Mnu_Refresh.Name = "Mnu_Refresh"; this.Mnu_Refresh.Size = new System.Drawing.Size(152, 22); this.Mnu_Refresh.Text = "&Refresh"; this.Mnu_Refresh.Click += new System.EventHandler(this.Mnu_Refresh_Click); // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(491, 434); this.Controls.Add(this.richTextBox1); this.Controls.Add(this.statusStrip1); this.Controls.Add(this.menuStrip1); this.MainMenuStrip = this.menuStrip1; this.Name = "Form1"; this.Text = "Form1"; this.menuStrip1.ResumeLayout(false); this.menuStrip1.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.MenuStrip menuStrip1; private System.Windows.Forms.ToolStripMenuItem Mnu_ファイル; private System.Windows.Forms.StatusStrip statusStrip1; private System.Windows.Forms.RichTextBox richTextBox1; private System.Windows.Forms.ToolStripMenuItem Mnu_編集; private System.Windows.Forms.ToolStripMenuItem Mnu_Refresh; } }
33.967213
156
0.699807
[ "MIT" ]
stackprobe/Annex
Junk/CEdit/CEdit/Form1.Designer.cs
4,524
C#
//////////////////////////////////////////////////////////////////////////////// //NUnit tests for "EF Core Provider for LCPI OLE DB" // IBProvider and Contributors. 07.12.2021. using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using Microsoft.EntityFrameworkCore; using NUnit.Framework; using xdb=lcpi.data.oledb; namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D1.Query.Funcs.Int64.SET001.STD.Equals.Complete.Double{ //////////////////////////////////////////////////////////////////////////////// using T_DATA1 =System.Int64; using T_DATA2 =System.Double; using T_DATA1_U=System.Int64; using T_DATA2_U=System.Double; //////////////////////////////////////////////////////////////////////////////// //class TestSet_001__fields__01__VV public static class TestSet_001__fields__01__VV { private const string c_NameOf__TABLE ="TEST_MODIFY_ROW2"; private const string c_NameOf__COL_DATA1 ="COL_BIGINT"; private const string c_NameOf__COL_DATA2 ="COL2_DOUBLE"; private sealed class MyContext:TestBaseDbContext { [Table(c_NameOf__TABLE)] public sealed class TEST_RECORD { [Key] [Column("TEST_ID")] public System.Int64? TEST_ID { get; set; } [Column(c_NameOf__COL_DATA1)] public T_DATA1 COL_DATA1 { get; set; } [Column(c_NameOf__COL_DATA2)] public T_DATA2 COL_DATA2 { get; set; } };//class TEST_RECORD //---------------------------------------------------------------------- public DbSet<TEST_RECORD> testTable { get; set; } //---------------------------------------------------------------------- public MyContext(xdb.OleDbTransaction tr) :base(tr) { }//MyContext };//class MyContext //----------------------------------------------------------------------- [Test] public static void Test_001() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { const T_DATA1_U c_value1=4; const T_DATA2_U c_value2=4; System.Int64? testID=Helper__InsertRow(db,c_value1,c_value2); var recs=db.testTable.Where(r => ((r.COL_DATA1) /*OP{*/ .Equals /*}OP*/ (r.COL_DATA2)) && r.TEST_ID==testID); int nRecs=0; foreach(var r in recs) { Assert.AreEqual (0, nRecs); ++nRecs; Assert.IsTrue (r.TEST_ID.HasValue); Assert.AreEqual (testID, r.TEST_ID.Value); Assert.AreEqual (c_value1, r.COL_DATA1); Assert.AreEqual (c_value2, r.COL_DATA2); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("t","TEST_ID").T(", ").N("t",c_NameOf__COL_DATA1).T(", ").N("t",c_NameOf__COL_DATA2).EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("t").EOL() .T("WHERE (").N("t",c_NameOf__COL_DATA1).T(" = ").N("t",c_NameOf__COL_DATA2).T(") AND (").N("t","TEST_ID").T(" = ").P_ID("__testID_0").T(")")); Assert.AreEqual (1, nRecs); }//using db tr.Rollback(); }//using tr }//using cn }//Test_001 //Helper methods -------------------------------------------------------- private static System.Int64 Helper__InsertRow(MyContext db, T_DATA1 valueForColData1, T_DATA2 valueForColData2) { var newRecord=new MyContext.TEST_RECORD(); newRecord.COL_DATA1 =valueForColData1; newRecord.COL_DATA2 =valueForColData2; db.testTable.Add(newRecord); db.SaveChanges(); db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("INSERT INTO ").N(c_NameOf__TABLE).T(" (").N(c_NameOf__COL_DATA1).T(", ").N(c_NameOf__COL_DATA2).T(")").EOL() .T("VALUES (").P("p0").T(", ").P("p1").T(")").EOL() .T("RETURNING ").N("TEST_ID").EOL() .T("INTO ").P("p2").T(";")); Assert.IsTrue (newRecord.TEST_ID.HasValue); Console.WriteLine("TEST_ID: {0}",newRecord.TEST_ID.Value); return newRecord.TEST_ID.Value; }//Helper__InsertRow };//class TestSet_001__fields__01__VV //////////////////////////////////////////////////////////////////////////////// }//namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D1.Query.Funcs.Int64.SET001.STD.Equals.Complete.Double
29.596026
151
0.561871
[ "MIT" ]
ibprovider/Lcpi.EFCore.LcpiOleDb
Tests/General/Source/Work/DBMS/Firebird/V03_0_0/D1/Query/Funcs/Int64/SET001/STD/Equals/Complete/Double/TestSet_001__fields__01__VV.cs
4,471
C#
using System; using Windows.Devices.Geolocation; using TrackMe.Core.Models; using TrackMe.Core.Services.Interfaces; namespace TrackMe.WinPhoneUniversalNative.Helpers { static class Extensions { public static Geopoint ToNative(this Position position) { return new Geopoint(new BasicGeoposition(){ Latitude = position.Latitude, Longitude = position.Longitude }); } } public static class PhoneExtensions { public static LocationStatus ToLocationStatus(this PositionStatus status) { switch (status) { case PositionStatus.Disabled | PositionStatus.NotAvailable | PositionStatus.NoData | PositionStatus.NotInitialized: return LocationStatus.Stopped; case PositionStatus.Ready: return LocationStatus.Started; case PositionStatus.Initializing: return LocationStatus.Initializing; default: return LocationStatus.Stopped; } } } public static class StringExtensions { public static bool IsNullOrEmpty(this string stringToCheck) { return String.IsNullOrEmpty(stringToCheck); } public static bool IsNotNullOrEmpty(this string stringToCheck) { return !String.IsNullOrEmpty(stringToCheck); } } }
31.152174
131
0.62596
[ "MIT" ]
PGSSoft/TrackMe-Mobile
TrackMe.WinPhoneUniversalNative/Helpers/Extensions.cs
1,435
C#
using System.Collections.Generic; using System.Data; using System.Data.Common; using System.Linq; using NUnit.Framework; using Paramol.SqlClient; namespace Paramol.Tests.SqlClient { public partial class TSqlTests { [TestCaseSource("QueryStatementCases")] public void QueryStatementReturnsExpectedInstance(SqlQueryCommand actual, SqlQueryCommand expected) { Assert.That(actual.Text, Is.EqualTo(expected.Text)); Assert.That(actual.Parameters, Is.EquivalentTo(expected.Parameters).Using(new SqlParameterEqualityComparer())); } private static IEnumerable<TestCaseData> QueryStatementCases() { yield return new TestCaseData( TSql.QueryStatement("text"), new SqlQueryCommand("text", new DbParameter[0], CommandType.Text)); yield return new TestCaseData( TSql.QueryStatement("text", parameters: null), new SqlQueryCommand("text", new DbParameter[0], CommandType.Text)); yield return new TestCaseData( TSql.QueryStatement("text", new { }), new SqlQueryCommand("text", new DbParameter[0], CommandType.Text)); yield return new TestCaseData( TSql.QueryStatement("text", new { Parameter = new SqlParameterValueStub() }), new SqlQueryCommand("text", new[] { new SqlParameterValueStub().ToDbParameter("@Parameter") }, CommandType.Text)); yield return new TestCaseData( TSql.QueryStatement("text", new { Parameter1 = new SqlParameterValueStub(), Parameter2 = new SqlParameterValueStub() }), new SqlQueryCommand("text", new[] { new SqlParameterValueStub().ToDbParameter("@Parameter1"), new SqlParameterValueStub().ToDbParameter("@Parameter2") }, CommandType.Text)); } [TestCaseSource("QueryStatementIfCases")] public void QueryStatementIfReturnsExpectedInstance(IEnumerable<SqlQueryCommand> actual, SqlQueryCommand[] expected) { var actualArray = actual.ToArray(); Assert.That(actualArray.Length, Is.EqualTo(expected.Length)); for (var index = 0; index < actualArray.Length; index++) { Assert.That(actualArray[index].Text, Is.EqualTo(expected[index].Text)); Assert.That(actualArray[index].Parameters, Is.EquivalentTo(expected[index].Parameters).Using(new SqlParameterEqualityComparer())); } } private static IEnumerable<TestCaseData> QueryStatementIfCases() { yield return new TestCaseData( TSql.QueryStatementIf(true, "text"), new[] { new SqlQueryCommand("text", new DbParameter[0], CommandType.Text) }); yield return new TestCaseData( TSql.QueryStatementIf(true, "text", parameters: null), new[] { new SqlQueryCommand("text", new DbParameter[0], CommandType.Text) }); yield return new TestCaseData( TSql.QueryStatementIf(true, "text", new { }), new[] { new SqlQueryCommand("text", new DbParameter[0], CommandType.Text) }); yield return new TestCaseData( TSql.QueryStatementIf(true, "text", new { Parameter = new SqlParameterValueStub() }), new[] { new SqlQueryCommand("text", new[] { new SqlParameterValueStub().ToDbParameter("@Parameter") }, CommandType.Text) }); yield return new TestCaseData( TSql.QueryStatementIf(true, "text", new { Parameter1 = new SqlParameterValueStub(), Parameter2 = new SqlParameterValueStub() }), new[] { new SqlQueryCommand("text", new[] { new SqlParameterValueStub().ToDbParameter("@Parameter1"), new SqlParameterValueStub().ToDbParameter("@Parameter2") }, CommandType.Text) }); yield return new TestCaseData( TSql.QueryStatementIf(false, "text"), new SqlQueryCommand[0]); yield return new TestCaseData( TSql.QueryStatementIf(false, "text", parameters: null), new SqlQueryCommand[0]); yield return new TestCaseData( TSql.QueryStatementIf(false, "text", new { }), new SqlQueryCommand[0]); yield return new TestCaseData( TSql.QueryStatementIf(false, "text", new { Parameter = new SqlParameterValueStub() }), new SqlQueryCommand[0]); yield return new TestCaseData( TSql.QueryStatementIf(false, "text", new { Parameter1 = new SqlParameterValueStub(), Parameter2 = new SqlParameterValueStub() }), new SqlQueryCommand[0]); } [TestCaseSource("QueryStatementUnlessCases")] public void QueryStatementUnlessReturnsExpectedInstance(IEnumerable<SqlQueryCommand> actual, SqlQueryCommand[] expected) { var actualArray = actual.ToArray(); Assert.That(actualArray.Length, Is.EqualTo(expected.Length)); for (var index = 0; index < actualArray.Length; index++) { Assert.That(actualArray[index].Text, Is.EqualTo(expected[index].Text)); Assert.That(actualArray[index].Parameters, Is.EquivalentTo(expected[index].Parameters).Using(new SqlParameterEqualityComparer())); } } private static IEnumerable<TestCaseData> QueryStatementUnlessCases() { yield return new TestCaseData( TSql.QueryStatementUnless(false, "text"), new[] { new SqlQueryCommand("text", new DbParameter[0], CommandType.Text) }); yield return new TestCaseData( TSql.QueryStatementUnless(false, "text", parameters: null), new[] { new SqlQueryCommand("text", new DbParameter[0], CommandType.Text) }); yield return new TestCaseData( TSql.QueryStatementUnless(false, "text", new { }), new[] { new SqlQueryCommand("text", new DbParameter[0], CommandType.Text) }); yield return new TestCaseData( TSql.QueryStatementUnless(false, "text", new { Parameter = new SqlParameterValueStub() }), new[] { new SqlQueryCommand("text", new[] { new SqlParameterValueStub().ToDbParameter("@Parameter") }, CommandType.Text) }); yield return new TestCaseData( TSql.QueryStatementUnless(false, "text", new { Parameter1 = new SqlParameterValueStub(), Parameter2 = new SqlParameterValueStub() }), new[] { new SqlQueryCommand("text", new[] { new SqlParameterValueStub().ToDbParameter("@Parameter1"), new SqlParameterValueStub().ToDbParameter("@Parameter2") }, CommandType.Text) }); yield return new TestCaseData( TSql.QueryStatementUnless(true, "text"), new SqlQueryCommand[0]); yield return new TestCaseData( TSql.QueryStatementUnless(true, "text", parameters: null), new SqlQueryCommand[0]); yield return new TestCaseData( TSql.QueryStatementUnless(true, "text", new { }), new SqlQueryCommand[0]); yield return new TestCaseData( TSql.QueryStatementUnless(true, "text", new { Parameter = new SqlParameterValueStub() }), new SqlQueryCommand[0]); yield return new TestCaseData( TSql.QueryStatementUnless(true, "text", new { Parameter1 = new SqlParameterValueStub(), Parameter2 = new SqlParameterValueStub() }), new SqlQueryCommand[0]); } [TestCaseSource("QueryStatementFormatCases")] public void QueryStatementFormatReturnsExpectedInstance(SqlQueryCommand actual, SqlQueryCommand expected) { Assert.That(actual.Text, Is.EqualTo(expected.Text)); Assert.That(actual.Parameters, Is.EquivalentTo(expected.Parameters).Using(new SqlParameterEqualityComparer())); } private static IEnumerable<TestCaseData> QueryStatementFormatCases() { yield return new TestCaseData( TSql.QueryStatementFormat("text"), new SqlQueryCommand("text", new DbParameter[0], CommandType.Text)); yield return new TestCaseData( TSql.QueryStatementFormat("text", parameters: null), new SqlQueryCommand("text", new DbParameter[0], CommandType.Text)); yield return new TestCaseData( TSql.QueryStatementFormat("text", new IDbParameterValue[0]), new SqlQueryCommand("text", new DbParameter[0], CommandType.Text)); yield return new TestCaseData( TSql.QueryStatementFormat("text", new SqlParameterValueStub()), new SqlQueryCommand("text", new[] { new SqlParameterValueStub().ToDbParameter("@P0") }, CommandType.Text)); yield return new TestCaseData( TSql.QueryStatementFormat("text {0}", new SqlParameterValueStub()), new SqlQueryCommand("text @P0", new[] { new SqlParameterValueStub().ToDbParameter("@P0") }, CommandType.Text)); yield return new TestCaseData( TSql.QueryStatementFormat("text", new SqlParameterValueStub(), new SqlParameterValueStub()), new SqlQueryCommand("text", new[] { new SqlParameterValueStub().ToDbParameter("@P0"), new SqlParameterValueStub().ToDbParameter("@P1") }, CommandType.Text)); yield return new TestCaseData( TSql.QueryStatementFormat("text {0} {1}", new SqlParameterValueStub(), new SqlParameterValueStub()), new SqlQueryCommand("text @P0 @P1", new[] { new SqlParameterValueStub().ToDbParameter("@P0"), new SqlParameterValueStub().ToDbParameter("@P1") }, CommandType.Text)); } [TestCaseSource("QueryStatementFormatIfCases")] public void QueryStatementFormatIfReturnsExpectedInstance(IEnumerable<SqlQueryCommand> actual, SqlQueryCommand[] expected) { var actualArray = actual.ToArray(); Assert.That(actualArray.Length, Is.EqualTo(expected.Length)); for (var index = 0; index < actualArray.Length; index++) { Assert.That(actualArray[index].Text, Is.EqualTo(expected[index].Text)); Assert.That(actualArray[index].Parameters, Is.EquivalentTo(expected[index].Parameters).Using(new SqlParameterEqualityComparer())); } } private static IEnumerable<TestCaseData> QueryStatementFormatIfCases() { yield return new TestCaseData( TSql.QueryStatementFormatIf(true, "text"), new[] { new SqlQueryCommand("text", new DbParameter[0], CommandType.Text) }); yield return new TestCaseData( TSql.QueryStatementFormatIf(true, "text", parameters: null), new[] { new SqlQueryCommand("text", new DbParameter[0], CommandType.Text) }); yield return new TestCaseData( TSql.QueryStatementFormatIf(true, "text", new IDbParameterValue[0]), new[] { new SqlQueryCommand("text", new DbParameter[0], CommandType.Text) }); yield return new TestCaseData( TSql.QueryStatementFormatIf(true, "text", new SqlParameterValueStub()), new[] { new SqlQueryCommand("text", new[] { new SqlParameterValueStub().ToDbParameter("@P0") }, CommandType.Text) }); yield return new TestCaseData( TSql.QueryStatementFormatIf(true, "text {0}", new SqlParameterValueStub()), new[] { new SqlQueryCommand("text @P0", new[] { new SqlParameterValueStub().ToDbParameter("@P0") }, CommandType.Text) }); yield return new TestCaseData( TSql.QueryStatementFormatIf(true, "text", new SqlParameterValueStub(), new SqlParameterValueStub()), new[] { new SqlQueryCommand("text", new[] { new SqlParameterValueStub().ToDbParameter("@P0"), new SqlParameterValueStub().ToDbParameter("@P1") }, CommandType.Text) }); yield return new TestCaseData( TSql.QueryStatementFormatIf(true, "text {0} {1}", new SqlParameterValueStub(), new SqlParameterValueStub()), new[] { new SqlQueryCommand("text @P0 @P1", new[] { new SqlParameterValueStub().ToDbParameter("@P0"), new SqlParameterValueStub().ToDbParameter("@P1") }, CommandType.Text) }); yield return new TestCaseData( TSql.QueryStatementFormatIf(false, "text"), new SqlQueryCommand[0]); yield return new TestCaseData( TSql.QueryStatementFormatIf(false, "text", parameters: null), new SqlQueryCommand[0]); yield return new TestCaseData( TSql.QueryStatementFormatIf(false, "text", new IDbParameterValue[0]), new SqlQueryCommand[0]); yield return new TestCaseData( TSql.QueryStatementFormatIf(false, "text", new SqlParameterValueStub()), new SqlQueryCommand[0]); yield return new TestCaseData( TSql.QueryStatementFormatIf(false, "text {0}", new SqlParameterValueStub()), new SqlQueryCommand[0]); yield return new TestCaseData( TSql.QueryStatementFormatIf(false, "text", new SqlParameterValueStub(), new SqlParameterValueStub()), new SqlQueryCommand[0]); yield return new TestCaseData( TSql.QueryStatementFormatIf(false, "text {0} {1}", new SqlParameterValueStub(), new SqlParameterValueStub()), new SqlQueryCommand[0]); } [TestCaseSource("QueryStatementFormatUnlessCases")] public void QueryStatementFormatUnlessReturnsExpectedInstance(IEnumerable<SqlQueryCommand> actual, SqlQueryCommand[] expected) { var actualArray = actual.ToArray(); Assert.That(actualArray.Length, Is.EqualTo(expected.Length)); for (var index = 0; index < actualArray.Length; index++) { Assert.That(actualArray[index].Text, Is.EqualTo(expected[index].Text)); Assert.That(actualArray[index].Parameters, Is.EquivalentTo(expected[index].Parameters).Using(new SqlParameterEqualityComparer())); } } private static IEnumerable<TestCaseData> QueryStatementFormatUnlessCases() { yield return new TestCaseData( TSql.QueryStatementFormatUnless(false, "text"), new[] { new SqlQueryCommand("text", new DbParameter[0], CommandType.Text) }); yield return new TestCaseData( TSql.QueryStatementFormatUnless(false, "text", parameters: null), new[] { new SqlQueryCommand("text", new DbParameter[0], CommandType.Text) }); yield return new TestCaseData( TSql.QueryStatementFormatUnless(false, "text", new IDbParameterValue[0]), new[] { new SqlQueryCommand("text", new DbParameter[0], CommandType.Text) }); yield return new TestCaseData( TSql.QueryStatementFormatUnless(false, "text", new SqlParameterValueStub()), new[] { new SqlQueryCommand("text", new[] { new SqlParameterValueStub().ToDbParameter("@P0") }, CommandType.Text) }); yield return new TestCaseData( TSql.QueryStatementFormatUnless(false, "text {0}", new SqlParameterValueStub()), new[] { new SqlQueryCommand("text @P0", new[] { new SqlParameterValueStub().ToDbParameter("@P0") }, CommandType.Text) }); yield return new TestCaseData( TSql.QueryStatementFormatUnless(false, "text", new SqlParameterValueStub(), new SqlParameterValueStub()), new[] { new SqlQueryCommand("text", new[] { new SqlParameterValueStub().ToDbParameter("@P0"), new SqlParameterValueStub().ToDbParameter("@P1") }, CommandType.Text) }); yield return new TestCaseData( TSql.QueryStatementFormatUnless(false, "text {0} {1}", new SqlParameterValueStub(), new SqlParameterValueStub()), new[] { new SqlQueryCommand("text @P0 @P1", new[] { new SqlParameterValueStub().ToDbParameter("@P0"), new SqlParameterValueStub().ToDbParameter("@P1") }, CommandType.Text) }); yield return new TestCaseData( TSql.QueryStatementFormatUnless(true, "text"), new SqlQueryCommand[0]); yield return new TestCaseData( TSql.QueryStatementFormatUnless(true, "text", parameters: null), new SqlQueryCommand[0]); yield return new TestCaseData( TSql.QueryStatementFormatUnless(true, "text", new IDbParameterValue[0]), new SqlQueryCommand[0]); yield return new TestCaseData( TSql.QueryStatementFormatUnless(true, "text", new SqlParameterValueStub()), new SqlQueryCommand[0]); yield return new TestCaseData( TSql.QueryStatementFormatUnless(true, "text {0}", new SqlParameterValueStub()), new SqlQueryCommand[0]); yield return new TestCaseData( TSql.QueryStatementFormatUnless(true, "text", new SqlParameterValueStub(), new SqlParameterValueStub()), new SqlQueryCommand[0]); yield return new TestCaseData( TSql.QueryStatementFormatUnless(true, "text {0} {1}", new SqlParameterValueStub(), new SqlParameterValueStub()), new SqlQueryCommand[0]); } } }
51.195313
148
0.566814
[ "BSD-3-Clause" ]
ddd-cqrs-es/Projac
src/Paramol.Tests/Legacy/TSqlTests.QueryStatement.cs
19,661
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace DeadManSwitch.UI.Web.AspNet { public partial class Site_Error : System.Web.UI.MasterPage { protected void Page_Load(object sender, EventArgs e) { } } }
19.941176
62
0.702065
[ "MIT" ]
tategriffin/DeadManSwitch
Source/DeadManSwitch.UI.Web.AspNet/Site.Error.Master.cs
341
C#
#pragma checksum "..\..\App.xaml" "{8829d00f-11b8-4213-878b-770e8597ac16}" "566B1D0DDC2F1A4BB448C271237320FFC92F1AFC959F2511484851907AC82C66" //------------------------------------------------------------------------------ // <auto-generated> // Этот код создан программой. // Исполняемая версия:4.0.30319.42000 // // Изменения в этом файле могут привести к неправильной работе и будут потеряны в случае // повторной генерации кода. // </auto-generated> //------------------------------------------------------------------------------ using Messages; using System; using System.Diagnostics; using System.Windows; using System.Windows.Automation; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Ink; using System.Windows.Input; using System.Windows.Markup; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Media.Effects; using System.Windows.Media.Imaging; using System.Windows.Media.Media3D; using System.Windows.Media.TextFormatting; using System.Windows.Navigation; using System.Windows.Shapes; using System.Windows.Shell; namespace Messages { /// <summary> /// App /// </summary> public partial class App : System.Windows.Application { /// <summary> /// InitializeComponent /// </summary> [System.Diagnostics.DebuggerNonUserCodeAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")] public void InitializeComponent() { #line 5 "..\..\App.xaml" this.StartupUri = new System.Uri("MainWindow.xaml", System.UriKind.Relative); #line default #line hidden } /// <summary> /// Application Entry Point. /// </summary> [System.STAThreadAttribute()] [System.Diagnostics.DebuggerNonUserCodeAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")] public static void Main() { Messages.App app = new Messages.App(); app.InitializeComponent(); app.Run(); } } }
32.070423
142
0.621432
[ "Apache-2.0" ]
danilinus/LMClient
Messages/Messages/obj/Debug/App.g.cs
2,413
C#
/* * LeagueClient * * 7.23.209.3517 * * OpenAPI spec version: 1.0.0 * * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Text; using System.Collections.Generic; using System.Runtime.Serialization; using Newtonsoft.Json; using System.ComponentModel.DataAnnotations; namespace LeagueClientApi.Model { /// <summary> /// LolInventoryInventoryResponseDTO /// </summary> [DataContract] public partial class LolInventoryInventoryResponseDTO : IEquatable<LolInventoryInventoryResponseDTO>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="LolInventoryInventoryResponseDTO" /> class. /// </summary> /// <param name="Data">Data.</param> public LolInventoryInventoryResponseDTO(LolInventoryInventoryDTO Data = default(LolInventoryInventoryDTO)) { this.Data = Data; } /// <summary> /// Gets or Sets Data /// </summary> [DataMember(Name="data", EmitDefaultValue=false)] public LolInventoryInventoryDTO Data { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class LolInventoryInventoryResponseDTO {\n"); sb.Append(" Data: ").Append(Data).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as LolInventoryInventoryResponseDTO); } /// <summary> /// Returns true if LolInventoryInventoryResponseDTO instances are equal /// </summary> /// <param name="other">Instance of LolInventoryInventoryResponseDTO to be compared</param> /// <returns>Boolean</returns> public bool Equals(LolInventoryInventoryResponseDTO other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.Data == other.Data || this.Data != null && this.Data.Equals(other.Data) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.Data != null) hash = hash * 59 + this.Data.GetHashCode(); return hash; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) { yield break; } } }
32.162602
140
0.569767
[ "MIT" ]
wildbook/LeagueClientApi
Model/LolInventoryInventoryResponseDTO.cs
3,956
C#
using System; using System.CodeDom.Compiler; using System.ComponentModel; using System.Diagnostics; using System.ServiceModel; namespace Workday.Recruiting { [GeneratedCode("System.ServiceModel", "4.0.0.0"), EditorBrowsable(EditorBrowsableState.Advanced), DebuggerStepThrough, MessageContract(IsWrapped = false)] public class Get_Evergreen_RequisitionsOutput { [MessageBodyMember(Namespace = "urn:com.workday/bsvc", Order = 0)] public Get_Evergreen_Requisitions_ResponseType Get_Evergreen_Requisitions_Response; public Get_Evergreen_RequisitionsOutput() { } public Get_Evergreen_RequisitionsOutput(Get_Evergreen_Requisitions_ResponseType Get_Evergreen_Requisitions_Response) { this.Get_Evergreen_Requisitions_Response = Get_Evergreen_Requisitions_Response; } } }
31.56
155
0.830165
[ "MIT" ]
matteofabbri/Workday.WebServices
Workday.Recruiting/Get_Evergreen_RequisitionsOutput.cs
789
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Diagnostics.ContractsLight; using BuildXL.Native.IO; namespace BuildXL.Native.Streams { /// <summary> /// Result of a pending or completed I/O operation. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes")] public readonly struct FileAsyncIOResult { /// <summary> /// Success / completion status. The rest of the result is not valid when the status is <see cref="FileAsyncIOStatus.Pending"/>. /// </summary> public readonly FileAsyncIOStatus Status; private readonly int m_bytesTransferred; private readonly int m_error; internal FileAsyncIOResult(FileAsyncIOStatus status, int bytesTransferred, int error) { Contract.Requires(bytesTransferred >= 0); Contract.Requires((status == FileAsyncIOStatus.Succeeded) == (error == NativeIOConstants.ErrorSuccess)); Status = status; m_bytesTransferred = bytesTransferred; m_error = error; } /// <summary> /// Number of bytes transferred (from the requested start offset). /// Present only when the result status is not <see cref="FileAsyncIOStatus.Pending"/>. /// </summary> public int BytesTransferred { get { Contract.Requires(Status != FileAsyncIOStatus.Pending); return m_bytesTransferred; } } /// <summary> /// Native error code. /// Present only when the result status is not <see cref="FileAsyncIOStatus.Pending"/>. /// If the status is <see cref="FileAsyncIOStatus.Succeeded"/>, then this is <c>ERROR_SUCCESS</c>. /// </summary> public int Error { get { Contract.Requires(Status != FileAsyncIOStatus.Pending); return m_error; } } /// <summary> /// Indicates if the native error code specifies that the end of the file has been reached (specific to reading). /// Present only when the result status is not <see cref="FileAsyncIOStatus.Pending"/>. /// </summary> public bool ErrorIndicatesEndOfFile { get { return Error == NativeIOConstants.ErrorHandleEof; } } } }
37.055556
137
0.591454
[ "MIT" ]
AzureMentor/BuildXL
Public/Src/Utilities/Native/Streams/FileAsyncIOResult.cs
2,668
C#
namespace SoftJail.Data { using Microsoft.EntityFrameworkCore; using SoftJail.Data.Models; public class SoftJailDbContext : DbContext { public SoftJailDbContext(){} public SoftJailDbContext(DbContextOptions options) : base(options) {} public DbSet<Prisoner> Prisoners { get; set; } public DbSet<Officer> Officers { get; set; } public DbSet<Mail> Mails { get; set; } public DbSet<Cell> Cells { get; set; } public DbSet<Department> Departments { get; set; } public DbSet<OfficerPrisoner> OfficersPrisoners { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { if (!optionsBuilder.IsConfigured) { optionsBuilder .UseSqlServer(Configuration.ConnectionString); } } protected override void OnModelCreating(ModelBuilder builder) { builder .Entity<OfficerPrisoner>(entity => { entity.HasKey(op => new { op.OfficerId, op.PrisonerId }); entity .HasOne(op => op.Prisoner) .WithMany(p => p.PrisonerOfficers) .HasForeignKey(op => op.PrisonerId); entity .HasOne(op => op.Officer) .WithMany(o => o.OfficerPrisoners) .HasForeignKey(op => op.OfficerId); }); } } }
27.653846
85
0.579972
[ "MIT" ]
CvetelinLozanov/SoftUni-C-
DBSQL-Advanced/01. Model Definition_Skeleton and Datasets/SoftJail/Data/SoftJailDbContext.cs
1,440
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; namespace Microsoft.CodeAnalysis.Sarif.Visitors { public class RemoveOptionalDataVisitor : SarifRewritingVisitor { public RemoveOptionalDataVisitor(OptionallyEmittedData optionallyEmittedData) { _dataToRemove = optionallyEmittedData; } private readonly OptionallyEmittedData _dataToRemove; public override Invocation VisitInvocation(Invocation node) { if (_dataToRemove.HasFlag(OptionallyEmittedData.NondeterministicProperties)) { node.StartTimeUtc = new DateTime(); node.EndTimeUtc = new DateTime(); } return base.VisitInvocation(node); } public override Notification VisitNotification(Notification node) { if (_dataToRemove.HasFlag(OptionallyEmittedData.NondeterministicProperties)) { node.TimeUtc = new DateTime(); } return base.VisitNotification(node); } public override PhysicalLocation VisitPhysicalLocation(PhysicalLocation node) { if (_dataToRemove.HasFlag(OptionallyEmittedData.ContextRegionSnippets) && node.ContextRegion != null) { node.ContextRegion.Snippet = null; } if (_dataToRemove.HasFlag(OptionallyEmittedData.RegionSnippets) && node.Region != null) { node.Region.Snippet = null; } return base.VisitPhysicalLocation(node); } public override Artifact VisitArtifact(Artifact node) { if (_dataToRemove.HasFlag(OptionallyEmittedData.BinaryFiles) && node.Contents?.Binary != null) { node.Contents.Binary = null; } if (_dataToRemove.HasFlag(OptionallyEmittedData.TextFiles) && node.Contents?.Text != null) { node.Contents.Text = null; } return base.VisitArtifact(node); } public override Result VisitResult(Result node) { if (_dataToRemove.HasFlag(OptionallyEmittedData.Guids)) { node.Guid = null; } if (_dataToRemove.HasFlag(OptionallyEmittedData.CodeFlows)) { node.CodeFlows = null; } return base.VisitResult(node); } } }
30.785714
113
0.594741
[ "MIT" ]
LaudateCorpus1/sarif-sdk
src/Sarif/Visitors/RemoveOptionalDataVisitor.cs
2,588
C#
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // 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 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Visual Studio - IronPython interpreters")] [assembly: AssemblyDescription("Provides support for IronPython interpreters.")] [assembly: ComVisible(false)] [assembly: Guid("6EBFBF59-39BC-4C0A-8366-94796A551241")] [assembly: InternalsVisibleTo("Microsoft.PythonTools.IronPython, PublicKey=002400000480000094000000060200000024000052534131000400000100010007d1fa57c4aed9f0a32e84aa0faefd0de9e8fd6aec8f87fb03766c834c99921eb23be79ad9d5dcc1dd9ad236132102900b723cf980957fc4e177108fc607774f29e8320e92ea05ece4e821c0a5efe8f1645c4c0c93c1ab99285d622caa652c1dfad63d745d6f2de5f17e5eaf0fc4963d261c8a12436518206dc093344d5ad293")] [assembly: InternalsVisibleTo("AnalysisTests, PublicKey=002400000480000094000000060200000024000052534131000400000100010007d1fa57c4aed9f0a32e84aa0faefd0de9e8fd6aec8f87fb03766c834c99921eb23be79ad9d5dcc1dd9ad236132102900b723cf980957fc4e177108fc607774f29e8320e92ea05ece4e821c0a5efe8f1645c4c0c93c1ab99285d622caa652c1dfad63d745d6f2de5f17e5eaf0fc4963d261c8a12436518206dc093344d5ad293")] [assembly: InternalsVisibleTo("IronPythonTests, PublicKey=002400000480000094000000060200000024000052534131000400000100010007d1fa57c4aed9f0a32e84aa0faefd0de9e8fd6aec8f87fb03766c834c99921eb23be79ad9d5dcc1dd9ad236132102900b723cf980957fc4e177108fc607774f29e8320e92ea05ece4e821c0a5efe8f1645c4c0c93c1ab99285d622caa652c1dfad63d745d6f2de5f17e5eaf0fc4963d261c8a12436518206dc093344d5ad293")] [assembly: InternalsVisibleTo("PythonToolsUITests, PublicKey=002400000480000094000000060200000024000052534131000400000100010007d1fa57c4aed9f0a32e84aa0faefd0de9e8fd6aec8f87fb03766c834c99921eb23be79ad9d5dcc1dd9ad236132102900b723cf980957fc4e177108fc607774f29e8320e92ea05ece4e821c0a5efe8f1645c4c0c93c1ab99285d622caa652c1dfad63d745d6f2de5f17e5eaf0fc4963d261c8a12436518206dc093344d5ad293")] [assembly: InternalsVisibleTo("ReplWindowUITests, PublicKey=002400000480000094000000060200000024000052534131000400000100010007d1fa57c4aed9f0a32e84aa0faefd0de9e8fd6aec8f87fb03766c834c99921eb23be79ad9d5dcc1dd9ad236132102900b723cf980957fc4e177108fc607774f29e8320e92ea05ece4e821c0a5efe8f1645c4c0c93c1ab99285d622caa652c1dfad63d745d6f2de5f17e5eaf0fc4963d261c8a12436518206dc093344d5ad293")] [assembly: InternalsVisibleTo("ReplWindowUITestsIRON27, PublicKey=002400000480000094000000060200000024000052534131000400000100010007d1fa57c4aed9f0a32e84aa0faefd0de9e8fd6aec8f87fb03766c834c99921eb23be79ad9d5dcc1dd9ad236132102900b723cf980957fc4e177108fc607774f29e8320e92ea05ece4e821c0a5efe8f1645c4c0c93c1ab99285d622caa652c1dfad63d745d6f2de5f17e5eaf0fc4963d261c8a12436518206dc093344d5ad293")]
99.5
398
0.907774
[ "Apache-2.0" ]
alepao821/PTVS
Python/Product/IronPython/Interpreter/AssemblyInfo.cs
3,383
C#
using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace advent_of_code_2018 { class Day07 { public class Node: IComparable<Node> { public char name; public List<Node> parents; public List<Node> children; public bool ready; public Node(char p_name) { name = p_name; parents = new List<Node>(); children = new List<Node>(); ready = false; } public override string ToString() { return name.ToString(); } public override bool Equals(object obj) { var other = obj as Node; return (name == other.name); } public override int GetHashCode() { return name.GetHashCode(); } public int CompareTo(Node other) { return name.CompareTo(other.name); } } public List<Node> ParseFile(string filename) { IDictionary<char, Node> nodes = new Dictionary<char, Node>(); foreach (string line in File.ReadLines(filename)) { string[] parts = line.Split(" "); char parent = parts[1][0]; char child = parts[7][0]; if (! nodes.ContainsKey(parent)) nodes.Add(parent, new Node(parent)); if (! nodes.ContainsKey(child)) nodes.Add(child, new Node(child)); nodes[parent].children.Add(nodes[child]); nodes[child].parents.Add(nodes[parent]); } return nodes.Values.ToList(); } private class Worker { public Node job; public int duration; private int _step; private int _time; public Worker(int p_step) { job = null; _step = p_step; } public void AssignWork(Node p_job) { _time = 0; job = p_job; duration = (int)(job.name) - 64 + _step; } public Node DoWork() { _time++; return (duration == _time) ? job : null; } } public void SolveA() { List<Node> nodes = ParseFile("07_input.txt"); List<Node> done = new List<Node>(); List<Node> todo = nodes.Where(n => n.parents.Count() == 0).ToList(); List<Node> ready = new List<Node>(); while (done.Count() < nodes.Count()) { Node job = todo.Where(n => (n.parents.Where(p => !done.Contains(p)).Count()) == 0) .OrderBy(n => n) .First(); todo.Remove(job); done.Add(job); todo = todo.Union(job.children).ToList(); } string result = string.Join("", done.Select(n => n.name)); Console.WriteLine("Day 07 A: " + result); } public void SolveB() { List<Node> nodes = ParseFile("07_input.txt"); List<Node> done = new List<Node>(); List<Node> todo = nodes.Where(n => n.parents.Count() == 0).ToList(); List<Node> ready = new List<Node>(); List<Worker> workers = new List<Worker>(); int duration = 0; int step = 60; for (int i=0; i<5; i++) { workers.Add(new Worker(step)); } while (done.Count() < nodes.Count()) { duration++; // Assign work ready = todo.Where(n => (n.parents.Where(p => !done.Contains(p)).Count()) == 0) .OrderBy(n => n) .ToList(); foreach (Worker w in workers) { if ( (ready.Count() > 0) && (w.job == null) ) { Node job = ready.First(); ready.Remove(job); todo.Remove(job); w.AssignWork(job); } } // do some work foreach (Worker w in workers) { Node result = w.DoWork(); if (result != null) { done.Add(result); todo = todo.Union(result.children).ToList(); w.job = null; } } } string code = string.Join("", done.Select(n => n.name)); Console.WriteLine("Day 07 B: " + code + " (" + duration + ")"); } } }
29.33908
98
0.410578
[ "MIT" ]
patboyer/advent_of_code_2018
Day07.cs
5,105
C#
/* * Copyright (c) 2018 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ namespace TencentCloud.Vpc.V20170312.Models { using Newtonsoft.Json; using System.Collections.Generic; using TencentCloud.Common; public class ModifySecurityGroupPoliciesRequest : AbstractModel { /// <summary> /// 安全组实例ID,例如sg-33ocnj9n,可通过DescribeSecurityGroups获取。 /// </summary> [JsonProperty("SecurityGroupId")] public string SecurityGroupId{ get; set; } /// <summary> /// 安全组规则集合。 SecurityGroupPolicySet对象必须同时指定新的出(Egress)入(Ingress)站规则。 SecurityGroupPolicy对象不支持自定义索引(PolicyIndex)。 /// </summary> [JsonProperty("SecurityGroupPolicySet")] public SecurityGroupPolicySet SecurityGroupPolicySet{ get; set; } /// <summary> /// 内部实现,用户禁止调用 /// </summary> internal override void ToMap(Dictionary<string, string> map, string prefix) { this.SetParamSimple(map, prefix + "SecurityGroupId", this.SecurityGroupId); this.SetParamObj(map, prefix + "SecurityGroupPolicySet.", this.SecurityGroupPolicySet); } } }
34.078431
120
0.680667
[ "Apache-2.0" ]
Darkfaker/tencentcloud-sdk-dotnet
TencentCloud/Vpc/V20170312/Models/ModifySecurityGroupPoliciesRequest.cs
1,872
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Maui; using System.Maui.Xaml; namespace System.Maui.Controls.GalleryPages.VisualStateManagerGalleries { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class VisualStateSetterTarget : ContentPage { string _currentColorState = "Normal"; public VisualStateSetterTarget() { InitializeComponent (); } void ToggleValid_OnClicked(object sender, EventArgs e) { if (_currentColorState == "Normal") { _currentColorState = "Invalid"; } else { _currentColorState = "Normal"; } CurrentState.Text = $"Current state: {_currentColorState}"; VisualStateManager.GoToState(TheStack, _currentColorState); } } }
21.486486
71
0.74717
[ "MIT" ]
AswinPG/maui
System.Maui.Controls/GalleryPages/VisualStateManagerGalleries/VisualStateSetterTarget.xaml.cs
795
C#
// Copyright (c) Six Labors. // Licensed under the Apache License, Version 2.0. using System.Numerics; using System.Runtime.CompilerServices; using SixLabors.ImageSharp.Memory; // ReSharper disable UseObjectOrCollectionInitializer // ReSharper disable InconsistentNaming namespace SixLabors.ImageSharp.Formats.Jpeg.Components { internal partial struct Block8x8F { /// <summary> /// Copy block data into the destination color buffer pixel area with the provided horizontal and vertical scale factors. /// </summary> [MethodImpl(InliningOptions.ShortMethod)] public void ScaledCopyTo(in Buffer2DRegion<float> region, int horizontalScale, int verticalScale) { ref float areaOrigin = ref region.GetReferenceToOrigin(); this.ScaledCopyTo(ref areaOrigin, region.Stride, horizontalScale, verticalScale); } [MethodImpl(InliningOptions.ShortMethod)] public void ScaledCopyTo(ref float areaOrigin, int areaStride, int horizontalScale, int verticalScale) { if (horizontalScale == 1 && verticalScale == 1) { this.Copy1x1Scale(ref areaOrigin, areaStride); return; } if (horizontalScale == 2 && verticalScale == 2) { this.Copy2x2Scale(ref areaOrigin, areaStride); return; } // TODO: Optimize: implement all cases with scale-specific, loopless code! this.CopyArbitraryScale(ref areaOrigin, areaStride, horizontalScale, verticalScale); } public void Copy1x1Scale(ref float areaOrigin, int areaStride) { ref byte selfBase = ref Unsafe.As<Block8x8F, byte>(ref this); ref byte destBase = ref Unsafe.As<float, byte>(ref areaOrigin); int destStride = areaStride * sizeof(float); CopyRowImpl(ref selfBase, ref destBase, destStride, 0); CopyRowImpl(ref selfBase, ref destBase, destStride, 1); CopyRowImpl(ref selfBase, ref destBase, destStride, 2); CopyRowImpl(ref selfBase, ref destBase, destStride, 3); CopyRowImpl(ref selfBase, ref destBase, destStride, 4); CopyRowImpl(ref selfBase, ref destBase, destStride, 5); CopyRowImpl(ref selfBase, ref destBase, destStride, 6); CopyRowImpl(ref selfBase, ref destBase, destStride, 7); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void CopyRowImpl(ref byte selfBase, ref byte destBase, int destStride, int row) { ref byte s = ref Unsafe.Add(ref selfBase, row * 8 * sizeof(float)); ref byte d = ref Unsafe.Add(ref destBase, row * destStride); Unsafe.CopyBlock(ref d, ref s, 8 * sizeof(float)); } private void Copy2x2Scale(ref float areaOrigin, int areaStride) { ref Vector2 destBase = ref Unsafe.As<float, Vector2>(ref areaOrigin); int destStride = areaStride / 2; this.WidenCopyRowImpl2x2(ref destBase, 0, destStride); this.WidenCopyRowImpl2x2(ref destBase, 1, destStride); this.WidenCopyRowImpl2x2(ref destBase, 2, destStride); this.WidenCopyRowImpl2x2(ref destBase, 3, destStride); this.WidenCopyRowImpl2x2(ref destBase, 4, destStride); this.WidenCopyRowImpl2x2(ref destBase, 5, destStride); this.WidenCopyRowImpl2x2(ref destBase, 6, destStride); this.WidenCopyRowImpl2x2(ref destBase, 7, destStride); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void WidenCopyRowImpl2x2(ref Vector2 destBase, int row, int destStride) { ref Vector4 sLeft = ref Unsafe.Add(ref this.V0L, 2 * row); ref Vector4 sRight = ref Unsafe.Add(ref sLeft, 1); int offset = 2 * row * destStride; ref Vector4 dTopLeft = ref Unsafe.As<Vector2, Vector4>(ref Unsafe.Add(ref destBase, offset)); ref Vector4 dBottomLeft = ref Unsafe.As<Vector2, Vector4>(ref Unsafe.Add(ref destBase, offset + destStride)); var xyLeft = new Vector4(sLeft.X); xyLeft.Z = sLeft.Y; xyLeft.W = sLeft.Y; var zwLeft = new Vector4(sLeft.Z); zwLeft.Z = sLeft.W; zwLeft.W = sLeft.W; var xyRight = new Vector4(sRight.X); xyRight.Z = sRight.Y; xyRight.W = sRight.Y; var zwRight = new Vector4(sRight.Z); zwRight.Z = sRight.W; zwRight.W = sRight.W; dTopLeft = xyLeft; Unsafe.Add(ref dTopLeft, 1) = zwLeft; Unsafe.Add(ref dTopLeft, 2) = xyRight; Unsafe.Add(ref dTopLeft, 3) = zwRight; dBottomLeft = xyLeft; Unsafe.Add(ref dBottomLeft, 1) = zwLeft; Unsafe.Add(ref dBottomLeft, 2) = xyRight; Unsafe.Add(ref dBottomLeft, 3) = zwRight; } [MethodImpl(InliningOptions.ColdPath)] private void CopyArbitraryScale(ref float areaOrigin, int areaStride, int horizontalScale, int verticalScale) { for (int y = 0; y < 8; y++) { int yy = y * verticalScale; int y8 = y * 8; for (int x = 0; x < 8; x++) { int xx = x * horizontalScale; float value = this[y8 + x]; for (int i = 0; i < verticalScale; i++) { int baseIdx = ((yy + i) * areaStride) + xx; for (int j = 0; j < horizontalScale; j++) { // area[xx + j, yy + i] = value; Unsafe.Add(ref areaOrigin, baseIdx + j) = value; } } } } } } }
40.358108
129
0.578771
[ "Apache-2.0" ]
0xced/ImageSharp
src/ImageSharp/Formats/Jpeg/Components/Block8x8F.ScaledCopyTo.cs
5,973
C#
//------------------------------------------------------------------------------ // <auto-generated> // Este código se generó a partir de una plantilla. // // Los cambios manuales en este archivo pueden causar un comportamiento inesperado de la aplicación. // Los cambios manuales en este archivo se sobrescribirán si se regenera el código. // </auto-generated> //------------------------------------------------------------------------------ namespace WebApiAdventure.AdventureWork { using System; using System.Collections.Generic; public partial class EmployeeDepartmentHistory { public int BusinessEntityID { get; set; } public short DepartmentID { get; set; } public byte ShiftID { get; set; } public System.DateTime StartDate { get; set; } public Nullable<System.DateTime> EndDate { get; set; } public System.DateTime ModifiedDate { get; set; } public virtual Department Department { get; set; } public virtual Employee Employee { get; set; } public virtual Shift Shift { get; set; } } }
38.206897
104
0.573105
[ "MIT" ]
javiergandres/PracticasNET
TiendaOnlineDroid/WebApiAdventure/AdventureWork/EmployeeDepartmentHistory.cs
1,113
C#
using Amazon.CDK; using System; using System.Collections.Generic; using System.Linq; namespace %name.PascalCased% { class Program { static void Main(string[] args) { var app = new App(null); new %name.PascalCased%Stack(app, "%name.PascalCased%Stack", new StackProps()); app.Synth(); } } }
20.166667
90
0.584022
[ "Apache-2.0" ]
0gajun/aws-cdk
packages/aws-cdk/lib/init-templates/app/csharp/src/%name.PascalCased%/Program.template.cs
365
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Utf8Json.AspNetCoreMvcFormatter")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: Guid("899f8b6c-c4c7-4e8b-9875-f61fdfb630bd")] [assembly: AssemblyVersion("1.3.7")] [assembly: AssemblyFileVersion("1.3.7")]
31.4375
60
0.77336
[ "MIT" ]
AlexeyVoid/Utf8Json
src/Utf8Json.AspNetCoreMvcFormatter/_AssemblyInfo.cs
505
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.Security.Permissions { #if NET5_0_OR_GREATER [Obsolete(Obsoletions.CodeAccessSecurityMessage, DiagnosticId = Obsoletions.CodeAccessSecurityDiagId, UrlFormat = Obsoletions.SharedUrlFormat)] #endif public abstract class IsolatedStoragePermissionAttribute : CodeAccessSecurityAttribute { protected IsolatedStoragePermissionAttribute(SecurityAction action) : base(action) { } public long UserQuota { get; set; } public IsolatedStorageContainment UsageAllowed { get; set; } } }
41.75
147
0.773952
[ "MIT" ]
333fred/runtime
src/libraries/System.Security.Permissions/src/System/Security/Permissions/IsolatedStoragePermissionAttribute.cs
668
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace FlatRedBall.Glue.Plugins.EmbeddedPlugins { public abstract class EmbeddedPlugin : PluginBase { public override string FriendlyName { get { return "Embedded Plugin"; } } public override Version Version { get { return new Version(); } } public override bool ShutDown(Interfaces.PluginShutDownReason shutDownReason) { // this can't be shut down return false; } } }
22.037037
85
0.605042
[ "MIT" ]
derKosi/FlatRedBall
FRBDK/Glue/Glue/Plugins/EmbeddedPlugins/EmbeddedPlugin.cs
597
C#
using System; using System.Collections.Generic; using System.Text; public class Brackets { // taken from https://msdn.microsoft.com/en-us/library/x53a06bb.aspx - remove all known keywords which can invoke methods (primitive data types) - example int.Parse private static string[] keywords = { "abstract", "as", "base", "break", "case", "catch", "checked", "class", "const", "continue", "default", "delegate", "do", "else", "enum", "event", "explicit", "extern", "false", "finally", "fixed", "for", "foreach", "goto", "if", "implicit", "in", "interface", "internal", "is", "lock", "namespace", "new", "null", "operator", "out", "override", "params", "private", "protected", "public", "readonly", "ref", "return", "sealed", "sizeof", "stackalloc", "static", "struct", "switch", "this", "throw", "true", "try", "typeof", "unchecked", "unsafe", "using", "virtual", "void", "volatile", "while" }; public static void Main() { int numberOfLines = int.Parse(Console.ReadLine()); List<string> methodCalls = new List<string>(); int foundMethods = 0; for (int i = 0; i < numberOfLines; i++) { string currentReadLineTrimmed = Console.ReadLine().Trim(); int indexOfMethodDeclaration = 0; if (currentReadLineTrimmed.IndexOf("static ") == 0) { if (methodCalls.Count > 0) { Console.WriteLine(string.Join(", ", methodCalls)); } if (foundMethods > 0 && methodCalls.Count == 0) { Console.WriteLine("None"); } methodCalls.Clear(); int indexOfOpenBracket = currentReadLineTrimmed.IndexOf("("); int indexOfWhiteSpace = indexOfOpenBracket; while (!char.IsLetter(currentReadLineTrimmed[indexOfWhiteSpace])) { indexOfWhiteSpace--; } int indexOfSpaceBeforeBracket = currentReadLineTrimmed.LastIndexOf(" ", indexOfWhiteSpace); indexOfMethodDeclaration = indexOfOpenBracket; Console.Write(currentReadLineTrimmed.Substring(indexOfSpaceBeforeBracket + 1, indexOfOpenBracket - indexOfSpaceBeforeBracket - 1).Trim()); Console.Write(" -> "); foundMethods++; } var currentWord = new StringBuilder(); bool isKeyWord = false; string lastKeyword = string.Empty; for (int j = indexOfMethodDeclaration; j < currentReadLineTrimmed.Length; j++) { if (char.IsLetter(currentReadLineTrimmed[j])) { currentWord.Append(currentReadLineTrimmed[j]); continue; } if (!char.IsLetter(currentReadLineTrimmed[j]) && currentWord.Length > 0) { var currentWordString = currentWord.ToString(); if (Array.IndexOf(keywords, currentWordString) > -1) { isKeyWord = true; currentWord.Clear(); lastKeyword = currentWordString; continue; } else if (lastKeyword != "new") { isKeyWord = false; } if (CheckForMethodCall(currentReadLineTrimmed, j)) { if (isKeyWord) { isKeyWord = false; currentWord.Clear(); continue; } isKeyWord = false; methodCalls.Add(currentWordString); } currentWord.Clear(); } } } if (methodCalls.Count > 0) { Console.WriteLine(string.Join(", ", methodCalls)); } if (foundMethods > 0 && methodCalls.Count == 0) { Console.WriteLine("None"); } } private static bool CheckForMethodCall(string line, int position) { for (int i = position; i < line.Length; i++) { if (line[i] == ' ') { continue; } if (line[i] == '(') { return true; } break; } return false; } }
27.530928
168
0.415091
[ "MIT" ]
SimoPrG/HighQualityCodeHomework
HighQualityMethods/Task2.CSharp2ExamRefactored/Brackets/Brackets.cs
5,343
C#
using Aiursoft.Handler.Exceptions; using Aiursoft.Handler.Models; using Aiursoft.Probe.SDK.Models.FilesAddressModels; using Aiursoft.Probe.SDK.Models.FilesViewModels; using Aiursoft.Scanner.Interfaces; using Aiursoft.XelNaga.Models; using Aiursoft.XelNaga.Services; using Aiursoft.XelNaga.Tools; using Newtonsoft.Json; using System.IO; using System.Threading.Tasks; namespace Aiursoft.Probe.SDK.Services.ToProbeServer { public class FilesService : IScopedDependency { private readonly HTTPService _http; private readonly ProbeLocator _serviceLocation; public FilesService( HTTPService http, ProbeLocator serviceLocation) { _http = http; _serviceLocation = serviceLocation; } public async Task<UploadFileViewModel> UploadFileAsync(string accessToken, string siteName, string folderNames, Stream file, bool recursiveCreate = false) { var url = new AiurUrl(_serviceLocation.Endpoint, $"/Files/UploadFile/{siteName.ToUrlEncoded()}/{folderNames.EncodePath()}", new UploadFileAddressModel { Token = accessToken, RecursiveCreate = recursiveCreate }); var result = await _http.PostWithFile(url, file, true); var jResult = JsonConvert.DeserializeObject<UploadFileViewModel>(result); if (jResult.Code != ErrorType.Success) throw new AiurUnexpectedResponse(jResult); return jResult; } public async Task<AiurProtocol> DeleteFileAsync(string accessToken, string siteName, string folderNames) { var url = new AiurUrl(_serviceLocation.Endpoint, $"/Files/DeleteFile/{siteName.ToUrlEncoded()}/{folderNames.EncodePath()}", new { }); var form = new AiurUrl(string.Empty, new DeleteFileAddressModel { AccessToken = accessToken }); var result = await _http.Post(url, form, true); var jResult = JsonConvert.DeserializeObject<AiurProtocol>(result); if (jResult.Code != ErrorType.Success) throw new AiurUnexpectedResponse(jResult); return jResult; } public async Task<UploadFileViewModel> CopyFileAsync(string accessToken, string siteName, string folderNames, string targetSiteName, string targetFolderNames) { if (string.IsNullOrWhiteSpace(targetFolderNames)) { targetFolderNames = "/"; } var url = new AiurUrl(_serviceLocation.Endpoint, $"/Files/CopyFile/{siteName.ToUrlEncoded()}/{folderNames.EncodePath()}", new { }); var form = new AiurUrl(string.Empty, new CopyFileAddressModel { AccessToken = accessToken, TargetSiteName = targetSiteName, TargetFolderNames = targetFolderNames }); var result = await _http.Post(url, form, true); var jResult = JsonConvert.DeserializeObject<UploadFileViewModel>(result); if (jResult.Code != ErrorType.Success) throw new AiurUnexpectedResponse(jResult); return jResult; } } }
42.618421
166
0.645261
[ "MIT" ]
gaufung/Infrastructures
src/Infrastructure/Probe.SDK/Services/ToProbeServer/FilesService.cs
3,241
C#