content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
//----------------------------------------------------------------------- // <copyright file="PinchGesture.cs" company="Google"> // // Copyright 2018 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // </copyright> //----------------------------------------------------------------------- namespace GoogleARCore.Examples.ObjectManipulation { using GoogleARCore.Examples.ObjectManipulationInternal; using UnityEngine; /// <summary> /// Gesture for when the user performs a two-finger pinch motion on the touch screen. /// </summary> public class PinchGesture : Gesture<PinchGesture> { /// <summary> /// Constructs a PinchGesture gesture. /// </summary> /// <param name="recognizer">The gesture recognizer.</param> /// <param name="touch1">The first touch that started this gesture.</param> /// <param name="touch2">The second touch that started this gesture.</param> public PinchGesture(PinchGestureRecognizer recognizer, Touch touch1, Touch touch2) : base(recognizer) { FingerId1 = touch1.fingerId; FingerId2 = touch2.fingerId; StartPosition1 = touch1.position; StartPosition2 = touch2.position; } /// <summary> /// Gets the id of the first finger used in this gesture. /// </summary> public int FingerId1 { get; private set; } /// <summary> /// Gets the id of the second finger used in this gesture. /// </summary> public int FingerId2 { get; private set; } /// <summary> /// Gets the screen position of the first finger where the gesture started. /// </summary> public Vector2 StartPosition1 { get; private set; } /// <summary> /// Gets the screen position of the second finger where the gesture started. /// </summary> public Vector2 StartPosition2 { get; private set; } /// <summary> /// Gets the gap between then position of the first and second fingers. /// </summary> public float Gap { get; private set; } /// <summary> /// Gets the gap delta between then position of the first and second fingers. /// </summary> public float GapDelta { get; private set; } /// <summary> /// Returns true if this gesture can start. /// </summary> /// <returns>True if the gesture can start.</returns> protected internal override bool CanStart() { if (GestureTouchesUtility.IsFingerIdRetained(FingerId1) || GestureTouchesUtility.IsFingerIdRetained(FingerId2)) { Cancel(); return false; } Touch touch1, touch2; bool foundTouches = GestureTouchesUtility.TryFindTouch(FingerId1, out touch1); foundTouches = GestureTouchesUtility.TryFindTouch(FingerId2, out touch2) && foundTouches; if (!foundTouches) { Cancel(); return false; } // Check that at least one finger is moving. if (touch1.deltaPosition == Vector2.zero && touch2.deltaPosition == Vector2.zero) { return false; } PinchGestureRecognizer pinchRecognizer = m_Recognizer as PinchGestureRecognizer; Vector3 firstToSecondDirection = (StartPosition1 - StartPosition2).normalized; float dot1 = Vector3.Dot(touch1.deltaPosition.normalized, -firstToSecondDirection); float dot2 = Vector3.Dot(touch2.deltaPosition.normalized, firstToSecondDirection); float dotThreshold = Mathf.Cos(pinchRecognizer.m_SlopMotionDirectionDegrees * Mathf.Deg2Rad); // Check angle of motion for the first touch. if (touch1.deltaPosition != Vector2.zero && Mathf.Abs(dot1) < dotThreshold) { return false; } // Check angle of motion for the second touch. if (touch2.deltaPosition != Vector2.zero && Mathf.Abs(dot2) < dotThreshold) { return false; } float startgap = (StartPosition1 - StartPosition2).magnitude; Gap = (touch1.position - touch2.position).magnitude; float separation = GestureTouchesUtility.PixelsToInches(Mathf.Abs(Gap - startgap)); if (separation < pinchRecognizer.m_SlopInches) { return false; } return true; } /// <summary> /// Action to be performed when this gesture is started. /// </summary> protected internal override void OnStart() { GestureTouchesUtility.LockFingerId(FingerId1); GestureTouchesUtility.LockFingerId(FingerId2); } /// <summary> /// Updates this gesture. /// </summary> /// <returns>True if the update was successful.</returns> protected internal override bool UpdateGesture() { Touch touch1, touch2; bool foundTouches = GestureTouchesUtility.TryFindTouch(FingerId1, out touch1); foundTouches = GestureTouchesUtility.TryFindTouch(FingerId2, out touch2) && foundTouches; if (!foundTouches) { Cancel(); return false; } if (touch1.phase == TouchPhase.Canceled || touch2.phase == TouchPhase.Canceled) { Cancel(); return false; } if (touch1.phase == TouchPhase.Ended || touch2.phase == TouchPhase.Ended) { Complete(); return false; } if (touch1.phase == TouchPhase.Moved || touch2.phase == TouchPhase.Moved) { float newgap = (touch1.position - touch2.position).magnitude; GapDelta = newgap - Gap; Gap = newgap; return true; } return false; } /// <summary> /// Action to be performed when this gesture is cancelled. /// </summary> protected internal override void OnCancel() { } /// <summary> /// Action to be performed when this gesture is finished. /// </summary> protected internal override void OnFinish() { GestureTouchesUtility.ReleaseFingerId(FingerId1); GestureTouchesUtility.ReleaseFingerId(FingerId2); } } }
36.232323
109
0.572623
[ "Apache-2.0" ]
BSAA0203/AR_duino_GUN
AR_Shot_Bluetooth/Assets/GoogleARCore/Examples/ObjectManipulation/Scripts/Gestures/PinchGesture.cs
7,176
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleAppAdo.Domain { public class PedidoHandler { public PedidoHandler() { } public Pedido AdicionarPedido() { var pedido = new Pedido(DateTimeOffset.Now, cliente, itens); } } }
12.272727
72
0.592593
[ "MIT" ]
lincolnzocateli/ADO.NET
Domain/PedidoHandler.cs
407
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Linq; using Xunit; namespace System.Threading.Tasks.Dataflow.Tests { public class TransformBlockTests { [Fact] public async Task TestCtor() { var blocks = new[] { new TransformBlock<int, string>(i => i.ToString()), new TransformBlock<int, string>(i => i.ToString(), new ExecutionDataflowBlockOptions { MaxMessagesPerTask = 1 }), new TransformBlock<int, string>(i => Task.Run(() => i.ToString()), new ExecutionDataflowBlockOptions { MaxMessagesPerTask = 1 }) }; foreach (var block in blocks) { Assert.Equal(expected: 0, actual: block.InputCount); Assert.Equal(expected: 0, actual: block.OutputCount); Assert.False(block.Completion.IsCompleted); } blocks = new[] { new TransformBlock<int, string>(i => i.ToString(), new ExecutionDataflowBlockOptions { CancellationToken = new CancellationToken(true) }), new TransformBlock<int, string>(i => Task.Run(() => i.ToString()), new ExecutionDataflowBlockOptions { CancellationToken = new CancellationToken(true) }) }; foreach (var block in blocks) { Assert.Equal(expected: 0, actual: block.InputCount); Assert.Equal(expected: 0, actual: block.OutputCount); await Assert.ThrowsAnyAsync<OperationCanceledException>(() => block.Completion); } } [Fact] public void TestArgumentExceptions() { Assert.Throws<ArgumentNullException>(() => new TransformBlock<int, int>((Func<int, int>)null)); Assert.Throws<ArgumentNullException>(() => new TransformBlock<int, int>((Func<int, Task<int>>)null)); Assert.Throws<ArgumentNullException>(() => new TransformBlock<int, int>(i => i, null)); Assert.Throws<ArgumentNullException>(() => new TransformBlock<int, int>(i => Task.Run(() => i), null)); DataflowTestHelpers.TestArgumentsExceptions(new TransformBlock<int, int>(i => i)); } [Fact] public void TestToString() { DataflowTestHelpers.TestToString(nameFormat => nameFormat != null ? new TransformBlock<int, int>(i => i, new ExecutionDataflowBlockOptions() { NameFormat = nameFormat }) : new TransformBlock<int, int>(i => i)); } [Fact] public async Task TestOfferMessage() { var generators = new Func<TransformBlock<int, int>>[] { () => new TransformBlock<int, int>(i => i), () => new TransformBlock<int, int>(i => i, new ExecutionDataflowBlockOptions { BoundedCapacity = 10 }), () => new TransformBlock<int, int>(i => Task.Run(() => i), new ExecutionDataflowBlockOptions { BoundedCapacity = 10, MaxMessagesPerTask = 1 }) }; foreach (var generator in generators) { DataflowTestHelpers.TestOfferMessage_ArgumentValidation(generator()); var target = generator(); DataflowTestHelpers.TestOfferMessage_AcceptsDataDirectly(target); DataflowTestHelpers.TestOfferMessage_CompleteAndOffer(target); target = generator(); await DataflowTestHelpers.TestOfferMessage_AcceptsViaLinking(target); DataflowTestHelpers.TestOfferMessage_CompleteAndOffer(target); } } [Fact] public void TestPost() { foreach (bool bounded in DataflowTestHelpers.BooleanValues) foreach (var tb in new[] { new TransformBlock<int, int>(i => i, new ExecutionDataflowBlockOptions { BoundedCapacity = bounded ? 1 : -1 }), new TransformBlock<int, int>(i => Task.Run(() => i), new ExecutionDataflowBlockOptions { BoundedCapacity = bounded ? 1 : -1 })}) { Assert.True(tb.Post(0), "Expected non-completed TransformBlock to accept Post'd message"); tb.Complete(); Assert.False(tb.Post(0), "Expected Complete'd TransformBlock to decline messages"); } } [Fact] public Task TestCompletionTask() { return DataflowTestHelpers.TestCompletionTask(() => new TransformBlock<int, int>(i => i)); } [Fact] public async Task TestLinkToOptions() { const int Messages = 1; foreach (bool append in DataflowTestHelpers.BooleanValues) foreach (var tb in new[] { new TransformBlock<int, int>(i => i), new TransformBlock<int, int>(i => Task.Run(() => i)) }) { var values = new int[Messages]; var targets = new ActionBlock<int>[Messages]; for (int i = 0; i < Messages; i++) { int slot = i; targets[i] = new ActionBlock<int>(item => values[slot] = item); tb.LinkTo(targets[i], new DataflowLinkOptions { MaxMessages = 1, Append = append }); } tb.PostRange(0, Messages); tb.Complete(); await tb.Completion; for (int i = 0; i < Messages; i++) { Assert.Equal( expected: append ? i : Messages - i - 1, actual: values[i]); } } } [Fact] public async Task TestReceives() { for (int test = 0; test < 2; test++) { foreach (var tb in new[] { new TransformBlock<int, int>(i => i * 2), new TransformBlock<int, int>(i => Task.Run(() => i * 2)) }) { tb.PostRange(0, 5); for (int i = 0; i < 5; i++) { Assert.Equal(expected: i * 2, actual: await tb.ReceiveAsync()); } int item; IList<int> items; Assert.False(tb.TryReceive(out item)); Assert.False(tb.TryReceiveAll(out items)); } } } [Fact] public async Task TestCircularLinking() { const int Iters = 200; foreach (bool sync in DataflowTestHelpers.BooleanValues) { var tcs = new TaskCompletionSource<bool>(); Func<int, int> body = i => { if (i >= Iters) tcs.SetResult(true); return i + 1; }; TransformBlock<int, int> tb = sync ? new TransformBlock<int, int>(body) : new TransformBlock<int, int>(i => Task.Run(() => body(i))); using (tb.LinkTo(tb)) { tb.Post(0); await tcs.Task; tb.Complete(); } } } [Fact] public async Task TestProducerConsumer() { foreach (TaskScheduler scheduler in new[] { TaskScheduler.Default, new ConcurrentExclusiveSchedulerPair().ConcurrentScheduler }) foreach (int maxMessagesPerTask in new[] { DataflowBlockOptions.Unbounded, 1, 2 }) foreach (int boundedCapacity in new[] { DataflowBlockOptions.Unbounded, 1, 2 }) foreach (int dop in new[] { 1, 2 }) foreach (bool sync in DataflowTestHelpers.BooleanValues) { const int Messages = 100; var options = new ExecutionDataflowBlockOptions { BoundedCapacity = boundedCapacity, MaxDegreeOfParallelism = dop, MaxMessagesPerTask = maxMessagesPerTask, TaskScheduler = scheduler }; TransformBlock<int, int> tb = sync ? new TransformBlock<int, int>(i => i, options) : new TransformBlock<int, int>(i => Task.Run(() => i), options); await Task.WhenAll( Task.Run(async delegate { // consumer int i = 0; while (await tb.OutputAvailableAsync()) { Assert.Equal(expected: i, actual: await tb.ReceiveAsync()); i++; } }), Task.Run(async delegate { // producer for (int i = 0; i < Messages; i++) { await tb.SendAsync(i); } tb.Complete(); })); } } [Fact] public async Task TestMessagePostponement() { const int Excess = 10; foreach (int boundedCapacity in new[] { 1, 3 }) { var options = new ExecutionDataflowBlockOptions { BoundedCapacity = boundedCapacity }; foreach (var tb in new[] { new TransformBlock<int, int>(i => i, options), new TransformBlock<int, int>(i => Task.Run(() => i), options) }) { var sendAsync = new Task<bool>[boundedCapacity + Excess]; for (int i = 0; i < boundedCapacity + Excess; i++) { sendAsync[i] = tb.SendAsync(i); } tb.Complete(); for (int i = 0; i < boundedCapacity; i++) { Assert.True(sendAsync[i].IsCompleted); Assert.True(sendAsync[i].Result); } for (int i = 0; i < Excess; i++) { Assert.False(await sendAsync[boundedCapacity + i]); } } } } [Fact] public async Task TestReserveReleaseConsume() { var tb = new TransformBlock<int, int>(i => i * 2); tb.Post(1); await DataflowTestHelpers.TestReserveAndRelease(tb); tb = new TransformBlock<int, int>(i => i * 2); tb.Post(2); await DataflowTestHelpers.TestReserveAndConsume(tb); } [Fact] public async Task TestCountZeroAtCompletion() { var cts = new CancellationTokenSource(); var tb = new TransformBlock<int, int>(i => i, new ExecutionDataflowBlockOptions() { CancellationToken = cts.Token }); tb.Post(1); cts.Cancel(); await Assert.ThrowsAnyAsync<OperationCanceledException>(() => tb.Completion); Assert.Equal(expected: 0, actual: tb.InputCount); Assert.Equal(expected: 0, actual: tb.OutputCount); cts = new CancellationTokenSource(); tb = new TransformBlock<int, int>(i => i); tb.Post(1); ((IDataflowBlock)tb).Fault(new InvalidOperationException()); await Assert.ThrowsAnyAsync<InvalidOperationException>(() => tb.Completion); Assert.Equal(expected: 0, actual: tb.InputCount); Assert.Equal(expected: 0, actual: tb.OutputCount); } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))] public void TestInputCount() { foreach (bool sync in DataflowTestHelpers.BooleanValues) { Barrier barrier1 = new Barrier(2), barrier2 = new Barrier(2); Func<int, int> body = item => { barrier1.SignalAndWait(); // will test InputCount here barrier2.SignalAndWait(); return item; }; TransformBlock<int, int> tb = sync ? new TransformBlock<int, int>(body) : new TransformBlock<int, int>(i => Task.Run(() => body(i))); for (int iter = 0; iter < 2; iter++) { tb.PostItems(1, 2); for (int i = 1; i >= 0; i--) { barrier1.SignalAndWait(); Assert.Equal(expected: i, actual: tb.InputCount); barrier2.SignalAndWait(); } } } } [Fact] [OuterLoop] // spins waiting for a condition to be true, though it should happen very quickly public async Task TestCount() { var tb = new TransformBlock<int, int>(i => i); Assert.Equal(expected: 0, actual: tb.InputCount); Assert.Equal(expected: 0, actual: tb.OutputCount); tb.PostRange(1, 11); await Task.Run(() => SpinWait.SpinUntil(() => tb.OutputCount == 10)); for (int i = 10; i > 0; i--) { int item; Assert.True(tb.TryReceive(out item)); Assert.Equal(expected: 11 - i, actual: item); Assert.Equal(expected: i - 1, actual: tb.OutputCount); } } [Fact] public async Task TestChainedSendReceive() { foreach (bool post in DataflowTestHelpers.BooleanValues) foreach (bool sync in DataflowTestHelpers.BooleanValues) { const int Iters = 10; Func<TransformBlock<int, int>> func = sync ? (Func<TransformBlock<int, int>>)(() => new TransformBlock<int, int>(i => i * 2)) : (Func<TransformBlock<int, int>>)(() => new TransformBlock<int, int>(i => Task.Run(() => i * 2))); var network = DataflowTestHelpers.Chain<TransformBlock<int, int>, int>(4, func); for (int i = 0; i < Iters; i++) { if (post) { network.Post(i); } else { await network.SendAsync(i); } Assert.Equal(expected: i * 16, actual: await network.ReceiveAsync()); } } } [Fact] public async Task TestSendAllThenReceive() { foreach (bool post in DataflowTestHelpers.BooleanValues) foreach (bool sync in DataflowTestHelpers.BooleanValues) { const int Iters = 10; Func<TransformBlock<int, int>> func = sync ? (Func<TransformBlock<int, int>>)(() => new TransformBlock<int, int>(i => i * 2)) : (Func<TransformBlock<int, int>>)(() => new TransformBlock<int, int>(i => Task.Run(() => i * 2))); var network = DataflowTestHelpers.Chain<TransformBlock<int, int>, int>(4, func); if (post) { network.PostRange(0, Iters); } else { await Task.WhenAll(from i in Enumerable.Range(0, Iters) select network.SendAsync(i)); } for (int i = 0; i < Iters; i++) { Assert.Equal(expected: i * 16, actual: await network.ReceiveAsync()); } } } [Fact] public async Task TestPrecanceled() { var bb = new TransformBlock<int, int>(i => i, new ExecutionDataflowBlockOptions { CancellationToken = new CancellationToken(canceled: true) }); int ignoredValue; IList<int> ignoredValues; IDisposable link = bb.LinkTo(DataflowBlock.NullTarget<int>()); Assert.NotNull(link); link.Dispose(); Assert.False(bb.Post(42)); var t = bb.SendAsync(42); Assert.True(t.IsCompleted); Assert.False(t.Result); Assert.False(bb.TryReceiveAll(out ignoredValues)); Assert.False(bb.TryReceive(out ignoredValue)); Assert.NotNull(bb.Completion); await Assert.ThrowsAnyAsync<OperationCanceledException>(() => bb.Completion); bb.Complete(); // just make sure it doesn't throw } [Fact] public async Task TestExceptions() { var tb1 = new TransformBlock<int, int>((Func<int, int>)(i => { throw new InvalidCastException(); })); var tb2 = new TransformBlock<int, int>((Func<int, Task<int>>)(i => { throw new InvalidProgramException(); })); var tb3 = new TransformBlock<int, int>((Func<int, Task<int>>)(i => Task.Run((Func<int>)(() => { throw new InvalidTimeZoneException(); })))); for (int i = 0; i < 3; i++) { tb1.Post(i); tb2.Post(i); tb3.Post(i); } await Assert.ThrowsAsync<InvalidCastException>(() => tb1.Completion); await Assert.ThrowsAsync<InvalidProgramException>(() => tb2.Completion); await Assert.ThrowsAsync<InvalidTimeZoneException>(() => tb3.Completion); Assert.All(new[] { tb1, tb2, tb3 }, tb => Assert.True(tb.InputCount == 0 && tb.OutputCount == 0)); } [Fact] public async Task TestFaultingAndCancellation() { foreach (bool fault in DataflowTestHelpers.BooleanValues) { var cts = new CancellationTokenSource(); var tb = new TransformBlock<int, int>(i => i, new ExecutionDataflowBlockOptions { CancellationToken = cts.Token }); tb.PostRange(0, 4); Assert.Equal(expected: 0, actual: await tb.ReceiveAsync()); Assert.Equal(expected: 1, actual: await tb.ReceiveAsync()); if (fault) { Assert.Throws<ArgumentNullException>(() => ((IDataflowBlock)tb).Fault(null)); ((IDataflowBlock)tb).Fault(new InvalidCastException()); await Assert.ThrowsAsync<InvalidCastException>(() => tb.Completion); } else { cts.Cancel(); await Assert.ThrowsAnyAsync<OperationCanceledException>(() => tb.Completion); } Assert.Equal(expected: 0, actual: tb.InputCount); Assert.Equal(expected: 0, actual: tb.OutputCount); } } [Fact] public async Task TestCancellationExceptionsIgnored() { var t = new TransformBlock<int, int>(i => { if ((i % 2) == 0) throw new OperationCanceledException(); return i; }); t.PostRange(0, 2); t.Complete(); for (int i = 0; i < 2; i++) { if ((i % 2) != 0) { Assert.Equal(expected: i, actual: await t.ReceiveAsync()); } } await t.Completion; } [Fact] public async Task TestNullTasksIgnored() { foreach (int dop in new[] { DataflowBlockOptions.Unbounded, 1, 2 }) { var tb = new TransformBlock<int, int>(i => { if ((i % 2) == 0) return null; return Task.Run(() => i); }, new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = dop }); const int Iters = 100; tb.PostRange(0, Iters); tb.Complete(); for (int i = 0; i < Iters; i++) { if ((i % 2) != 0) { Assert.Equal(expected: i, actual: await tb.ReceiveAsync()); } } await tb.Completion; } } // Verifies that internally, TransformBlock does not get confused // between Func<T, Task<object>> and Func<T, object>. [Fact] public async Task TestCtorOverloading() { Func<object, Task<object>> f = x => Task.FromResult<object>(x); for (int test = 0; test < 2; test++) { TransformBlock<object, object> tf = test == 0 ? new TransformBlock<object, object>(f) : new TransformBlock<object, object>((Func<object, object>)f); var tcs = new TaskCompletionSource<bool>(); ActionBlock<object> a = new ActionBlock<object>(x => { Assert.Equal(expected: test == 1, actual: x is Task<object>); tcs.SetResult(true); }); tf.LinkTo(a); tf.Post(new object()); await tcs.Task; } } [Fact] public async Task TestFaultyLinkedTarget() { var tb = new TransformBlock<int, int>(i => i); tb.LinkTo(new DelegatePropagator<int, int> { OfferMessageDelegate = delegate { throw new InvalidCastException(); } }); tb.Post(42); await Assert.ThrowsAsync<InvalidCastException>(() => tb.Completion); } [Theory] [InlineData(DataflowBlockOptions.Unbounded, 1, null)] [InlineData(DataflowBlockOptions.Unbounded, 2, null)] [InlineData(DataflowBlockOptions.Unbounded, DataflowBlockOptions.Unbounded, null)] [InlineData(1, 1, null)] [InlineData(1, 2, null)] [InlineData(1, DataflowBlockOptions.Unbounded, null)] [InlineData(2, 2, true)] [InlineData(2, 1, false)] // no force ordered, but dop == 1, so it doesn't matter public async Task TestOrdering_Sync_OrderedEnabled(int mmpt, int dop, bool? EnsureOrdered) { const int iters = 1000; var options = new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = dop, MaxMessagesPerTask = mmpt }; if (EnsureOrdered == null) { Assert.True(options.EnsureOrdered); } else { options.EnsureOrdered = EnsureOrdered.Value; } var tb = new TransformBlock<int, int>(i => i, options); tb.PostRange(0, iters); for (int i = 0; i < iters; i++) { Assert.Equal(expected: i, actual: await tb.ReceiveAsync()); } tb.Complete(); await tb.Completion; } [Theory] [InlineData(DataflowBlockOptions.Unbounded, 1, null)] [InlineData(DataflowBlockOptions.Unbounded, 2, null)] [InlineData(DataflowBlockOptions.Unbounded, DataflowBlockOptions.Unbounded, null)] [InlineData(1, 1, null)] [InlineData(1, 2, null)] [InlineData(1, DataflowBlockOptions.Unbounded, null)] [InlineData(2, 2, true)] [InlineData(2, 1, false)] // no force ordered, but dop == 1, so it doesn't matter public async Task TestOrdering_Async_OrderedEnabled(int mmpt, int dop, bool? EnsureOrdered) { const int iters = 1000; var options = new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = dop, MaxMessagesPerTask = mmpt }; if (EnsureOrdered == null) { Assert.True(options.EnsureOrdered); } else { options.EnsureOrdered = EnsureOrdered.Value; } var tb = new TransformBlock<int, int>(i => Task.FromResult(i), options); tb.PostRange(0, iters); for (int i = 0; i < iters; i++) { Assert.Equal(expected: i, actual: await tb.ReceiveAsync()); } tb.Complete(); await tb.Completion; } [Fact] public async Task TestOrdering_Async_OrderedDisabled() { // If ordering were enabled, this test would hang. var options = new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = DataflowBlockOptions.Unbounded, EnsureOrdered = false }; var tasks = new TaskCompletionSource<int>[10]; for (int i = 0; i < tasks.Length; i++) { tasks[i] = new TaskCompletionSource<int>(); } var tb = new TransformBlock<int, int>(i => tasks[i].Task, options); tb.PostRange(0, tasks.Length); for (int i = tasks.Length - 1; i >= 0; i--) { tasks[i].SetResult(i); Assert.Equal(expected: i, actual: await tb.ReceiveAsync()); } tb.Complete(); await tb.Completion; } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))] public async Task TestOrdering_Sync_OrderedDisabled() { // If ordering were enabled, this test would hang. var options = new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = 2, EnsureOrdered = false }; var mres = new ManualResetEventSlim(); var tb = new TransformBlock<int, int>(i => { if (i == 0) mres.Wait(); return i; }, options); tb.Post(0); tb.Post(1); Assert.Equal(1, await tb.ReceiveAsync()); mres.Set(); Assert.Equal(0, await tb.ReceiveAsync()); tb.Complete(); await tb.Completion; } } }
39.444109
158
0.502451
[ "MIT" ]
2m0nd/runtime
src/libraries/System.Threading.Tasks.Dataflow/tests/Dataflow/TransformBlockTests.cs
26,112
C#
using System; using System.Collections.Generic; using System.Runtime.Serialization; using Umbraco.Core.Composing; using Umbraco.Core.Logging; namespace Umbraco.Core.Models { /// <summary> /// Represents a Member object /// </summary> [Serializable] [DataContract(IsReference = true)] public class Member : ContentBase, IMember { private IDictionary<string, object> _additionalData; private string _username; private string _email; private string _rawPasswordValue; private object _providerUserKey; /// <summary> /// Constructor for creating an empty Member object /// </summary> /// <param name="contentType">ContentType for the current Content object</param> public Member(IMemberType contentType) : base("", -1, contentType, new PropertyCollection()) { IsApproved = true; //this cannot be null but can be empty _rawPasswordValue = ""; _email = ""; _username = ""; } /// <summary> /// Constructor for creating a Member object /// </summary> /// <param name="name">Name of the content</param> /// <param name="contentType">ContentType for the current Content object</param> public Member(string name, IMemberType contentType) : base(name, -1, contentType, new PropertyCollection()) { if (name == null) throw new ArgumentNullException(nameof(name)); if (string.IsNullOrWhiteSpace(name)) throw new ArgumentException("Value can't be empty or consist only of white-space characters.", nameof(name)); IsApproved = true; //this cannot be null but can be empty _rawPasswordValue = ""; _email = ""; _username = ""; } /// <summary> /// Constructor for creating a Member object /// </summary> /// <param name="name"></param> /// <param name="email"></param> /// <param name="username"></param> /// <param name="contentType"></param> public Member(string name, string email, string username, IMemberType contentType, bool isApproved = true) : base(name, -1, contentType, new PropertyCollection()) { if (name == null) throw new ArgumentNullException(nameof(name)); if (string.IsNullOrWhiteSpace(name)) throw new ArgumentException("Value can't be empty or consist only of white-space characters.", nameof(name)); if (email == null) throw new ArgumentNullException(nameof(email)); if (string.IsNullOrWhiteSpace(email)) throw new ArgumentException("Value can't be empty or consist only of white-space characters.", nameof(email)); if (username == null) throw new ArgumentNullException(nameof(username)); if (string.IsNullOrWhiteSpace(username)) throw new ArgumentException("Value can't be empty or consist only of white-space characters.", nameof(username)); _email = email; _username = username; IsApproved = isApproved; //this cannot be null but can be empty _rawPasswordValue = ""; } /// <summary> /// Constructor for creating a Member object /// </summary> /// <param name="name"></param> /// <param name="email"></param> /// <param name="username"></param> /// <param name="rawPasswordValue"> /// The password value passed in to this parameter should be the encoded/encrypted/hashed format of the member's password /// </param> /// <param name="contentType"></param> public Member(string name, string email, string username, string rawPasswordValue, IMemberType contentType) : base(name, -1, contentType, new PropertyCollection()) { _email = email; _username = username; _rawPasswordValue = rawPasswordValue; IsApproved = true; } /// <summary> /// Constructor for creating a Member object /// </summary> /// <param name="name"></param> /// <param name="email"></param> /// <param name="username"></param> /// <param name="rawPasswordValue"> /// The password value passed in to this parameter should be the encoded/encrypted/hashed format of the member's password /// </param> /// <param name="contentType"></param> /// <param name="isApproved"></param> public Member(string name, string email, string username, string rawPasswordValue, IMemberType contentType, bool isApproved) : base(name, -1, contentType, new PropertyCollection()) { _email = email; _username = username; _rawPasswordValue = rawPasswordValue; IsApproved = isApproved; } /// <summary> /// Gets or sets the Username /// </summary> [DataMember] public string Username { get => _username; set => SetPropertyValueAndDetectChanges(value, ref _username, nameof(Username)); } /// <summary> /// Gets or sets the Email /// </summary> [DataMember] public string Email { get => _email; set => SetPropertyValueAndDetectChanges(value, ref _email, nameof(Email)); } /// <summary> /// Gets or sets the raw password value /// </summary> [IgnoreDataMember] public string RawPasswordValue { get => _rawPasswordValue; set { if (value == null) { //special case, this is used to ensure that the password is not updated when persisting, in this case //we don't want to track changes either _rawPasswordValue = null; } else { SetPropertyValueAndDetectChanges(value, ref _rawPasswordValue, nameof(RawPasswordValue)); } } } /// <summary> /// Gets or sets the Groups that Member is part of /// </summary> [DataMember] public IEnumerable<string> Groups { get; set; } // TODO: When get/setting all of these properties we MUST: // * Check if we are using the umbraco membership provider, if so then we need to use the configured fields - not the explicit fields below // * If any of the fields don't exist, what should we do? Currently it will throw an exception! /// <summary> /// Gets or sets the Password Question /// </summary> /// <remarks> /// Alias: umbracoMemberPasswordRetrievalQuestion /// Part of the standard properties collection. /// </remarks> [DataMember] public string PasswordQuestion { get { var a = WarnIfPropertyTypeNotFoundOnGet(Constants.Conventions.Member.PasswordQuestion, "PasswordQuestion", default(string)); if (a.Success == false) return a.Result; return Properties[Constants.Conventions.Member.PasswordQuestion].GetValue() == null ? string.Empty : Properties[Constants.Conventions.Member.PasswordQuestion].GetValue().ToString(); } set { if (WarnIfPropertyTypeNotFoundOnSet( Constants.Conventions.Member.PasswordQuestion, "PasswordQuestion") == false) return; Properties[Constants.Conventions.Member.PasswordQuestion].SetValue(value); } } /// <summary> /// Gets or sets the raw password answer value /// </summary> /// <remarks> /// For security reasons this value should be encrypted, the encryption process is handled by the membership provider /// Alias: umbracoMemberPasswordRetrievalAnswer /// /// Part of the standard properties collection. /// </remarks> [IgnoreDataMember] public string RawPasswordAnswerValue { get { var a = WarnIfPropertyTypeNotFoundOnGet(Constants.Conventions.Member.PasswordAnswer, "PasswordAnswer", default(string)); if (a.Success == false) return a.Result; return Properties[Constants.Conventions.Member.PasswordAnswer].GetValue() == null ? string.Empty : Properties[Constants.Conventions.Member.PasswordAnswer].GetValue().ToString(); } set { if (WarnIfPropertyTypeNotFoundOnSet( Constants.Conventions.Member.PasswordAnswer, "PasswordAnswer") == false) return; Properties[Constants.Conventions.Member.PasswordAnswer].SetValue(value); } } /// <summary> /// Gets or set the comments for the member /// </summary> /// <remarks> /// Alias: umbracoMemberComments /// Part of the standard properties collection. /// </remarks> [DataMember] public string Comments { get { var a = WarnIfPropertyTypeNotFoundOnGet(Constants.Conventions.Member.Comments, "Comments", default(string)); if (a.Success == false) return a.Result; return Properties[Constants.Conventions.Member.Comments].GetValue() == null ? string.Empty : Properties[Constants.Conventions.Member.Comments].GetValue().ToString(); } set { if (WarnIfPropertyTypeNotFoundOnSet( Constants.Conventions.Member.Comments, "Comments") == false) return; Properties[Constants.Conventions.Member.Comments].SetValue(value); } } /// <summary> /// Gets or sets a boolean indicating whether the Member is approved /// </summary> /// <remarks> /// Alias: umbracoMemberApproved /// Part of the standard properties collection. /// </remarks> [DataMember] public bool IsApproved { get { var a = WarnIfPropertyTypeNotFoundOnGet(Constants.Conventions.Member.IsApproved, "IsApproved", //This is the default value if the prop is not found true); if (a.Success == false) return a.Result; if (Properties[Constants.Conventions.Member.IsApproved].GetValue() == null) return true; var tryConvert = Properties[Constants.Conventions.Member.IsApproved].GetValue().TryConvertTo<bool>(); if (tryConvert.Success) { return tryConvert.Result; } //if the property exists but it cannot be converted, we will assume true return true; } set { if (WarnIfPropertyTypeNotFoundOnSet( Constants.Conventions.Member.IsApproved, "IsApproved") == false) return; Properties[Constants.Conventions.Member.IsApproved].SetValue(value); } } /// <summary> /// Gets or sets a boolean indicating whether the Member is locked out /// </summary> /// <remarks> /// Alias: umbracoMemberLockedOut /// Part of the standard properties collection. /// </remarks> [DataMember] public bool IsLockedOut { get { var a = WarnIfPropertyTypeNotFoundOnGet(Constants.Conventions.Member.IsLockedOut, "IsLockedOut", false); if (a.Success == false) return a.Result; if (Properties[Constants.Conventions.Member.IsLockedOut].GetValue() == null) return false; var tryConvert = Properties[Constants.Conventions.Member.IsLockedOut].GetValue().TryConvertTo<bool>(); if (tryConvert.Success) { return tryConvert.Result; } return false; // TODO: Use TryConvertTo<T> instead } set { if (WarnIfPropertyTypeNotFoundOnSet( Constants.Conventions.Member.IsLockedOut, "IsLockedOut") == false) return; Properties[Constants.Conventions.Member.IsLockedOut].SetValue(value); } } /// <summary> /// Gets or sets the date for last login /// </summary> /// <remarks> /// Alias: umbracoMemberLastLogin /// Part of the standard properties collection. /// </remarks> [DataMember] public DateTime LastLoginDate { get { var a = WarnIfPropertyTypeNotFoundOnGet(Constants.Conventions.Member.LastLoginDate, "LastLoginDate", default(DateTime)); if (a.Success == false) return a.Result; if (Properties[Constants.Conventions.Member.LastLoginDate].GetValue() == null) return default(DateTime); var tryConvert = Properties[Constants.Conventions.Member.LastLoginDate].GetValue().TryConvertTo<DateTime>(); if (tryConvert.Success) { return tryConvert.Result; } return default(DateTime); // TODO: Use TryConvertTo<T> instead } set { if (WarnIfPropertyTypeNotFoundOnSet( Constants.Conventions.Member.LastLoginDate, "LastLoginDate") == false) return; Properties[Constants.Conventions.Member.LastLoginDate].SetValue(value); } } /// <summary> /// Gest or sets the date for last password change /// </summary> /// <remarks> /// Alias: umbracoMemberLastPasswordChangeDate /// Part of the standard properties collection. /// </remarks> [DataMember] public DateTime LastPasswordChangeDate { get { var a = WarnIfPropertyTypeNotFoundOnGet(Constants.Conventions.Member.LastPasswordChangeDate, "LastPasswordChangeDate", default(DateTime)); if (a.Success == false) return a.Result; if (Properties[Constants.Conventions.Member.LastPasswordChangeDate].GetValue() == null) return default(DateTime); var tryConvert = Properties[Constants.Conventions.Member.LastPasswordChangeDate].GetValue().TryConvertTo<DateTime>(); if (tryConvert.Success) { return tryConvert.Result; } return default(DateTime); // TODO: Use TryConvertTo<T> instead } set { if (WarnIfPropertyTypeNotFoundOnSet( Constants.Conventions.Member.LastPasswordChangeDate, "LastPasswordChangeDate") == false) return; Properties[Constants.Conventions.Member.LastPasswordChangeDate].SetValue(value); } } /// <summary> /// Gets or sets the date for when Member was locked out /// </summary> /// <remarks> /// Alias: umbracoMemberLastLockoutDate /// Part of the standard properties collection. /// </remarks> [DataMember] public DateTime LastLockoutDate { get { var a = WarnIfPropertyTypeNotFoundOnGet(Constants.Conventions.Member.LastLockoutDate, "LastLockoutDate", default(DateTime)); if (a.Success == false) return a.Result; if (Properties[Constants.Conventions.Member.LastLockoutDate].GetValue() == null) return default(DateTime); var tryConvert = Properties[Constants.Conventions.Member.LastLockoutDate].GetValue().TryConvertTo<DateTime>(); if (tryConvert.Success) { return tryConvert.Result; } return default(DateTime); // TODO: Use TryConvertTo<T> instead } set { if (WarnIfPropertyTypeNotFoundOnSet( Constants.Conventions.Member.LastLockoutDate, "LastLockoutDate") == false) return; Properties[Constants.Conventions.Member.LastLockoutDate].SetValue(value); } } /// <summary> /// Gets or sets the number of failed password attempts. /// This is the number of times the password was entered incorrectly upon login. /// </summary> /// <remarks> /// Alias: umbracoMemberFailedPasswordAttempts /// Part of the standard properties collection. /// </remarks> [DataMember] public int FailedPasswordAttempts { get { var a = WarnIfPropertyTypeNotFoundOnGet(Constants.Conventions.Member.FailedPasswordAttempts, "FailedPasswordAttempts", 0); if (a.Success == false) return a.Result; if (Properties[Constants.Conventions.Member.FailedPasswordAttempts].GetValue() == null) return default(int); var tryConvert = Properties[Constants.Conventions.Member.FailedPasswordAttempts].GetValue().TryConvertTo<int>(); if (tryConvert.Success) { return tryConvert.Result; } return default(int); // TODO: Use TryConvertTo<T> instead } set { if (WarnIfPropertyTypeNotFoundOnSet( Constants.Conventions.Member.FailedPasswordAttempts, "FailedPasswordAttempts") == false) return; Properties[Constants.Conventions.Member.FailedPasswordAttempts].SetValue(value); } } /// <summary> /// String alias of the default ContentType /// </summary> [DataMember] public virtual string ContentTypeAlias => ContentType.Alias; /// <summary> /// User key from the Provider. /// </summary> /// <remarks> /// When using standard umbraco provider this key will /// correspond to the guid UniqueId/Key. /// Otherwise it will the one available from the asp.net /// membership provider. /// </remarks> [DataMember] public virtual object ProviderUserKey { get => _providerUserKey; set => SetPropertyValueAndDetectChanges(value, ref _providerUserKey, nameof(ProviderUserKey)); } /* Internal experiment - only used for mapping queries. * Adding these to have first level properties instead of the Properties collection. */ [IgnoreDataMember] internal string LongStringPropertyValue { get; set; } [IgnoreDataMember] internal string ShortStringPropertyValue { get; set; } [IgnoreDataMember] internal int IntegerPropertyValue { get; set; } [IgnoreDataMember] internal bool BoolPropertyValue { get; set; } [IgnoreDataMember] internal DateTime DateTimePropertyValue { get; set; } [IgnoreDataMember] internal string PropertyTypeAlias { get; set; } private Attempt<T> WarnIfPropertyTypeNotFoundOnGet<T>(string propertyAlias, string propertyName, T defaultVal) { void DoLog(string logPropertyAlias, string logPropertyName) { Current.Logger.Warn<Member>("Trying to access the '{PropertyName}' property on '{MemberType}' " + "but the {PropertyAlias} property does not exist on the member type so a default value is returned. " + "Ensure that you have a property type with alias: {PropertyAlias} configured on your member type in order to use the '{PropertyName}' property on the model correctly.", logPropertyName, typeof(Member), logPropertyAlias); } // if the property doesn't exist, if (Properties.Contains(propertyAlias) == false) { // put a warn in the log if this entity has been persisted // then return a failure if (HasIdentity) DoLog(propertyAlias, propertyName); return Attempt<T>.Fail(defaultVal); } return Attempt<T>.Succeed(); } private bool WarnIfPropertyTypeNotFoundOnSet(string propertyAlias, string propertyName) { void DoLog(string logPropertyAlias, string logPropertyName) { Current.Logger.Warn<Member>("An attempt was made to set a value on the property '{PropertyName}' on type '{MemberType}' but the " + "property type {PropertyAlias} does not exist on the member type, ensure that this property type exists so that setting this property works correctly.", logPropertyName, typeof(Member), logPropertyAlias); } // if the property doesn't exist, if (Properties.Contains(propertyAlias) == false) { // put a warn in the log if this entity has been persisted // then return a failure if (HasIdentity) DoLog(propertyAlias, propertyName); return false; } return true; } /// <inheritdoc /> [DataMember] [DoNotClone] public IDictionary<string, object> AdditionalData => _additionalData ?? (_additionalData = new Dictionary<string, object>()); /// <inheritdoc /> [IgnoreDataMember] public bool HasAdditionalData => _additionalData != null; } }
40.674419
213
0.559573
[ "MIT" ]
Adamanderss/Umbraco-CMS
src/Umbraco.Core/Models/Member.cs
22,739
C#
// Copyright (C) 2003-2010 Xtensive LLC. // All rights reserved. // For conditions of distribution and use, see license. // Created by: Alex Yakunin // Created: 2009.03.16 using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Reflection; using System.Runtime.Serialization; using Xtensive.Collections; using Xtensive.Core; using Xtensive.Modelling.Actions; using Xtensive.Modelling.Attributes; using Xtensive.Reflection; using Xtensive.Modelling.Validation; using System.Linq; namespace Xtensive.Modelling { /// <summary> /// An abstract base class for model node. /// </summary> [Serializable] [DebuggerDisplay("{Name}")] public abstract class Node : LockableBase, INode, IDeserializationCallback { /// <summary> /// Path delimiter character. /// </summary> public static readonly char PathDelimiter = '/'; /// <summary> /// Path escape character. /// </summary> public static readonly char PathEscape = '\\'; [NonSerialized] private static ThreadSafeDictionary<Type, PropertyAccessorDictionary> cachedPropertyAccessors = ThreadSafeDictionary<Type, PropertyAccessorDictionary>.Create(new object()); [NonSerialized] private Node model; [NonSerialized] private string cachedPath; [NonSerialized] private Nesting nesting; [NonSerialized] private PropertyAccessorDictionary propertyAccessors; internal Node parent; private string name; private string escapedName; private NodeState state; private int index; #region Properties /// <inheritdoc/> [SystemProperty] public Node Parent { [DebuggerStepThrough] get { return parent; } [DebuggerStepThrough] set { ArgumentValidator.EnsureArgumentNotNull(value, "value"); if (value==Parent) return; NodeCollection collection = null; if (Nesting.IsNestedToCollection) collection = (NodeCollection) Nesting.PropertyGetter(value); Move(value, Name, collection==null ? 0 : collection.Count); } } /// <inheritdoc/> public Node Model { [DebuggerStepThrough] get { return model; } } /// <inheritdoc/> [SystemProperty] public string Name { [DebuggerStepThrough] get { return name; } [DebuggerStepThrough] set { Move(Parent, value, Index); } } /// <inheritdoc/> public string EscapedName { [DebuggerStepThrough] get { if (escapedName==null) escapedName = new[] {Name}.RevertibleJoin(PathEscape, PathDelimiter); return escapedName; } } /// <inheritdoc/> public NodeState State { get { return state; } } /// <inheritdoc/> [SystemProperty] public int Index { [DebuggerStepThrough] get { return index; } [DebuggerStepThrough] set { Move(Parent, Name, value); } } /// <inheritdoc/> public Nesting Nesting { [DebuggerStepThrough] get { return nesting; } } /// <inheritdoc/> public PropertyAccessorDictionary PropertyAccessors { [DebuggerStepThrough] get { return propertyAccessors; } } /// <inheritdoc/> public object GetProperty(string propertyName) { return PropertyAccessors[propertyName].Getter.Invoke(this); } /// <inheritdoc/> public void SetProperty(string propertyName, object value) { PropertyAccessors[propertyName].Setter.Invoke(this, value); } /// <inheritdoc/> public IPathNode GetNestedProperty(string propertyName) { var getter = PropertyAccessors[propertyName].Getter; if (getter==null) return null; var value = getter.Invoke(this) as IPathNode; if (value==null) return null; if (value is NodeCollection) return value; var node = value as Node; if (node!=null && node.Parent==this) return value; return null; } /// <inheritdoc/> public IEnumerable<Pair<string, IPathNode>> GetPathNodes(bool nestedOnly) { foreach (var pair in propertyAccessors) { string propertyName = pair.Key; var accessor = pair.Value; if (accessor.PropertyInfo.GetAttribute<SystemPropertyAttribute>( AttributeSearchOptions.InheritNone)!=null) continue; IPathNode propertyValue; if (nestedOnly) propertyValue = GetNestedProperty(propertyName); else propertyValue = accessor.HasGetter ? GetProperty(propertyName) as IPathNode : null; if (propertyValue!=null) yield return new Pair<string, IPathNode>(propertyName, propertyValue); } } /// <inheritdoc/> public string Path { [DebuggerStepThrough] get { if (cachedPath!=null) return cachedPath; if (Parent==null) return string.Empty; string parentPath = Parent.Path; if (parentPath.Length!=0) parentPath += PathDelimiter; return string.Concat( parentPath, Nesting.EscapedPropertyName, Nesting.IsNestedToCollection ? PathDelimiter.ToString() : string.Empty, Nesting.IsNestedToCollection ? EscapedName : string.Empty); } } #endregion /// <inheritdoc/> /// <exception cref="InvalidOperationException">Invalid node state.</exception> public void Move(Node newParent, string newName, int newIndex) { if (State==NodeState.Removed) throw new InvalidOperationException(Strings.ExInvalidNodeState); this.EnsureNotLocked(); if (newParent==Parent && newName==Name && newIndex==Index) return; if (this is IUnnamedNode) newName = newIndex.ToString(); ValidateMove(newParent, newName, newIndex); if (State==NodeState.Initializing) { parent = newParent; name = newName; escapedName = null; index = newIndex; UpdateModel(); OnPropertyChanged("Parent"); OnPropertyChanged("Model"); OnPropertyChanged("Name"); OnPropertyChanged("EscapedName"); OnPropertyChanged("Index"); using (var scope = LogAction()) { var a = new CreateNodeAction() { Path = newParent==null ? string.Empty : newParent.Path, Type = GetType(), Name = newName, }; scope.Action = a; PerformCreate(); scope.Commit(); } } else { using (var scope = LogAction()) { var a = new MoveNodeAction() { Path = Path, Parent = newParent==parent ? null : newParent.Path, Name = newName==name ? null : newName, Index = newIndex==index ? (int?)null : newIndex }; scope.Action = a; PerformMove(newParent, newName, newIndex); a.NewPath = Path; scope.Commit(); } } OnPropertyChanged("State"); } /// <inheritdoc/> /// <exception cref="InvalidOperationException">Invalid node state.</exception> public void Remove() { EnsureIsEditable(); ValidateRemove(); using (var scope = LogAction(new RemoveNodeAction() { Path = Path })) { PerformRemove(this); scope.Commit(); } OnPropertyChanged("State"); } /// <inheritdoc/> public IPathNode Resolve(string path) { if (path.IsNullOrEmpty()) return this; var parts = path.RevertibleSplitFirstAndTail(Node.PathEscape, Node.PathDelimiter); var accessor = PropertyAccessors.TryGetValue(parts.First, out var v) ? v : default; if (accessor==null) return null; var next = (IPathNode) accessor.Getter.Invoke(this); if (parts.Second==null) return next; return next.Resolve(parts.Second); } /// <inheritdoc/> public void Validate() { using (ValidationScope.Open()) { using (var ea = new ExceptionAggregator()) { if (ValidationContext.Current.IsValidated(this)) { ea.Complete(); return; } ValidateState(); foreach (var pair in PropertyAccessors) { if (!pair.Value.HasGetter) continue; var nested = GetNestedProperty(pair.Key); if (nested!=null) { ea.Execute(x => x.Validate(), nested); continue; } var value = GetProperty(pair.Key); if (value!=null) { var pathNode = value as Node; if (pathNode!=null) ea.Execute(x => x.ValidateState(), pathNode); } } ea.Complete(); } } } /// <inheritdoc/> /// <exception cref="InvalidOperationException">Required constructor isn't found.</exception> public virtual Node Clone(Node newParent, string newName) { using (CloningScope.Open()) { var isModel = this is IModel; if (!isModel) ArgumentValidator.EnsureArgumentNotNull(newParent, "newParent"); ArgumentValidator.EnsureArgumentNotNull(newName, "newName"); // Cloning the instance var model = isModel ? null : (IModel) newParent.Model; Node node; if (isModel) node = TryConstructor(null, newName); else { node = TryConstructor(model, newParent, newName); // Regular node if (node==null) node = TryConstructor(model, newParent); // Unnamed node } if (node==null) throw new InvalidOperationException(string.Format( Strings.ExCannotFindConstructorToExecuteX, this)); // Cloning properties foreach (var pair in PropertyAccessors) { var accessor = pair.Value; if (!accessor.HasGetter) continue; CopyPropertyValue(node, accessor); } return node; } } /// <summary> /// Copies the property value. /// </summary> /// <param name="target">The target node.</param> /// <param name="accessor">The accessor of the property to copy value of.</param> protected virtual void CopyPropertyValue(Node target, PropertyAccessor accessor) { var propertyName = accessor.PropertyInfo.Name; var nested = GetNestedProperty(propertyName); if (nested!=null) { var collection = nested as NodeCollection; if (collection!=null) foreach (Node newNode in collection) newNode.Clone(target, newNode.Name); else { var newNode = (Node) nested; newNode.Clone(target, newNode.Name); } } else if (accessor.HasSetter) { var value = GetProperty(propertyName); var pathNode = value as IPathNode; if (pathNode!=null) { CloningContext.Current.AddFixup(() => accessor.Setter(target, PathNodeReference.Resolve((IModel) target.Model, new PathNodeReference(pathNode.Path)))); return; } var cloneable = value as ICloneable; if (cloneable!=null) value = cloneable.Clone(); accessor.Setter(target, value); } } #region ValidateXxx methods /// <summary> /// Validates the <see cref="Move"/> method arguments. /// </summary> /// <param name="newParent">The new parent.</param> /// <param name="newName">The new name.</param> /// <param name="newIndex">The new index.</param> /// <exception cref="ArgumentException">Item already exists.</exception> /// <exception cref="ArgumentOutOfRangeException"><paramref name="newIndex"/> is out of range, /// or <paramref name="newParent"/> belongs to a different <see cref="Model"/>.</exception> /// <exception cref="InvalidOperationException">newName!=newIndex for <see cref="IUnnamedNode"/>.</exception> protected virtual void ValidateMove(Node newParent, string newName, int newIndex) { ArgumentValidator.EnsureArgumentNotNullOrEmpty(newName, "newName"); if (this is IModel) { ArgumentValidator.EnsureArgumentIsInRange(newIndex, 0, 0, "newIndex"); return; } // Validating parent model ArgumentValidator.EnsureArgumentNotNull(newParent, "newParent"); ArgumentValidator.EnsureArgumentIs<Node>(newParent, "newParent"); var model = Model; if (model!=null) { var newModel = newParent.Model; if (model!=newModel) throw new ArgumentOutOfRangeException("newParent.Model"); } if (this is IUnnamedNode) { // Validation for unnamed nodes if (newName!=newIndex.ToString()) throw Exceptions.InternalError("newName!=newIndex for IUnnamedNode!", CoreLog.Instance); } else if (!Nesting.IsNestedToCollection) // Validation parent property nesting ArgumentValidator.EnsureArgumentIsInRange(newIndex, 0, 0, "newIndex"); else { // Validation parent collection nesting var collection = (NodeCollection) Nesting.PropertyGetter(newParent); ArgumentValidator.EnsureArgumentIsInRange(newIndex, 0, collection.Count - (newParent==Parent ? 1 : 0), "newIndex"); Node node; if (!collection.TryGetValue(newName, out node)) return; if (node!=this) throw new ArgumentException(String.Format( Strings.ExItemWithNameXAlreadyExists, newName), newName); } } /// <summary> /// Validates the <see cref="Remove"/> method call. /// </summary> /// <exception cref="InvalidOperationException">Model object cannot be removed.</exception> protected virtual void ValidateRemove() { if (this is IModel) throw new InvalidOperationException(Strings.ExModelObjectCannotBeRemoved); } /// <summary> /// Validates the state (i.e. checks everything except nested properties). /// </summary> protected virtual void ValidateState() { EnsureIsLive(); } #endregion #region PerformXxx methods /// <summary> /// Actually performs construction operation. /// </summary> /// <exception cref="InvalidOperationException">Target object already exists.</exception> protected virtual void PerformCreate() { if (Parent!=null) { if (!Nesting.IsNestedToCollection) { if (Nesting.PropertyValue!=null) throw new InvalidOperationException(string.Format( Strings.ExTargetObjectExistsX, Nesting.PropertyValue)); Nesting.PropertyValue = this; } else { var collection = (NodeCollection) Nesting.PropertyValue; collection.Add(this); } } state = NodeState.Live; } /// <summary> /// Actually performs <see cref="Move"/> operation. /// </summary> /// <param name="newParent">The new parent.</param> /// <param name="newName">The new name.</param> /// <param name="newIndex">The new index.</param> /// <exception cref="InvalidOperationException">Target object already exists.</exception> protected virtual void PerformMove(Node newParent, string newName, int newIndex) { bool nameIsChanging = (this is IUnnamedNode) || Name!=newName; var propertyGetter = Nesting.PropertyGetter; if (newParent!=parent) { // Parent is changed if (!Nesting.IsNestedToCollection) { Nesting.PropertySetter(parent, null); var existingNode = propertyGetter(newParent); if (existingNode!=null) throw new InvalidOperationException(string.Format( Strings.ExTargetObjectExistsX, existingNode)); Nesting.PropertySetter(newParent, this); } else { var oldCollection = (NodeCollection) propertyGetter(parent); var newCollection = (NodeCollection) propertyGetter(newParent); for (int i = index + 1; i < oldCollection.Count; i++) oldCollection[i].EnsureIsEditable(); for (int i = newIndex; i < newCollection.Count; i++) newCollection[i].EnsureIsEditable(); if (nameIsChanging) oldCollection.RemoveName(this); for (int i = index + 1; i < oldCollection.Count; i++) oldCollection[i].PerformShift(-1); for (int i = newCollection.Count-1; i>=newIndex; i--) newCollection[i].PerformShift(1); oldCollection.Remove(this); index = newIndex; if (nameIsChanging) { name = newName; escapedName = null; } newCollection.Add(this); } } else if (propertyGetter==null) { if (!(this is IModel)) throw Exceptions.InternalError(string.Format( Strings.ExInvalidNestingOfNodeX, this), CoreLog.Instance); } else if (Nesting.IsNestedToCollection) { // Parent isn't changed var collection = (NodeCollection) propertyGetter(newParent); int minIndex, maxIndex, shift; if (newIndex < index) { minIndex = newIndex; maxIndex = index - 1; shift = 1; } else { minIndex = index + 1; maxIndex = newIndex; shift = -1; } if (nameIsChanging) collection.RemoveName(this); for (int i = minIndex; i <= maxIndex; i++) collection[i].EnsureIsEditable(); if (shift<0) for (int i = minIndex; i <= maxIndex; i++) collection[i].PerformShift(shift); else for (int i = maxIndex; i >= minIndex; i--) collection[i].PerformShift(shift); collection.Move(this, newIndex); name = newName; escapedName = null; index = newIndex; if (nameIsChanging) collection.AddName(this); // collection.CheckIntegrity(); } parent = newParent; name = newName; escapedName = null; index = newIndex; UpdateModel(); } /// <summary> /// Performs "shift" operation /// (induced by <see cref="Move"/> operation of another node). /// </summary> /// <param name="offset">Shift offset.</param> protected virtual void PerformShift(int offset) { bool bUnnamed = this is IUnnamedNode; string newName = name; var newIndex = index + offset; if (bUnnamed) { newName = newIndex.ToString(); if (Nesting.IsNestedToCollection) { var collection = ((NodeCollection) Nesting.PropertyValue); if (collection!=null) { collection.RemoveName(this); name = newName; escapedName = null; index = newIndex; collection.AddName(this); } } } else { index = newIndex; } } /// <summary> /// Actually performs <see cref="Remove"/> operation. /// </summary> protected virtual void PerformRemove(Node source) { state = NodeState.Removed; if (source==this) { // Updating parents if (!Nesting.IsNestedToCollection) Nesting.PropertyValue = null; else { var collection = (NodeCollection) Nesting.PropertyValue; collection.Remove(this); for (int i = index; i < collection.Count; i++) collection[i].EnsureIsEditable(); for (int i = index; i < collection.Count; i++) collection[i].PerformShift(-1); } } // Notifying children foreach (var pair in GetPathNodes(true)) { var pathNode = pair.Second; var nodeCollection = pathNode as NodeCollection; if (nodeCollection!=null) foreach (Node nestedNode in nodeCollection) nestedNode.PerformRemove(source); var node = pathNode as Node; if (node!=null) node.PerformRemove(source); } if (source==this) Lock(true); } #endregion #region LogXxx methods /// <summary> /// Logs the property change. /// </summary> /// <param name="propertyName">Name of the property.</param> /// <param name="propertyValue">The property value.</param> /// <returns></returns> protected ActionScope LogPropertyChange(string propertyName, object propertyValue) { var scope = LogAction(); var action = new PropertyChangeAction {Path = Path}; action.Properties.Add(propertyName, PathNodeReference.Get(propertyValue)); scope.Action = action; return scope; } /// <summary> /// Begins registration of a new action. /// </summary> /// <param name="action">The action to register.</param> /// <returns> /// <see cref="ActionScope"/> object allowing to describe it. /// </returns> protected ActionScope LogAction(NodeAction action) { var scope = LogAction(); scope.Action = action; return scope; } /// <summary> /// Begins registration of a new action. /// </summary> /// <returns> /// <see cref="ActionScope"/> object allowing to describe it. /// </returns> protected ActionScope LogAction() { var model = (IModel) Model; if (model==null) return new ActionScope(); var actions = model.Actions; if (actions==null) return new ActionScope(); return actions.LogAction(); } #endregion #region EnsureXxxx methods /// <summary> /// Ensures the node <see cref="State"/> is <see cref="NodeState.Live"/>. /// </summary> /// <exception cref="InvalidOperationException"><see cref="State"/> is invalid.</exception> protected void EnsureIsLive() { if (State!=NodeState.Live) throw new InvalidOperationException(Strings.ExInvalidNodeState); } /// <summary> /// Ensures the node <see cref="State"/> is <see cref="NodeState.Live"/> and /// node isn't <see cref="Lock"/>ed. /// </summary> /// <exception cref="InvalidOperationException"><see cref="State"/> is invalid.</exception> protected void EnsureIsEditable() { if (State!=NodeState.Live) throw new InvalidOperationException(Strings.ExInvalidNodeState); this.EnsureNotLocked(); } #endregion #region INotifyPropertyChanged methods /// <inheritdoc/> [field : NonSerialized] public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// Raises <see cref="PropertyChanged"/> event. /// </summary> /// <param name="name">Name of the property.</param> protected virtual void OnPropertyChanged(string name) { if (PropertyChanged!=null) PropertyChanged.Invoke(this, new PropertyChangedEventArgs(name)); } /// <summary> /// Does all the dirty job to change the property of this node. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="name">Name of the property.</param> /// <param name="value">New value of the property.</param> /// <param name="setter">Property setter delegate.</param> /// <exception cref="ArgumentOutOfRangeException"><paramref name="value"/> belongs to a different <see cref="Model"/>.</exception> protected void ChangeProperty<T>(string name, T value, Action<Node,T> setter) { EnsureIsEditable(); var pathNode = value as IPathNode; var model = Model; if (pathNode!=null && model!=null && pathNode.Model!=model) throw new ArgumentOutOfRangeException(Strings.ExPropertyValueMustBelongToTheSameModel, "value"); using (var scope = !PropertyAccessors.ContainsKey(name) ? null : LogPropertyChange(name, value)) { setter.Invoke(this, value); OnPropertyChanged(name); if (scope!=null) scope.Commit(); } } #endregion #region ILockable methods /// <inheritdoc/> public override void Lock(bool recursive) { base.Lock(recursive); foreach (var pair in PropertyAccessors) { var nested = GetNestedProperty(pair.Key); if (nested!=null) nested.Lock(); } cachedPath = Path; } #endregion #region Private \ internal methods private void UpdateModel() { var p = Parent; if (p==null) model = (Node) (this as IModel); else model = p.Model; } private static PropertyAccessorDictionary GetPropertyAccessors(Type type) { ArgumentValidator.EnsureArgumentNotNull(type, "type"); return cachedPropertyAccessors.GetValue(type, (_type) => { var d = new Dictionary<string, PropertyAccessor>(); if (_type!=typeof(object)) foreach (var pair in GetPropertyAccessors(_type.BaseType)) d.Add(pair.Key, pair.Value); foreach (var p in _type.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly)) { if (p.GetAttribute<PropertyAttribute>(AttributeSearchOptions.InheritNone)!=null) d.Add(p.Name, new PropertyAccessor(p)); } return new PropertyAccessorDictionary(d, false); }); } private Node TryConstructor(IModel model, params object[] args) { var argTypes = args.Select(a => a.GetType()).ToArray(); var ci = GetType().GetConstructor(argTypes); if (ci==null) return null; return (Node) ci.Invoke(args); } #endregion #region To override /// <summary> /// Creates <see cref="Nesting"/> object describing how this node is nested. /// </summary> /// <returns>New <see cref="Nesting"/> object.</returns> protected abstract Nesting CreateNesting(); /// <summary> /// Initializes this instance. /// </summary> /// <exception cref="InvalidOperationException"><see cref="CreateNesting"/> has returned <see langword="null" />.</exception> protected virtual void Initialize() { nesting = CreateNesting(); if (nesting==null) throw new InvalidOperationException(Strings.ExNoNesting); propertyAccessors = GetPropertyAccessors(GetType()); } #endregion #region Dump, ToString /// <inheritdoc/> public virtual void Dump() { string prefix = string.Empty; if (Nesting.IsNestedToCollection && !(Nesting.PropertyValue is IUnorderedNodeCollection)) prefix = string.Format("{0}: ", Index); CoreLog.Info("{0}{1} \"{2}\"", prefix, GetType().GetShortName(), this); using (Orm.Logging.IndentManager.IncreaseIndent()) { // Validation errors Exception error = null; try { ValidateState(); } catch (Exception e) { error = e; } // Basic properties if (error!=null) CoreLog.Info("+Error = {0}", error); if (State!=NodeState.Live) CoreLog.Info("+State = {0}", State); // Everything else foreach (var pair in propertyAccessors) { string propertyName = pair.Key; var accessor = pair.Value; if (accessor.PropertyInfo.GetAttribute<SystemPropertyAttribute>( AttributeSearchOptions.InheritNone)!=null) continue; var propertyValue = accessor.HasGetter ? GetProperty(propertyName) : null; if (Equals(propertyValue, accessor.Default)) continue; var propertyType = (propertyValue==null ? accessor.PropertyInfo.PropertyType : propertyValue.GetType()) .GetShortName(); var nested = GetNestedProperty(propertyName); if (nested!=null) { var collection = nested as NodeCollection; if (collection!=null && collection.Count!=0) CoreLog.Info("+{0} ({1}):", propertyName, collection.Count); else CoreLog.Info("+{0}:", propertyName); using (Orm.Logging.IndentManager.IncreaseIndent()) nested.Dump(); } else CoreLog.Info("+{0} = {1} ({2})", propertyName, propertyValue, propertyType); } } } /// <inheritdoc/> public override string ToString() { var m = Model; string fullName = Path; if (m!=null) fullName = string.Concat(m.EscapedName, PathDelimiter, fullName); if (!Nesting.IsNestedToCollection && !(this is IModel)) fullName = string.Format(Strings.NodeInfoFormat, fullName, Name); return fullName; } #endregion // Constructors /// <summary> /// Initializes a new instance of the <see cref="Node"/> class. /// </summary> /// <param name="parent"><see cref="Parent"/> property value.</param> /// <param name="name">Initial <see cref="Name"/> property value.</param> protected Node(Node parent, string name) { if (!(this is IModel)) ArgumentValidator.EnsureArgumentNotNull(parent, "parent"); if (!(this is IUnnamedNode)) ArgumentValidator.EnsureArgumentNotNullOrEmpty(name, "name"); Initialize(); if (!Nesting.IsNestedToCollection) Move(parent, name, 0); else Move(parent, name, ((NodeCollection) Nesting.PropertyGetter(parent)).Count); } // Deserialization /// <inheritdoc/> void IDeserializationCallback.OnDeserialization(object sender) { if (nesting!=null) return; // Protects from multiple calls Initialize(); var p = Parent as IDeserializationCallback; if (p!=null) p.OnDeserialization(sender); UpdateModel(); if (IsLocked) cachedPath = Path; } } }
33.090323
135
0.586534
[ "MIT" ]
SergeiPavlov/dataobjects-net
DataObjects/Modelling/Node.cs
30,774
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. ==================================================================== */ namespace NPOI.HWPF.Model.Types { using NPOI.HWPF.UserModel; using NPOI.Util; using System; using System.Text; /** * Paragraph Properties. * NOTE: This source is automatically generated please do not modify this file. Either subclass or * remove the record in src/records/defInitions. * @author S. Ryan Ackley */ public abstract class PAPAbstractType:BaseObject { protected int field_1_istd; protected bool field_2_fSideBySide; protected bool field_3_fKeep; protected bool field_4_fKeepFollow; protected bool field_5_fPageBreakBefore; protected byte field_6_brcl; /**/ public static byte BRCL_SINGLE = 0; /**/ public static byte BRCL_THICK = 1; /**/ public static byte BRCL_DOUBLE = 2; /**/ public static byte BRCL_SHADOW = 3; protected byte field_7_brcp; /**/ public static byte BRCP_NONE = 0; /**/ public static byte BRCP_BORDER_ABOVE = 1; /**/ public static byte BRCP_BORDER_BELOW = 2; /**/ public static byte BRCP_BOX_AROUND = 15; /**/ public static byte BRCP_BAR_TO_LEFT_OF_PARAGRAPH = 16; protected byte field_8_ilvl; protected int field_9_ilfo; protected bool field_10_fNoLnn; protected LineSpacingDescriptor field_11_lspd; protected int field_12_dyaBefore; protected int field_13_dyaAfter; protected bool field_14_fInTable; protected bool field_15_finTableW97; protected bool field_16_fTtp; protected int field_17_dxaAbs; protected int field_18_dyaAbs; protected int field_19_dxaWidth; protected bool field_20_fBrLnAbove; protected bool field_21_fBrLnBelow; protected byte field_22_pcVert; protected byte field_23_pcHorz; protected byte field_24_wr; protected bool field_25_fNoAutoHyph; protected int field_26_dyaHeight; protected bool field_27_fMinHeight; /**/ public static bool FMINHEIGHT_EXACT = false; /**/ public static bool FMINHEIGHT_AT_LEAST = true; protected DropCapSpecifier field_28_dcs; protected int field_29_dyaFromText; protected int field_30_dxaFromText; protected bool field_31_fLocked; protected bool field_32_fWidowControl; protected bool field_33_fKinsoku; protected bool field_34_fWordWrap; protected bool field_35_fOverflowPunct; protected bool field_36_fTopLinePunct; protected bool field_37_fAutoSpaceDE; protected bool field_38_fAutoSpaceDN; protected int field_39_wAlignFont; /**/ public static byte WALIGNFONT_HANGING = 0; /**/ public static byte WALIGNFONT_CENTERED = 1; /**/ public static byte WALIGNFONT_ROMAN = 2; /**/ public static byte WALIGNFONT_VARIABLE = 3; /**/ public static byte WALIGNFONT_AUTO = 4; protected short field_40_fontAlign; private static BitField fVertical = new BitField(0x0001); private static BitField fBackward = new BitField(0x0002); private static BitField fRotateFont = new BitField(0x0004); protected byte field_41_lvl; protected bool field_42_fBiDi; protected bool field_43_fNumRMIns; protected bool field_44_fCrLf; protected bool field_45_fUsePgsuSettings; protected bool field_46_fAdjustRight; protected int field_47_itap; protected bool field_48_fInnerTableCell; protected bool field_49_fOpenTch; protected bool field_50_fTtpEmbedded; protected short field_51_dxcRight; protected short field_52_dxcLeft; protected short field_53_dxcLeft1; protected bool field_54_fDyaBeforeAuto; protected bool field_55_fDyaAfterAuto; protected int field_56_dxaRight; protected int field_57_dxaLeft; protected int field_58_dxaLeft1; protected byte field_59_jc; protected bool field_60_fNoAllowOverlap; protected BorderCode field_61_brcTop; protected BorderCode field_62_brcLeft; protected BorderCode field_63_brcBottom; protected BorderCode field_64_brcRight; protected BorderCode field_65_brcBetween; protected BorderCode field_66_brcBar; protected ShadingDescriptor field_67_shd; protected byte[] field_68_anld; protected byte[] field_69_phe; protected bool field_70_fPropRMark; protected int field_71_ibstPropRMark; protected DateAndTime field_72_dttmPropRMark; protected int field_73_itbdMac; protected int[] field_74_rgdxaTab; protected byte[] field_75_rgtbd; protected byte[] field_76_numrm; protected byte[] field_77_ptap; protected PAPAbstractType() { this.field_11_lspd = new LineSpacingDescriptor(); this.field_11_lspd = new LineSpacingDescriptor(); this.field_28_dcs = new DropCapSpecifier(); this.field_32_fWidowControl = true; this.field_41_lvl = 9; this.field_61_brcTop = new BorderCode(); this.field_62_brcLeft = new BorderCode(); this.field_63_brcBottom = new BorderCode(); this.field_64_brcRight = new BorderCode(); this.field_65_brcBetween = new BorderCode(); this.field_66_brcBar = new BorderCode(); this.field_67_shd = new ShadingDescriptor(); this.field_68_anld = new byte[0]; this.field_69_phe = new byte[0]; this.field_72_dttmPropRMark = new DateAndTime(); this.field_74_rgdxaTab = new int[0]; this.field_75_rgtbd = new byte[0]; this.field_76_numrm = new byte[0]; this.field_77_ptap = new byte[0]; } public override String ToString() { StringBuilder builder = new StringBuilder(); builder.Append("[PAP]\n"); builder.Append(" .Istd = "); builder.Append(" (").Append(GetIstd()).Append(" )\n"); builder.Append(" .fSideBySide = "); builder.Append(" (").Append(GetFSideBySide()).Append(" )\n"); builder.Append(" .fKeep = "); builder.Append(" (").Append(GetFKeep()).Append(" )\n"); builder.Append(" .fKeepFollow = "); builder.Append(" (").Append(GetFKeepFollow()).Append(" )\n"); builder.Append(" .fPageBreakBefore = "); builder.Append(" (").Append(GetFPageBreakBefore()).Append(" )\n"); builder.Append(" .brcl = "); builder.Append(" (").Append(GetBrcl()).Append(" )\n"); builder.Append(" .brcp = "); builder.Append(" (").Append(GetBrcp()).Append(" )\n"); builder.Append(" .ilvl = "); builder.Append(" (").Append(GetIlvl()).Append(" )\n"); builder.Append(" .ilfo = "); builder.Append(" (").Append(GetIlfo()).Append(" )\n"); builder.Append(" .fNoLnn = "); builder.Append(" (").Append(GetFNoLnn()).Append(" )\n"); builder.Append(" .lspd = "); builder.Append(" (").Append(GetLspd()).Append(" )\n"); builder.Append(" .dyaBefore = "); builder.Append(" (").Append(GetDyaBefore()).Append(" )\n"); builder.Append(" .dyaAfter = "); builder.Append(" (").Append(GetDyaAfter()).Append(" )\n"); builder.Append(" .fInTable = "); builder.Append(" (").Append(GetFInTable()).Append(" )\n"); builder.Append(" .finTableW97 = "); builder.Append(" (").Append(GetFinTableW97()).Append(" )\n"); builder.Append(" .fTtp = "); builder.Append(" (").Append(GetFTtp()).Append(" )\n"); builder.Append(" .dxaAbs = "); builder.Append(" (").Append(GetDxaAbs()).Append(" )\n"); builder.Append(" .dyaAbs = "); builder.Append(" (").Append(GetDyaAbs()).Append(" )\n"); builder.Append(" .dxaWidth = "); builder.Append(" (").Append(GetDxaWidth()).Append(" )\n"); builder.Append(" .fBrLnAbove = "); builder.Append(" (").Append(GetFBrLnAbove()).Append(" )\n"); builder.Append(" .fBrLnBelow = "); builder.Append(" (").Append(GetFBrLnBelow()).Append(" )\n"); builder.Append(" .pcVert = "); builder.Append(" (").Append(GetPcVert()).Append(" )\n"); builder.Append(" .pcHorz = "); builder.Append(" (").Append(GetPcHorz()).Append(" )\n"); builder.Append(" .wr = "); builder.Append(" (").Append(GetWr()).Append(" )\n"); builder.Append(" .fNoAutoHyph = "); builder.Append(" (").Append(GetFNoAutoHyph()).Append(" )\n"); builder.Append(" .dyaHeight = "); builder.Append(" (").Append(GetDyaHeight()).Append(" )\n"); builder.Append(" .fMinHeight = "); builder.Append(" (").Append(GetFMinHeight()).Append(" )\n"); builder.Append(" .dcs = "); builder.Append(" (").Append(GetDcs()).Append(" )\n"); builder.Append(" .dyaFromText = "); builder.Append(" (").Append(GetDyaFromText()).Append(" )\n"); builder.Append(" .dxaFromText = "); builder.Append(" (").Append(GetDxaFromText()).Append(" )\n"); builder.Append(" .fLocked = "); builder.Append(" (").Append(GetFLocked()).Append(" )\n"); builder.Append(" .fWidowControl = "); builder.Append(" (").Append(GetFWidowControl()).Append(" )\n"); builder.Append(" .fKinsoku = "); builder.Append(" (").Append(GetFKinsoku()).Append(" )\n"); builder.Append(" .fWordWrap = "); builder.Append(" (").Append(GetFWordWrap()).Append(" )\n"); builder.Append(" .fOverflowPunct = "); builder.Append(" (").Append(GetFOverflowPunct()).Append(" )\n"); builder.Append(" .fTopLinePunct = "); builder.Append(" (").Append(GetFTopLinePunct()).Append(" )\n"); builder.Append(" .fAutoSpaceDE = "); builder.Append(" (").Append(GetFAutoSpaceDE()).Append(" )\n"); builder.Append(" .fAutoSpaceDN = "); builder.Append(" (").Append(GetFAutoSpaceDN()).Append(" )\n"); builder.Append(" .wAlignFont = "); builder.Append(" (").Append(GetWAlignFont()).Append(" )\n"); builder.Append(" .fontAlign = "); builder.Append(" (").Append(GetFontAlign()).Append(" )\n"); builder.Append(" .fVertical = ").Append(IsFVertical()).Append('\n'); builder.Append(" .fBackward = ").Append(IsFBackward()).Append('\n'); builder.Append(" .fRotateFont = ").Append(IsFRotateFont()).Append('\n'); builder.Append(" .lvl = "); builder.Append(" (").Append(GetLvl()).Append(" )\n"); builder.Append(" .fBiDi = "); builder.Append(" (").Append(GetFBiDi()).Append(" )\n"); builder.Append(" .fNumRMIns = "); builder.Append(" (").Append(GetFNumRMIns()).Append(" )\n"); builder.Append(" .fCrLf = "); builder.Append(" (").Append(GetFCrLf()).Append(" )\n"); builder.Append(" .fUsePgsuSettings = "); builder.Append(" (").Append(GetFUsePgsuSettings()).Append(" )\n"); builder.Append(" .fAdjustRight = "); builder.Append(" (").Append(GetFAdjustRight()).Append(" )\n"); builder.Append(" .itap = "); builder.Append(" (").Append(GetItap()).Append(" )\n"); builder.Append(" .fInnerTableCell = "); builder.Append(" (").Append(GetFInnerTableCell()).Append(" )\n"); builder.Append(" .fOpenTch = "); builder.Append(" (").Append(GetFOpenTch()).Append(" )\n"); builder.Append(" .fTtpEmbedded = "); builder.Append(" (").Append(GetFTtpEmbedded()).Append(" )\n"); builder.Append(" .dxcRight = "); builder.Append(" (").Append(GetDxcRight()).Append(" )\n"); builder.Append(" .dxcLeft = "); builder.Append(" (").Append(GetDxcLeft()).Append(" )\n"); builder.Append(" .dxcLeft1 = "); builder.Append(" (").Append(GetDxcLeft1()).Append(" )\n"); builder.Append(" .fDyaBeforeAuto = "); builder.Append(" (").Append(GetFDyaBeforeAuto()).Append(" )\n"); builder.Append(" .fDyaAfterAuto = "); builder.Append(" (").Append(GetFDyaAfterAuto()).Append(" )\n"); builder.Append(" .dxaRight = "); builder.Append(" (").Append(GetDxaRight()).Append(" )\n"); builder.Append(" .dxaLeft = "); builder.Append(" (").Append(GetDxaLeft()).Append(" )\n"); builder.Append(" .dxaLeft1 = "); builder.Append(" (").Append(GetDxaLeft1()).Append(" )\n"); builder.Append(" .jc = "); builder.Append(" (").Append(GetJc()).Append(" )\n"); builder.Append(" .fNoAllowOverlap = "); builder.Append(" (").Append(GetFNoAllowOverlap()).Append(" )\n"); builder.Append(" .brcTop = "); builder.Append(" (").Append(GetBrcTop()).Append(" )\n"); builder.Append(" .brcLeft = "); builder.Append(" (").Append(GetBrcLeft()).Append(" )\n"); builder.Append(" .brcBottom = "); builder.Append(" (").Append(GetBrcBottom()).Append(" )\n"); builder.Append(" .brcRight = "); builder.Append(" (").Append(GetBrcRight()).Append(" )\n"); builder.Append(" .brcBetween = "); builder.Append(" (").Append(GetBrcBetween()).Append(" )\n"); builder.Append(" .brcBar = "); builder.Append(" (").Append(GetBrcBar()).Append(" )\n"); builder.Append(" .shd = "); builder.Append(" (").Append(GetShd()).Append(" )\n"); builder.Append(" .anld = "); builder.Append(" (").Append(GetAnld()).Append(" )\n"); builder.Append(" .phe = "); builder.Append(" (").Append(GetPhe()).Append(" )\n"); builder.Append(" .fPropRMark = "); builder.Append(" (").Append(GetFPropRMark()).Append(" )\n"); builder.Append(" .ibstPropRMark = "); builder.Append(" (").Append(GetIbstPropRMark()).Append(" )\n"); builder.Append(" .dttmPropRMark = "); builder.Append(" (").Append(GetDttmPropRMark()).Append(" )\n"); builder.Append(" .itbdMac = "); builder.Append(" (").Append(GetItbdMac()).Append(" )\n"); builder.Append(" .rgdxaTab = "); builder.Append(" (").Append(GetRgdxaTab()).Append(" )\n"); builder.Append(" .rgtbd = "); builder.Append(" (").Append(GetRgtbd()).Append(" )\n"); builder.Append(" .numrm = "); builder.Append(" (").Append(GetNumrm()).Append(" )\n"); builder.Append(" .ptap = "); builder.Append(" (").Append(GetPtap()).Append(" )\n"); builder.Append("[/PAP]\n"); return builder.ToString(); } /** * Index to style descriptor. */ public int GetIstd() { return field_1_istd; } /** * Index to style descriptor. */ public void SetIstd(int field_1_istd) { this.field_1_istd = field_1_istd; } /** * Get the fSideBySide field for the PAP record. */ public bool GetFSideBySide() { return field_2_fSideBySide; } /** * Set the fSideBySide field for the PAP record. */ public void SetFSideBySide(bool field_2_fSideBySide) { this.field_2_fSideBySide = field_2_fSideBySide; } /** * Get the fKeep field for the PAP record. */ public bool GetFKeep() { return field_3_fKeep; } /** * Set the fKeep field for the PAP record. */ public void SetFKeep(bool field_3_fKeep) { this.field_3_fKeep = field_3_fKeep; } /** * Get the fKeepFollow field for the PAP record. */ public bool GetFKeepFollow() { return field_4_fKeepFollow; } /** * Set the fKeepFollow field for the PAP record. */ public void SetFKeepFollow(bool field_4_fKeepFollow) { this.field_4_fKeepFollow = field_4_fKeepFollow; } /** * Get the fPageBreakBefore field for the PAP record. */ public bool GetFPageBreakBefore() { return field_5_fPageBreakBefore; } /** * Set the fPageBreakBefore field for the PAP record. */ public void SetFPageBreakBefore(bool field_5_fPageBreakBefore) { this.field_5_fPageBreakBefore = field_5_fPageBreakBefore; } /** * Border line style. * * @return One of * <li>{@link #BRCL_SINGLE} * <li>{@link #BRCL_THICK} * <li>{@link #BRCL_DOUBLE} * <li>{@link #BRCL_SHADOW} */ public byte GetBrcl() { return field_6_brcl; } /** * Border line style. * * @param field_6_brcl * One of * <li>{@link #BRCL_SINGLE} * <li>{@link #BRCL_THICK} * <li>{@link #BRCL_DOUBLE} * <li>{@link #BRCL_SHADOW} */ public void SetBrcl(byte field_6_brcl) { this.field_6_brcl = field_6_brcl; } /** * Rectangle border codes. * * @return One of * <li>{@link #BRCP_NONE} * <li>{@link #BRCP_BORDER_ABOVE} * <li>{@link #BRCP_BORDER_BELOW} * <li>{@link #BRCP_BOX_AROUND} * <li>{@link #BRCP_BAR_TO_LEFT_OF_PARAGRAPH} */ public byte GetBrcp() { return field_7_brcp; } /** * Rectangle border codes. * * @param field_7_brcp * One of * <li>{@link #BRCP_NONE} * <li>{@link #BRCP_BORDER_ABOVE} * <li>{@link #BRCP_BORDER_BELOW} * <li>{@link #BRCP_BOX_AROUND} * <li>{@link #BRCP_BAR_TO_LEFT_OF_PARAGRAPH} */ public void SetBrcp(byte field_7_brcp) { this.field_7_brcp = field_7_brcp; } /** * List level if non-zero. */ public byte GetIlvl() { return field_8_ilvl; } /** * List level if non-zero. */ public void SetIlvl(byte field_8_ilvl) { this.field_8_ilvl = field_8_ilvl; } /** * 1-based index into the pllfo (lists structure), if non-zero. */ public int GetIlfo() { return field_9_ilfo; } /** * 1-based index into the pllfo (lists structure), if non-zero. */ public void SetIlfo(int field_9_ilfo) { this.field_9_ilfo = field_9_ilfo; } /** * No line numbering. */ public bool GetFNoLnn() { return field_10_fNoLnn; } /** * No line numbering. */ public void SetFNoLnn(bool field_10_fNoLnn) { this.field_10_fNoLnn = field_10_fNoLnn; } /** * Line spacing descriptor. */ public LineSpacingDescriptor GetLspd() { return field_11_lspd; } /** * Line spacing descriptor. */ public void SetLspd(LineSpacingDescriptor field_11_lspd) { this.field_11_lspd = field_11_lspd; } /** * Space before paragraph. */ public int GetDyaBefore() { return field_12_dyaBefore; } /** * Space before paragraph. */ public void SetDyaBefore(int field_12_dyaBefore) { this.field_12_dyaBefore = field_12_dyaBefore; } /** * Space after paragraph. */ public int GetDyaAfter() { return field_13_dyaAfter; } /** * Space after paragraph. */ public void SetDyaAfter(int field_13_dyaAfter) { this.field_13_dyaAfter = field_13_dyaAfter; } /** * Paragraph is in table flag. */ public bool GetFInTable() { return field_14_fInTable; } /** * Paragraph is in table flag. */ public void SetFInTable(bool field_14_fInTable) { this.field_14_fInTable = field_14_fInTable; } /** * Archaic paragraph is in table flag. */ public bool GetFinTableW97() { return field_15_finTableW97; } /** * Archaic paragraph is in table flag. */ public void SetFinTableW97(bool field_15_finTableW97) { this.field_15_finTableW97 = field_15_finTableW97; } /** * Table trailer paragraph (last in table row). */ public bool GetFTtp() { return field_16_fTtp; } /** * Table trailer paragraph (last in table row). */ public void SetFTtp(bool field_16_fTtp) { this.field_16_fTtp = field_16_fTtp; } /** * Get the dxaAbs field for the PAP record. */ public int GetDxaAbs() { return field_17_dxaAbs; } /** * Set the dxaAbs field for the PAP record. */ public void SetDxaAbs(int field_17_dxaAbs) { this.field_17_dxaAbs = field_17_dxaAbs; } /** * Get the dyaAbs field for the PAP record. */ public int GetDyaAbs() { return field_18_dyaAbs; } /** * Set the dyaAbs field for the PAP record. */ public void SetDyaAbs(int field_18_dyaAbs) { this.field_18_dyaAbs = field_18_dyaAbs; } /** * Get the dxaWidth field for the PAP record. */ public int GetDxaWidth() { return field_19_dxaWidth; } /** * Set the dxaWidth field for the PAP record. */ public void SetDxaWidth(int field_19_dxaWidth) { this.field_19_dxaWidth = field_19_dxaWidth; } /** * Get the fBrLnAbove field for the PAP record. */ public bool GetFBrLnAbove() { return field_20_fBrLnAbove; } /** * Set the fBrLnAbove field for the PAP record. */ public void SetFBrLnAbove(bool field_20_fBrLnAbove) { this.field_20_fBrLnAbove = field_20_fBrLnAbove; } /** * Get the fBrLnBelow field for the PAP record. */ public bool GetFBrLnBelow() { return field_21_fBrLnBelow; } /** * Set the fBrLnBelow field for the PAP record. */ public void SetFBrLnBelow(bool field_21_fBrLnBelow) { this.field_21_fBrLnBelow = field_21_fBrLnBelow; } /** * Get the pcVert field for the PAP record. */ public byte GetPcVert() { return field_22_pcVert; } /** * Set the pcVert field for the PAP record. */ public void SetPcVert(byte field_22_pcVert) { this.field_22_pcVert = field_22_pcVert; } /** * Get the pcHorz field for the PAP record. */ public byte GetPcHorz() { return field_23_pcHorz; } /** * Set the pcHorz field for the PAP record. */ public void SetPcHorz(byte field_23_pcHorz) { this.field_23_pcHorz = field_23_pcHorz; } /** * Get the wr field for the PAP record. */ public byte GetWr() { return field_24_wr; } /** * Set the wr field for the PAP record. */ public void SetWr(byte field_24_wr) { this.field_24_wr = field_24_wr; } /** * Get the fNoAutoHyph field for the PAP record. */ public bool GetFNoAutoHyph() { return field_25_fNoAutoHyph; } /** * Set the fNoAutoHyph field for the PAP record. */ public void SetFNoAutoHyph(bool field_25_fNoAutoHyph) { this.field_25_fNoAutoHyph = field_25_fNoAutoHyph; } /** * Get the dyaHeight field for the PAP record. */ public int GetDyaHeight() { return field_26_dyaHeight; } /** * Set the dyaHeight field for the PAP record. */ public void SetDyaHeight(int field_26_dyaHeight) { this.field_26_dyaHeight = field_26_dyaHeight; } /** * Minimum height is exact or auto. * * @return One of * <li>{@link #FMINHEIGHT_EXACT} * <li>{@link #FMINHEIGHT_AT_LEAST} */ public bool GetFMinHeight() { return field_27_fMinHeight; } /** * Minimum height is exact or auto. * * @param field_27_fMinHeight * One of * <li>{@link #FMINHEIGHT_EXACT} * <li>{@link #FMINHEIGHT_AT_LEAST} */ public void SetFMinHeight(bool field_27_fMinHeight) { this.field_27_fMinHeight = field_27_fMinHeight; } /** * Get the dcs field for the PAP record. */ public DropCapSpecifier GetDcs() { return field_28_dcs; } /** * Set the dcs field for the PAP record. */ public void SetDcs(DropCapSpecifier field_28_dcs) { this.field_28_dcs = field_28_dcs; } /** * Vertical distance between text and absolutely positioned object. */ public int GetDyaFromText() { return field_29_dyaFromText; } /** * Vertical distance between text and absolutely positioned object. */ public void SetDyaFromText(int field_29_dyaFromText) { this.field_29_dyaFromText = field_29_dyaFromText; } /** * Horizontal distance between text and absolutely positioned object. */ public int GetDxaFromText() { return field_30_dxaFromText; } /** * Horizontal distance between text and absolutely positioned object. */ public void SetDxaFromText(int field_30_dxaFromText) { this.field_30_dxaFromText = field_30_dxaFromText; } /** * Anchor of an absolutely positioned frame is locked. */ public bool GetFLocked() { return field_31_fLocked; } /** * Anchor of an absolutely positioned frame is locked. */ public void SetFLocked(bool field_31_fLocked) { this.field_31_fLocked = field_31_fLocked; } /** * 1, Word will prevent widowed lines in this paragraph from being placed at the beginning of a page. */ public bool GetFWidowControl() { return field_32_fWidowControl; } /** * 1, Word will prevent widowed lines in this paragraph from being placed at the beginning of a page. */ public void SetFWidowControl(bool field_32_fWidowControl) { this.field_32_fWidowControl = field_32_fWidowControl; } /** * apply Kinsoku rules when performing line wrapping. */ public bool GetFKinsoku() { return field_33_fKinsoku; } /** * apply Kinsoku rules when performing line wrapping. */ public void SetFKinsoku(bool field_33_fKinsoku) { this.field_33_fKinsoku = field_33_fKinsoku; } /** * perform word wrap. */ public bool GetFWordWrap() { return field_34_fWordWrap; } /** * perform word wrap. */ public void SetFWordWrap(bool field_34_fWordWrap) { this.field_34_fWordWrap = field_34_fWordWrap; } /** * apply overflow punctuation rules when performing line wrapping. */ public bool GetFOverflowPunct() { return field_35_fOverflowPunct; } /** * apply overflow punctuation rules when performing line wrapping. */ public void SetFOverflowPunct(bool field_35_fOverflowPunct) { this.field_35_fOverflowPunct = field_35_fOverflowPunct; } /** * perform top line punctuation Processing. */ public bool GetFTopLinePunct() { return field_36_fTopLinePunct; } /** * perform top line punctuation Processing. */ public void SetFTopLinePunct(bool field_36_fTopLinePunct) { this.field_36_fTopLinePunct = field_36_fTopLinePunct; } /** * auto space East Asian and alphabetic characters. */ public bool GetFAutoSpaceDE() { return field_37_fAutoSpaceDE; } /** * auto space East Asian and alphabetic characters. */ public void SetFAutoSpaceDE(bool field_37_fAutoSpaceDE) { this.field_37_fAutoSpaceDE = field_37_fAutoSpaceDE; } /** * auto space East Asian and numeric characters. */ public bool GetFAutoSpaceDN() { return field_38_fAutoSpaceDN; } /** * auto space East Asian and numeric characters. */ public void SetFAutoSpaceDN(bool field_38_fAutoSpaceDN) { this.field_38_fAutoSpaceDN = field_38_fAutoSpaceDN; } /** * Get the wAlignFont field for the PAP record. * * @return One of * <li>{@link #WALIGNFONT_HANGING} * <li>{@link #WALIGNFONT_CENTERED} * <li>{@link #WALIGNFONT_ROMAN} * <li>{@link #WALIGNFONT_VARIABLE} * <li>{@link #WALIGNFONT_AUTO} */ public int GetWAlignFont() { return field_39_wAlignFont; } /** * Set the wAlignFont field for the PAP record. * * @param field_39_wAlignFont * One of * <li>{@link #WALIGNFONT_HANGING} * <li>{@link #WALIGNFONT_CENTERED} * <li>{@link #WALIGNFONT_ROMAN} * <li>{@link #WALIGNFONT_VARIABLE} * <li>{@link #WALIGNFONT_AUTO} */ public void SetWAlignFont(int field_39_wAlignFont) { this.field_39_wAlignFont = field_39_wAlignFont; } /** * Used internally by Word. */ public short GetFontAlign() { return field_40_fontAlign; } /** * Used internally by Word. */ public void SetFontAlign(short field_40_fontAlign) { this.field_40_fontAlign = field_40_fontAlign; } /** * Outline level. */ public byte GetLvl() { return field_41_lvl; } /** * Outline level. */ public void SetLvl(byte field_41_lvl) { this.field_41_lvl = field_41_lvl; } /** * Get the fBiDi field for the PAP record. */ public bool GetFBiDi() { return field_42_fBiDi; } /** * Set the fBiDi field for the PAP record. */ public void SetFBiDi(bool field_42_fBiDi) { this.field_42_fBiDi = field_42_fBiDi; } /** * Get the fNumRMIns field for the PAP record. */ public bool GetFNumRMIns() { return field_43_fNumRMIns; } /** * Set the fNumRMIns field for the PAP record. */ public void SetFNumRMIns(bool field_43_fNumRMIns) { this.field_43_fNumRMIns = field_43_fNumRMIns; } /** * Get the fCrLf field for the PAP record. */ public bool GetFCrLf() { return field_44_fCrLf; } /** * Set the fCrLf field for the PAP record. */ public void SetFCrLf(bool field_44_fCrLf) { this.field_44_fCrLf = field_44_fCrLf; } /** * Get the fUsePgsuSettings field for the PAP record. */ public bool GetFUsePgsuSettings() { return field_45_fUsePgsuSettings; } /** * Set the fUsePgsuSettings field for the PAP record. */ public void SetFUsePgsuSettings(bool field_45_fUsePgsuSettings) { this.field_45_fUsePgsuSettings = field_45_fUsePgsuSettings; } /** * Get the fAdjustRight field for the PAP record. */ public bool GetFAdjustRight() { return field_46_fAdjustRight; } /** * Set the fAdjustRight field for the PAP record. */ public void SetFAdjustRight(bool field_46_fAdjustRight) { this.field_46_fAdjustRight = field_46_fAdjustRight; } /** * Table nesting level. */ public int GetItap() { return field_47_itap; } /** * Table nesting level. */ public void SetItap(int field_47_itap) { this.field_47_itap = field_47_itap; } /** * When 1, the end of paragraph mark is really an end of cell mark for a nested table cell. */ public bool GetFInnerTableCell() { return field_48_fInnerTableCell; } /** * When 1, the end of paragraph mark is really an end of cell mark for a nested table cell. */ public void SetFInnerTableCell(bool field_48_fInnerTableCell) { this.field_48_fInnerTableCell = field_48_fInnerTableCell; } /** * Ensure the Table Cell char doesn't show up as zero height. */ public bool GetFOpenTch() { return field_49_fOpenTch; } /** * Ensure the Table Cell char doesn't show up as zero height. */ public void SetFOpenTch(bool field_49_fOpenTch) { this.field_49_fOpenTch = field_49_fOpenTch; } /** * Word 97 compatibility indicates this end of paragraph mark is really an end of row marker for a nested table. */ public bool GetFTtpEmbedded() { return field_50_fTtpEmbedded; } /** * Word 97 compatibility indicates this end of paragraph mark is really an end of row marker for a nested table. */ public void SetFTtpEmbedded(bool field_50_fTtpEmbedded) { this.field_50_fTtpEmbedded = field_50_fTtpEmbedded; } /** * Right indent in character units. */ public short GetDxcRight() { return field_51_dxcRight; } /** * Right indent in character units. */ public void SetDxcRight(short field_51_dxcRight) { this.field_51_dxcRight = field_51_dxcRight; } /** * Left indent in character units. */ public short GetDxcLeft() { return field_52_dxcLeft; } /** * Left indent in character units. */ public void SetDxcLeft(short field_52_dxcLeft) { this.field_52_dxcLeft = field_52_dxcLeft; } /** * First line indent in character units. */ public short GetDxcLeft1() { return field_53_dxcLeft1; } /** * First line indent in character units. */ public void SetDxcLeft1(short field_53_dxcLeft1) { this.field_53_dxcLeft1 = field_53_dxcLeft1; } /** * Vertical spacing before is automatic. */ public bool GetFDyaBeforeAuto() { return field_54_fDyaBeforeAuto; } /** * Vertical spacing before is automatic. */ public void SetFDyaBeforeAuto(bool field_54_fDyaBeforeAuto) { this.field_54_fDyaBeforeAuto = field_54_fDyaBeforeAuto; } /** * Vertical spacing after is automatic. */ public bool GetFDyaAfterAuto() { return field_55_fDyaAfterAuto; } /** * Vertical spacing after is automatic. */ public void SetFDyaAfterAuto(bool field_55_fDyaAfterAuto) { this.field_55_fDyaAfterAuto = field_55_fDyaAfterAuto; } /** * Get the dxaRight field for the PAP record. */ public int GetDxaRight() { return field_56_dxaRight; } /** * Set the dxaRight field for the PAP record. */ public void SetDxaRight(int field_56_dxaRight) { this.field_56_dxaRight = field_56_dxaRight; } /** * Get the dxaLeft field for the PAP record. */ public int GetDxaLeft() { return field_57_dxaLeft; } /** * Set the dxaLeft field for the PAP record. */ public void SetDxaLeft(int field_57_dxaLeft) { this.field_57_dxaLeft = field_57_dxaLeft; } /** * Get the dxaLeft1 field for the PAP record. */ public int GetDxaLeft1() { return field_58_dxaLeft1; } /** * Set the dxaLeft1 field for the PAP record. */ public void SetDxaLeft1(int field_58_dxaLeft1) { this.field_58_dxaLeft1 = field_58_dxaLeft1; } /** * Get the jc field for the PAP record. */ public byte GetJc() { return field_59_jc; } /** * Set the jc field for the PAP record. */ public void SetJc(byte field_59_jc) { this.field_59_jc = field_59_jc; } /** * Get the fNoAllowOverlap field for the PAP record. */ public bool GetFNoAllowOverlap() { return field_60_fNoAllowOverlap; } /** * Set the fNoAllowOverlap field for the PAP record. */ public void SetFNoAllowOverlap(bool field_60_fNoAllowOverlap) { this.field_60_fNoAllowOverlap = field_60_fNoAllowOverlap; } /** * Get the brcTop field for the PAP record. */ public BorderCode GetBrcTop() { return field_61_brcTop; } /** * Set the brcTop field for the PAP record. */ public void SetBrcTop(BorderCode field_61_brcTop) { this.field_61_brcTop = field_61_brcTop; } /** * Get the brcLeft field for the PAP record. */ public BorderCode GetBrcLeft() { return field_62_brcLeft; } /** * Set the brcLeft field for the PAP record. */ public void SetBrcLeft(BorderCode field_62_brcLeft) { this.field_62_brcLeft = field_62_brcLeft; } /** * Get the brcBottom field for the PAP record. */ public BorderCode GetBrcBottom() { return field_63_brcBottom; } /** * Set the brcBottom field for the PAP record. */ public void SetBrcBottom(BorderCode field_63_brcBottom) { this.field_63_brcBottom = field_63_brcBottom; } /** * Get the brcRight field for the PAP record. */ public BorderCode GetBrcRight() { return field_64_brcRight; } /** * Set the brcRight field for the PAP record. */ public void SetBrcRight(BorderCode field_64_brcRight) { this.field_64_brcRight = field_64_brcRight; } /** * Get the brcBetween field for the PAP record. */ public BorderCode GetBrcBetween() { return field_65_brcBetween; } /** * Set the brcBetween field for the PAP record. */ public void SetBrcBetween(BorderCode field_65_brcBetween) { this.field_65_brcBetween = field_65_brcBetween; } /** * Get the brcBar field for the PAP record. */ public BorderCode GetBrcBar() { return field_66_brcBar; } /** * Set the brcBar field for the PAP record. */ public void SetBrcBar(BorderCode field_66_brcBar) { this.field_66_brcBar = field_66_brcBar; } /** * Get the shd field for the PAP record. */ public ShadingDescriptor GetShd() { return field_67_shd; } /** * Set the shd field for the PAP record. */ public void SetShd(ShadingDescriptor field_67_shd) { this.field_67_shd = field_67_shd; } /** * Get the anld field for the PAP record. */ public byte[] GetAnld() { return field_68_anld; } /** * Set the anld field for the PAP record. */ public void SetAnld(byte[] field_68_anld) { this.field_68_anld = field_68_anld; } /** * Get the phe field for the PAP record. */ public byte[] GetPhe() { return field_69_phe; } /** * Set the phe field for the PAP record. */ public void SetPhe(byte[] field_69_phe) { this.field_69_phe = field_69_phe; } /** * Get the fPropRMark field for the PAP record. */ public bool GetFPropRMark() { return field_70_fPropRMark; } /** * Set the fPropRMark field for the PAP record. */ public void SetFPropRMark(bool field_70_fPropRMark) { this.field_70_fPropRMark = field_70_fPropRMark; } /** * Get the ibstPropRMark field for the PAP record. */ public int GetIbstPropRMark() { return field_71_ibstPropRMark; } /** * Set the ibstPropRMark field for the PAP record. */ public void SetIbstPropRMark(int field_71_ibstPropRMark) { this.field_71_ibstPropRMark = field_71_ibstPropRMark; } /** * Get the dttmPropRMark field for the PAP record. */ public DateAndTime GetDttmPropRMark() { return field_72_dttmPropRMark; } /** * Set the dttmPropRMark field for the PAP record. */ public void SetDttmPropRMark(DateAndTime field_72_dttmPropRMark) { this.field_72_dttmPropRMark = field_72_dttmPropRMark; } /** * Get the itbdMac field for the PAP record. */ public int GetItbdMac() { return field_73_itbdMac; } /** * Set the itbdMac field for the PAP record. */ public void SetItbdMac(int field_73_itbdMac) { this.field_73_itbdMac = field_73_itbdMac; } /** * Get the rgdxaTab field for the PAP record. */ public int[] GetRgdxaTab() { return field_74_rgdxaTab; } /** * Set the rgdxaTab field for the PAP record. */ public void SetRgdxaTab(int[] field_74_rgdxaTab) { this.field_74_rgdxaTab = field_74_rgdxaTab; } /** * Get the rgtbd field for the PAP record. */ public byte[] GetRgtbd() { return field_75_rgtbd; } /** * Set the rgtbd field for the PAP record. */ public void SetRgtbd(byte[] field_75_rgtbd) { this.field_75_rgtbd = field_75_rgtbd; } /** * Get the numrm field for the PAP record. */ public byte[] GetNumrm() { return field_76_numrm; } /** * Set the numrm field for the PAP record. */ public void SetNumrm(byte[] field_76_numrm) { this.field_76_numrm = field_76_numrm; } /** * Get the ptap field for the PAP record. */ public byte[] GetPtap() { return field_77_ptap; } /** * Set the ptap field for the PAP record. */ public void SetPtap(byte[] field_77_ptap) { this.field_77_ptap = field_77_ptap; } /** * Sets the fVertical field value. * */ public void SetFVertical(bool value) { field_40_fontAlign = (short)fVertical.SetBoolean(field_40_fontAlign, value); } /** * * @return the fVertical field value. */ public bool IsFVertical() { return fVertical.IsSet(field_40_fontAlign); } /** * Sets the fBackward field value. * */ public void SetFBackward(bool value) { field_40_fontAlign = (short)fBackward.SetBoolean(field_40_fontAlign, value); } /** * * @return the fBackward field value. */ public bool IsFBackward() { return fBackward.IsSet(field_40_fontAlign); } /** * Sets the fRotateFont field value. * */ public void SetFRotateFont(bool value) { field_40_fontAlign = (short)fRotateFont.SetBoolean(field_40_fontAlign, value); } /** * * @return the fRotateFont field value. */ public bool IsFRotateFont() { return fRotateFont.IsSet(field_40_fontAlign); } } }
30.704734
121
0.497023
[ "Apache-2.0" ]
sunshinele/npoi
scratchpad/HWPF/Model/Types/PAPAbstractType.cs
51,891
C#
// This file is auto generated, do not edit. using System; namespace Gwi.OpenGL.GLCompat { #pragma warning disable IDE1006 // Naming Styles unsafe partial class GL { private SGIXExtension? _SGIX; public SGIXExtension SGIX => _SGIX ??= new SGIXExtension(this); public sealed unsafe partial class SGIXExtension { private readonly VTable vtable; internal SGIXExtension(GL gl) => vtable = new VTable(gl.Lib); public void AsyncMarkerSGIX(uint marker) => ((delegate* unmanaged[Cdecl]<uint, void>)vtable.glAsyncMarkerSGIX)(marker); public int FinishAsyncSGIX(uint* markerp) => ((delegate* unmanaged[Cdecl]<uint*, int>)vtable.glFinishAsyncSGIX)(markerp); public int PollAsyncSGIX(uint* markerp) => ((delegate* unmanaged[Cdecl]<uint*, int>)vtable.glPollAsyncSGIX)(markerp); public uint GenAsyncMarkersSGIX(int range) => ((delegate* unmanaged[Cdecl]<int, uint>)vtable.glGenAsyncMarkersSGIX)(range); public void DeleteAsyncMarkersSGIX(uint marker, int range) => ((delegate* unmanaged[Cdecl]<uint, int, void>)vtable.glDeleteAsyncMarkersSGIX)(marker, range); public byte IsAsyncMarkerSGIX(uint marker) => ((delegate* unmanaged[Cdecl]<uint, byte>)vtable.glIsAsyncMarkerSGIX)(marker); public void FlushRasterSGIX() => ((delegate* unmanaged[Cdecl]<void>)vtable.glFlushRasterSGIX)(); public void FragmentColorMaterialSGIX(MaterialFace face, MaterialParameter mode) => ((delegate* unmanaged[Cdecl]<MaterialFace, MaterialParameter, void>)vtable.glFragmentColorMaterialSGIX)(face, mode); public void FragmentLightfSGIX(FragmentLightNameSGIX light, FragmentLightParameterSGIX pname, float param) => ((delegate* unmanaged[Cdecl]<FragmentLightNameSGIX, FragmentLightParameterSGIX, float, void>)vtable.glFragmentLightfSGIX)(light, pname, param); public void FragmentLightfvSGIX(FragmentLightNameSGIX light, FragmentLightParameterSGIX pname, float* parameters) => ((delegate* unmanaged[Cdecl]<FragmentLightNameSGIX, FragmentLightParameterSGIX, float*, void>)vtable.glFragmentLightfvSGIX)(light, pname, parameters); public void FragmentLightiSGIX(FragmentLightNameSGIX light, FragmentLightParameterSGIX pname, int param) => ((delegate* unmanaged[Cdecl]<FragmentLightNameSGIX, FragmentLightParameterSGIX, int, void>)vtable.glFragmentLightiSGIX)(light, pname, param); public void FragmentLightivSGIX(FragmentLightNameSGIX light, FragmentLightParameterSGIX pname, int* parameters) => ((delegate* unmanaged[Cdecl]<FragmentLightNameSGIX, FragmentLightParameterSGIX, int*, void>)vtable.glFragmentLightivSGIX)(light, pname, parameters); public void FragmentLightModelfSGIX(FragmentLightModelParameterSGIX pname, float param) => ((delegate* unmanaged[Cdecl]<FragmentLightModelParameterSGIX, float, void>)vtable.glFragmentLightModelfSGIX)(pname, param); public void FragmentLightModelfvSGIX(FragmentLightModelParameterSGIX pname, float* parameters) => ((delegate* unmanaged[Cdecl]<FragmentLightModelParameterSGIX, float*, void>)vtable.glFragmentLightModelfvSGIX)(pname, parameters); public void FragmentLightModeliSGIX(FragmentLightModelParameterSGIX pname, int param) => ((delegate* unmanaged[Cdecl]<FragmentLightModelParameterSGIX, int, void>)vtable.glFragmentLightModeliSGIX)(pname, param); public void FragmentLightModelivSGIX(FragmentLightModelParameterSGIX pname, int* parameters) => ((delegate* unmanaged[Cdecl]<FragmentLightModelParameterSGIX, int*, void>)vtable.glFragmentLightModelivSGIX)(pname, parameters); public void FragmentMaterialfSGIX(MaterialFace face, MaterialParameter pname, float param) => ((delegate* unmanaged[Cdecl]<MaterialFace, MaterialParameter, float, void>)vtable.glFragmentMaterialfSGIX)(face, pname, param); public void FragmentMaterialfvSGIX(MaterialFace face, MaterialParameter pname, float* parameters) => ((delegate* unmanaged[Cdecl]<MaterialFace, MaterialParameter, float*, void>)vtable.glFragmentMaterialfvSGIX)(face, pname, parameters); public void FragmentMaterialiSGIX(MaterialFace face, MaterialParameter pname, int param) => ((delegate* unmanaged[Cdecl]<MaterialFace, MaterialParameter, int, void>)vtable.glFragmentMaterialiSGIX)(face, pname, param); public void FragmentMaterialivSGIX(MaterialFace face, MaterialParameter pname, int* parameters) => ((delegate* unmanaged[Cdecl]<MaterialFace, MaterialParameter, int*, void>)vtable.glFragmentMaterialivSGIX)(face, pname, parameters); public void GetFragmentLightfvSGIX(FragmentLightNameSGIX light, FragmentLightParameterSGIX pname, float* parameters) => ((delegate* unmanaged[Cdecl]<FragmentLightNameSGIX, FragmentLightParameterSGIX, float*, void>)vtable.glGetFragmentLightfvSGIX)(light, pname, parameters); public void GetFragmentLightivSGIX(FragmentLightNameSGIX light, FragmentLightParameterSGIX pname, int* parameters) => ((delegate* unmanaged[Cdecl]<FragmentLightNameSGIX, FragmentLightParameterSGIX, int*, void>)vtable.glGetFragmentLightivSGIX)(light, pname, parameters); public void GetFragmentMaterialfvSGIX(MaterialFace face, MaterialParameter pname, float* parameters) => ((delegate* unmanaged[Cdecl]<MaterialFace, MaterialParameter, float*, void>)vtable.glGetFragmentMaterialfvSGIX)(face, pname, parameters); public void GetFragmentMaterialivSGIX(MaterialFace face, MaterialParameter pname, int* parameters) => ((delegate* unmanaged[Cdecl]<MaterialFace, MaterialParameter, int*, void>)vtable.glGetFragmentMaterialivSGIX)(face, pname, parameters); public void LightEnviSGIX(LightEnvParameterSGIX pname, int param) => ((delegate* unmanaged[Cdecl]<LightEnvParameterSGIX, int, void>)vtable.glLightEnviSGIX)(pname, param); public void FrameZoomSGIX(int factor) => ((delegate* unmanaged[Cdecl]<int, void>)vtable.glFrameZoomSGIX)(factor); public void IglooInterfaceSGIX(GLEnum pname, void* parameters) => ((delegate* unmanaged[Cdecl]<GLEnum, void*, void>)vtable.glIglooInterfaceSGIX)(pname, parameters); public int GetInstrumentsSGIX() => ((delegate* unmanaged[Cdecl]<int>)vtable.glGetInstrumentsSGIX)(); public void InstrumentsBufferSGIX(int size, int* buffer) => ((delegate* unmanaged[Cdecl]<int, int*, void>)vtable.glInstrumentsBufferSGIX)(size, buffer); public int PollInstrumentsSGIX(int* marker_p) => ((delegate* unmanaged[Cdecl]<int*, int>)vtable.glPollInstrumentsSGIX)(marker_p); public void ReadInstrumentsSGIX(int marker) => ((delegate* unmanaged[Cdecl]<int, void>)vtable.glReadInstrumentsSGIX)(marker); public void StartInstrumentsSGIX() => ((delegate* unmanaged[Cdecl]<void>)vtable.glStartInstrumentsSGIX)(); public void StopInstrumentsSGIX(int marker) => ((delegate* unmanaged[Cdecl]<int, void>)vtable.glStopInstrumentsSGIX)(marker); public void GetListParameterfvSGIX(uint list, ListParameterName pname, float* parameters) => ((delegate* unmanaged[Cdecl]<uint, ListParameterName, float*, void>)vtable.glGetListParameterfvSGIX)(list, pname, parameters); public void GetListParameterivSGIX(uint list, ListParameterName pname, int* parameters) => ((delegate* unmanaged[Cdecl]<uint, ListParameterName, int*, void>)vtable.glGetListParameterivSGIX)(list, pname, parameters); public void ListParameterfSGIX(uint list, ListParameterName pname, float param) => ((delegate* unmanaged[Cdecl]<uint, ListParameterName, float, void>)vtable.glListParameterfSGIX)(list, pname, param); public void ListParameterfvSGIX(uint list, ListParameterName pname, float* parameters) => ((delegate* unmanaged[Cdecl]<uint, ListParameterName, float*, void>)vtable.glListParameterfvSGIX)(list, pname, parameters); public void ListParameteriSGIX(uint list, ListParameterName pname, int param) => ((delegate* unmanaged[Cdecl]<uint, ListParameterName, int, void>)vtable.glListParameteriSGIX)(list, pname, param); public void ListParameterivSGIX(uint list, ListParameterName pname, int* parameters) => ((delegate* unmanaged[Cdecl]<uint, ListParameterName, int*, void>)vtable.glListParameterivSGIX)(list, pname, parameters); public void PixelTexGenSGIX(PixelTexGenModeSGIX mode) => ((delegate* unmanaged[Cdecl]<PixelTexGenModeSGIX, void>)vtable.glPixelTexGenSGIX)(mode); public void DeformationMap3dSGIX(FfdTargetSGIX target, double u1, double u2, int ustride, int uorder, double v1, double v2, int vstride, int vorder, double w1, double w2, int wstride, int worder, double* points) => ((delegate* unmanaged[Cdecl]<FfdTargetSGIX, double, double, int, int, double, double, int, int, double, double, int, int, double*, void>)vtable.glDeformationMap3dSGIX)(target, u1, u2, ustride, uorder, v1, v2, vstride, vorder, w1, w2, wstride, worder, points); public void DeformationMap3fSGIX(FfdTargetSGIX target, float u1, float u2, int ustride, int uorder, float v1, float v2, int vstride, int vorder, float w1, float w2, int wstride, int worder, float* points) => ((delegate* unmanaged[Cdecl]<FfdTargetSGIX, float, float, int, int, float, float, int, int, float, float, int, int, float*, void>)vtable.glDeformationMap3fSGIX)(target, u1, u2, ustride, uorder, v1, v2, vstride, vorder, w1, w2, wstride, worder, points); public void DeformSGIX(FfdMaskSGIX mask) => ((delegate* unmanaged[Cdecl]<FfdMaskSGIX, void>)vtable.glDeformSGIX)(mask); public void LoadIdentityDeformationMapSGIX(FfdMaskSGIX mask) => ((delegate* unmanaged[Cdecl]<FfdMaskSGIX, void>)vtable.glLoadIdentityDeformationMapSGIX)(mask); public void ReferencePlaneSGIX(double* equation) => ((delegate* unmanaged[Cdecl]<double*, void>)vtable.glReferencePlaneSGIX)(equation); public void SpriteParameterfSGIX(SpriteParameterNameSGIX pname, float param) => ((delegate* unmanaged[Cdecl]<SpriteParameterNameSGIX, float, void>)vtable.glSpriteParameterfSGIX)(pname, param); public void SpriteParameterfvSGIX(SpriteParameterNameSGIX pname, float* parameters) => ((delegate* unmanaged[Cdecl]<SpriteParameterNameSGIX, float*, void>)vtable.glSpriteParameterfvSGIX)(pname, parameters); public void SpriteParameteriSGIX(SpriteParameterNameSGIX pname, int param) => ((delegate* unmanaged[Cdecl]<SpriteParameterNameSGIX, int, void>)vtable.glSpriteParameteriSGIX)(pname, param); public void SpriteParameterivSGIX(SpriteParameterNameSGIX pname, int* parameters) => ((delegate* unmanaged[Cdecl]<SpriteParameterNameSGIX, int*, void>)vtable.glSpriteParameterivSGIX)(pname, parameters); public void TagSampleBufferSGIX() => ((delegate* unmanaged[Cdecl]<void>)vtable.glTagSampleBufferSGIX)(); } } #pragma warning restore IDE1006 // Naming Styles }
147.256757
486
0.756997
[ "MIT" ]
odalet/Gwi
src/Gwi.OpenGL/Gwi.OpenGL.V1/generated/GLCompat/SGIX/GL.SGIX.cs
10,897
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Linq; using System.Reflection; using Microsoft.Extensions.DependencyInjection; namespace Microsoft.AspNetCore.Hosting.Internal { public class ConfigureServicesBuilder { public ConfigureServicesBuilder(MethodInfo configureServices) { MethodInfo = configureServices; } public MethodInfo MethodInfo { get; } public Func<Func<IServiceCollection, IServiceProvider>, Func<IServiceCollection, IServiceProvider>> StartupServiceFilters { get; set; } = f => f; public Func<IServiceCollection, IServiceProvider> Build(object instance) => services => Invoke(instance, services); private IServiceProvider Invoke(object instance, IServiceCollection services) { return StartupServiceFilters(Startup)(services); IServiceProvider Startup(IServiceCollection serviceCollection) => InvokeCore(instance, serviceCollection); } private IServiceProvider InvokeCore(object instance, IServiceCollection services) { if (MethodInfo == null) { return null; } // Only support IServiceCollection parameters var parameters = MethodInfo.GetParameters(); if (parameters.Length > 1 || parameters.Any(p => p.ParameterType != typeof(IServiceCollection))) { throw new InvalidOperationException("The ConfigureServices method must either be parameterless or take only one parameter of type IServiceCollection."); } var arguments = new object[MethodInfo.GetParameters().Length]; if (parameters.Length > 0) { arguments[0] = services; } return MethodInfo.InvokeWithoutWrappingExceptions(instance, arguments) as IServiceProvider; } } }
36.175439
168
0.661979
[ "Apache-2.0" ]
CBaud/AspNetCore
src/Hosting/Hosting/src/Internal/ConfigureServicesBuilder.cs
2,062
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace ExportadorContatosGoogle { public partial class FormGerenciadorContatosVCardV3 : Form { private string DirArquivo { get; set; } private DataTable TblListaAtual { get; set; } //private List<string> CamposGoogleIngles = new List<string> { "Selecione...", "Given Name", "Name Prefix", "Nickname", "Birthday", "Gender", "Occupation", "Notes", "Group Membership", "Phone 1 - Type", "Phone 1 - Value", "Phone 2 - Type", "Phone 2- Value", "Phone 3 - Type", "Phone 3- Value", "Phone 4 - Type", "Phone 4- Value", "Phone 5 - Type", "Phone 5- Value", "Phone 6 - Type", "Phone 6- Value", "Address 1 - Type", "Address 1 - Formatted", "Address 1 - Street", "Address 1 - City", "Address 1 - PO Box", "Address 1 - Region", "Address 1 - Postal Code", "Address 1 - Country", "Address 1 - Extended Address", "Relation 1 - Type", "Relation 1 - Value", "Event 1 - Type", "Event 1 - Value" }; //private List<string> CamposGooglePortugues = new List<string> { "Selecione...", "Nome completo", "Tratamento", "Apelido", "Data nascimento", "Sexo", "Telefone Principal", "Telefone 2", "Telefone 3", "Telefone 4", "Telefone 5", "Telefone 6", "Email Pessoal", "Email Comercial", "Endereço Res.", "Bairro Res.", "Cidade Res.", "Estado Res.", "CEP Res.", "País Res.", "Endereço Com.", "Bairro Com.", "Cidade Com.", "Estado Com.", "CEP Com.", "País Com.", "Empresa", "Cargo/Funcão", "Nota/Histórico", "Site Pessoal", "Site Comercial", "Nome Cônjuge", "Data aniv. Cônjuge", "Nome do pai", "Nome da mãe", "Grupos" }; private List<string> CamposGooglePortugues = new List<string> { "Selecione...", "Nome completo", "Tratamento", "Apelido", "Data nascimento", "Sexo", "Telefone Principal", "Telefone 2", "Telefone 3", "Telefone 4", "Telefone 5", "Telefone 6", "Email Pessoal", "Email Comercial", "Endereço Res.", "Endereço Res. Núm.", "Bairro Res.", "Cidade Res.", "Estado Res.", "CEP Res.", "País Res.", "Endereço Com.", "Endereço Com. Núm.", "Bairro Com.", "Cidade Com.", "Estado Com.", "CEP Com.", "País Com.", "Empresa", "Cargo/Funcão", "Nota/Histórico", "Site Pessoal", "Site Comercial", "Nome Cônjuge", "Data aniv. Cônjuge", "Nome do pai", "Nome da mãe", "Grupos" }; private DataTable ColunaComboBoxCamposSelecaoGoogle; private string NomeUltimoCampo = "Event 1 - Value"; private StringBuilder gruposLinhaAtual = new StringBuilder(); private bool grupoLinhaJaProcessado = false; public FormGerenciadorContatosVCardV3() { InitializeComponent(); //this.dataGridView1.RowsDefaultCellStyle.BackColor = Color.Bisque; this.dataGridView1.AlternatingRowsDefaultCellStyle.BackColor = Color.Beige; dataGridView1.CellValueChanged += new DataGridViewCellEventHandler(dataGridView1_CellValueChanged); dataGridView1.EditingControlShowing += new DataGridViewEditingControlShowingEventHandler(dataGridView1_EditingControlShowing); dataGridView1.SelectionChanged += new EventHandler(dataGridView1_SelectionChanged); } private void dataGridView1_SelectionChanged(object sender, EventArgs e) { } private void FormGerenciadorContatosVCardV3_Load(object sender, EventArgs e) { } private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e) { } int indiceCo = 0; private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e) { try { indiceCo = e.ColumnIndex; DataGridViewComboBoxCell cb = (DataGridViewComboBoxCell)dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex]; if (cb.Value != null) { //Mensagens.Informa(string.Format("Voce selecionou: {0}", cb.EditedFormattedValue)); foreach (DataGridViewComboBoxCell item in dataGridView1.Rows[0].Cells) { string CampoAtualSelecionado = dataGridView1.Rows[0].Cells[item.ColumnIndex].FormattedValue.ToString(); //percorre todas as colunas que não seja essa atual... if (item.ColumnIndex == e.ColumnIndex) continue; if (CampoAtualSelecionado == "Grupos") continue; if (item.Value == cb.Value) { Mensagens.Informa(string.Format("Já existe um campo selecionado para \"{0}\".\nSelecione outra opção para continuar. ", cb.FormattedValue)); //cb.Value = 0; break; } } } } catch (Exception ex) { throw ex; } } private void MenuArquivoExcelXLSX_Click(object sender, EventArgs e) { AbrirTamplates.Title = "Buscar Arquivo Excel"; //AbrirTamplates.InitialDirectory = DirArquivo; //AbrirTamplates.FileName = string.Empty; AbrirTamplates.DefaultExt = ".xlsx"; AbrirTamplates.Filter = "Arquivos Excel|*.xlsx"; AbrirTamplates.RestoreDirectory = true; if (AbrirTamplates.ShowDialog() == System.Windows.Forms.DialogResult.OK) { string NomePlan = RetornaNomePlanilhaSelecionadoXLS(AbrirTamplates.FileName); if (string.IsNullOrEmpty(NomePlan)) return; try { using (DataTable dt = new ImportarArquivos().ImportarXLSXNovo(AbrirTamplates.FileName, string.Format("{0}$", NomePlan.Replace("$", "")), 0)) { if (dt != null && dt.Rows.Count > 0) { CarregaGridView(dt); return; } else { Mensagens.Alerta("Não foi possível carregar nenhum registro apartir do .xlsx informado. Por favor selecione outro arquivo."); } } } catch (Exception ex) { Mensagens.Erro(string.Format("Não foi possível carregar o arquivo: {0}", ex.Message)); } } } private void MenuArquivoExcelXLS_Click(object sender, EventArgs e) { AbrirTamplates.Title = "Buscar Arquivo Excel"; //AbrirTamplates.InitialDirectory = DirArquivo; //AbrirTamplates.FileName = string.Empty; AbrirTamplates.DefaultExt = ".xls"; AbrirTamplates.Filter = "Arquivos Excel|*.xls*"; AbrirTamplates.RestoreDirectory = true; if (AbrirTamplates.ShowDialog() == System.Windows.Forms.DialogResult.OK) { string NomePlan = RetornaNomePlanilhaSelecionadoXLS(AbrirTamplates.FileName); if (string.IsNullOrEmpty(NomePlan)) return; try { //using (DataTable dt = new ImportarArquivos().ImportarXLS(AbrirTamplates.FileName, NomePlan)) using (DataTable dt = new ImportarArquivos().ImportarXLSXNovo(AbrirTamplates.FileName, string.Format("{0}$", NomePlan.Replace("$", "")), 0)) { if (dt != null && dt.Rows.Count > 0) { CarregaGridView(dt); return; } else { Mensagens.Alerta("Não foi possível carregar nenhum registro apartir do .xls informado. Por favor selecione outro arquivo."); } } } catch (Exception ex) { Mensagens.Erro(string.Format("Não foi possível carregar o arquivo: {0}", ex.Message)); } } } private void MenuArquivoExcelCSV_Click(object sender, EventArgs e) { AbrirTamplates.Title = "Buscar Arquivo Excel"; //AbrirTamplates.InitialDirectory = DirArquivo; //AbrirTamplates.FileName = string.Empty; AbrirTamplates.DefaultExt = ".csv"; AbrirTamplates.Filter = "Arquivos Excel|*.csv"; AbrirTamplates.RestoreDirectory = true; if (AbrirTamplates.ShowDialog() == System.Windows.Forms.DialogResult.OK) { //string NomePlan = RetornaNomePlanilhaSelecionado(); //if (string.IsNullOrEmpty(NomePlan)) return; try { ImportarArquivos csv = new ImportarArquivos(); using (DataTable dt = csv.ImportarSCV(AbrirTamplates.FileName)) { if (dt != null && dt.Rows.Count > 0) { CarregaGridView(dt); return; } else { Mensagens.Alerta("Não foi possível carregar nenhum registro apartir do .csv informado. Por favor selecione outro arquivo."); } } } catch (Exception ex) { Mensagens.Erro(string.Format("Não foi possível carregar o arquivo: {0}", ex.Message)); } } } private void MenuArquivoExcelXML_Click(object sender, EventArgs e) { AbrirTamplates.Title = "Buscar Arquivo XML"; AbrirTamplates.InitialDirectory = DirArquivo; AbrirTamplates.FileName = string.Empty; AbrirTamplates.DefaultExt = ".xml"; AbrirTamplates.Filter = "Arquivos XML|*.xml|*.XML|"; AbrirTamplates.RestoreDirectory = true; if (AbrirTamplates.ShowDialog() == System.Windows.Forms.DialogResult.OK) { try { using (DataSet Ds = new DataSet()) { Ds.ReadXml(AbrirTamplates.FileName); if (Ds != null && Ds.Tables[0].Rows.Count > 0) { CarregaGridView(Ds.Tables[0]); return; } else { Mensagens.Alerta("Não foi possível carregar nenhum registro apartir do XML informado. Por favor selecione outro arquivo."); } } } catch (Exception ex) { Mensagens.Erro(string.Format("Não foi possível carregar o arquivo XML. {0}", ex.Message)); } } } private string RetornaNomePlanilhaSelecionadoXLS(string nomeArquivoBuscado) { List<DataTable> ListaDt = new List<DataTable>(); int qtdLinhasDesejadas = 10; List<string> ListaNomePlan = new ImportarArquivos().ListSheetInExcel(String.Format(@"{0}", nomeArquivoBuscado)); List<string> novaListaPlan = new List<string>(); foreach (string item in ListaNomePlan) { string lllll = item.Replace("$_", "$"); if (novaListaPlan.AsEnumerable().Any(m => m.Contains(lllll)) == false) { novaListaPlan.Add(lllll); } } if (novaListaPlan.Count == 0) { return ""; } if (novaListaPlan.Count == 1) { return novaListaPlan[0]; } foreach (string itemNomePlan in novaListaPlan) { using (DataTable dt = new ImportarArquivos().ImportarXLSXNovo(nomeArquivoBuscado, itemNomePlan, qtdLinhasDesejadas)) { if (dt != null && dt.Rows.Count == 0) { DataTable data = new DataTable(); data.Columns.Add(" -"); data.Columns.Add("A"); data.Columns.Add("B"); data.Columns.Add("C"); data.Columns.Add("D"); data.Columns.Add("E"); data.Columns.Add("F"); data.Columns.Add("G"); data.Columns.Add("H"); data.Columns.Add("I"); data.Columns.Add("J"); data.Columns.Add("K"); data.Columns.Add("L"); data.Columns.Add("M"); data.Columns.Add("N"); data.Columns.Add("O"); data.Columns.Add("P"); data.Columns.Add("Q"); for (int i = 1; i <= qtdLinhasDesejadas; i++) { DataRow row = data.NewRow(); row[" -"] = i; row["A"] = null; row["B"] = ""; row["C"] = ""; row["D"] = ""; row["E"] = ""; row["F"] = ""; row["G"] = ""; row["H"] = ""; row["I"] = ""; row["J"] = ""; row["K"] = ""; row["L"] = ""; row["M"] = ""; row["N"] = ""; row["O"] = ""; row["P"] = ""; row["Q"] = ""; data.Rows.Add(row); } ListaDt.Add(data); } if (dt != null && dt.Rows.Count > 0) { ListaDt.Add(dt); } } } using (FormPlan plan = new FormPlan(ListaDt, novaListaPlan, nomeArquivoBuscado)) { plan.ShowDialog(this); if (plan.cancelado == true) return ""; else return plan.retorno; } } //private string RetornaNomePlanilhaSelecionadoXLSX(string nomeArquivoBuscado) //{ // List<DataTable> ListaDt = new List<DataTable>(); // int qtdLinhasDesejadas = 10; // List<string> ListaNomePlan = new ImportarArquivos().ListSheetInExcel(String.Format(@"{0}", nomeArquivoBuscado)); // foreach (string itemNomePlan in ListaNomePlan) // { // using (DataTable dt = new ImportarArquivos().ImportarXLSXNovo(nomeArquivoBuscado, itemNomePlan, qtdLinhasDesejadas)) // { // if (dt != null && dt.Rows.Count == 0) // { // DataTable data = new DataTable(); // data.Columns.Add(" -"); // data.Columns.Add("A"); // data.Columns.Add("B"); // data.Columns.Add("C"); // data.Columns.Add("D"); // data.Columns.Add("E"); // data.Columns.Add("F"); // data.Columns.Add("G"); // data.Columns.Add("H"); // data.Columns.Add("I"); // data.Columns.Add("J"); // data.Columns.Add("K"); // data.Columns.Add("L"); // data.Columns.Add("M"); // data.Columns.Add("N"); // data.Columns.Add("O"); // data.Columns.Add("P"); // data.Columns.Add("Q"); // for (int i = 1; i <= qtdLinhasDesejadas; i++) // { // DataRow row = data.NewRow(); // row[" -"] = i; // row["A"] = null; // row["B"] = ""; // row["C"] = ""; // row["D"] = ""; // row["E"] = ""; // row["F"] = ""; // row["G"] = ""; // row["H"] = ""; // row["I"] = ""; // row["J"] = ""; // row["K"] = ""; // row["L"] = ""; // row["M"] = ""; // row["N"] = ""; // row["O"] = ""; // row["P"] = ""; // row["Q"] = ""; // data.Rows.Add(row); // } // ListaDt.Add(data); // } // if (dt != null && dt.Rows.Count > 0) // { // ListaDt.Add(dt); // } // } // } // using (FormPlan plan = new FormPlan(ListaDt, ListaNomePlan, nomeArquivoBuscado)) // { // plan.ShowDialog(this); // if (plan.cancelado == true) // return ""; // else // return plan.retorno; // } //} private void CarregaGridView(DataTable dt) { dataGridView1.Rows.Clear(); dataGridView1.Columns.Clear(); dataGridView1.ColumnCount = dt.Columns.Count; dataGridView1.ColumnHeadersVisible = true; // Set the column header style. DataGridViewCellStyle columnHeaderStyle = new DataGridViewCellStyle(); columnHeaderStyle.BackColor = Color.DarkGray; columnHeaderStyle.ForeColor = Color.Black; columnHeaderStyle.Font = new Font("Verdana", 12, FontStyle.Bold); dataGridView1.ColumnHeadersDefaultCellStyle = columnHeaderStyle; int i = 0; foreach (var item in dt.Columns) { dataGridView1.Columns[i].Name = dt.Columns[i].ColumnName; dataGridView1.Columns[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells; dataGridView1.Columns[i].SortMode = DataGridViewColumnSortMode.NotSortable; i++; } CarregaItensCombo(); SetaItensDataSourceComboBox(dt); //SetaItensComboBox(dt); i = 0; foreach (var L in dt.Rows) { int j = 0; int qtdColunas = dt.Columns.Count; string[] itemValor = new string[qtdColunas]; foreach (var C in dt.Columns) { string valor = dt.Rows[i][j].ToString(); itemValor[j] = valor; j++; } this.dataGridView1.Rows.Insert(i + 1, itemValor); dataGridView1.Rows[i + 1].ReadOnly = true; i++; //if (i > 0 && i.VerificaSePar())// muda a cor somente em linhas pares... // dataGridView1.Rows[i].DefaultCellStyle.BackColor = Color.DarkGray; } if (dataGridView1.Rows.Count >= 1) dataGridView1.Rows[1].Frozen = true; } private string[] list; private void SetaItensDataSourceComboBox(DataTable Dt) { DataGridViewRow LinhaCombos = new DataGridViewRow(); for (int i = 0; i < Dt.Columns.Count; i++) { DataGridViewComboBoxCell Cellcombo = new DataGridViewComboBoxCell(); Cellcombo.DataSource = ColunaComboBoxCamposSelecaoGoogle; Cellcombo.Value = ColunaComboBoxCamposSelecaoGoogle.Rows[0][0]; // default value for the ComboBox Cellcombo.ValueMember = "ID"; Cellcombo.DisplayMember = "CamposGooglePortugues"; LinhaCombos.Cells.Add(Cellcombo); } dataGridView1.Rows.Add(LinhaCombos); //dataGridView1.Rows[1].Frozen = true; } private void SetaItensComboBox(DataTable Dt) { DataGridViewRow LinhaCombos = new DataGridViewRow(); for (int i = 0; i < Dt.Columns.Count; i++) { DataGridViewComboBoxCell Cellcombo = new DataGridViewComboBoxCell(); int indice = 0; foreach (string item in CamposGooglePortugues) { Cellcombo.Items.Add(new { Text = item, Value = indice }); indice++; } //Cellcombo.Items = ColunaComboBoxCamposSelecaoGoogle[0]; Cellcombo.Value = 0; // default value for the ComboBox Cellcombo.DisplayMember = "Text"; Cellcombo.ValueMember = "Value"; LinhaCombos.Cells.Add(Cellcombo); } dataGridView1.Rows.Add(LinhaCombos); //dataGridView1.Rows[1].Frozen = true; } private void CarregaItensCombo() { ColunaComboBoxCamposSelecaoGoogle = new DataTable(); ColunaComboBoxCamposSelecaoGoogle.Columns.Add("ID"); ColunaComboBoxCamposSelecaoGoogle.Columns.Add("CamposGooglePortugues"); //ColunaComboBoxCamposSelecaoGoogle.Columns.Add("CamposGoogleIngles"); for (int i = 0; i < CamposGooglePortugues.Count; i++) { DataRow linha = ColunaComboBoxCamposSelecaoGoogle.NewRow(); linha["ID"] = i; linha["CamposGooglePortugues"] = CamposGooglePortugues[i]; //linha["CamposGoogleIngles"] = CamposGooglePortugues[i]; ColunaComboBoxCamposSelecaoGoogle.Rows.Add(linha); } } private StringBuilder sbFinalTXT = new StringBuilder(); StringBuilder sbContato = new StringBuilder(); Dictionary<int, string> dicionarioSequenciaGrid = new Dictionary<int, string>(); public static int valorIndiceLinhaGrid = 0; void Processando() { for (int IndiceLinhaGrid = 0; IndiceLinhaGrid < dataGridView1.Rows.Count; IndiceLinhaGrid++) //percorrendo linhas.... { if (IndiceLinhaGrid == 0) continue; gruposLinhaAtual.Clear(); // = new StringBuilder(); grupoLinhaJaProcessado = false; int qtdEncontrado = 0; sbContato.AppendLine("BEGIN:VCARD");//linha 1 sbContato.AppendLine("VERSION:3.0");//linha 2 #region Nome completo qtdEncontrado = RetornaQtdColunasParaOCampoIndicado(dicionarioSequenciaGrid, "Nome completo"); if (qtdEncontrado == 1) { string pegaCampoNomeCompleto = RetornaValorCelulaPelaColuna(IndiceLinhaGrid, dicionarioSequenciaGrid, "Nome completo"); //verifica se contém coluna selecionada para tratamento if (dicionarioSequenciaGrid.AsEnumerable().Any(pair => pair.Value == "Tratamento")) { string pegaCampoTratamento = RetornaValorCelulaPelaColuna(IndiceLinhaGrid, dicionarioSequenciaGrid, "Tratamento"); string linha = string.Format("N:;{0};;{1};", pegaCampoNomeCompleto, pegaCampoTratamento); sbContato.AppendLine(linha); linha = string.Format("FN:{0} {1}", pegaCampoTratamento, pegaCampoNomeCompleto); sbContato.AppendLine(linha); string temp = sbContato.ToString(); } else { string linha = string.Format("N:;{0};;;", pegaCampoNomeCompleto); sbContato.AppendLine(linha); linha = string.Format("FN:{0}", pegaCampoNomeCompleto); sbContato.AppendLine(linha); string temp = sbContato.ToString(); } } #endregion #region Apelido qtdEncontrado = RetornaQtdColunasParaOCampoIndicado(dicionarioSequenciaGrid, "Apelido"); if (qtdEncontrado == 1) { string pegaCampo = RetornaValorCelulaPelaColuna(IndiceLinhaGrid, dicionarioSequenciaGrid, "Apelido"); if (!string.IsNullOrEmpty(pegaCampo)) { string linha = string.Format("NICKNAME:{0}", pegaCampo); sbContato.AppendLine(linha); string temp = sbContato.ToString(); } } #endregion #region Grupos qtdEncontrado = RetornaQtdColunasParaOCampoIndicado(dicionarioSequenciaGrid, "Grupos"); if (qtdEncontrado == 1) { string pegaCampo = RetornaValorCelulaPelaColuna(IndiceLinhaGrid, dicionarioSequenciaGrid, "Grupos"); if (!string.IsNullOrEmpty(pegaCampo)) { string linha = string.Format("CATEGORIES:{0}", pegaCampo); sbContato.AppendLine(linha); string temp = sbContato.ToString(); } } if (qtdEncontrado > 1) { if (grupoLinhaJaProcessado == false) { gruposLinhaAtual.Clear(); string valorCelulaAtual = ""; var itensIguaisGrid = dicionarioSequenciaGrid.AsEnumerable().Where(pair => pair.Value == "Grupos"); foreach (KeyValuePair<int, string> item in itensIguaisGrid) { var key = item.Key; var value = item.Value; valorCelulaAtual = dataGridView1.Rows[IndiceLinhaGrid].Cells[key].FormattedValue.ToString(); if (string.IsNullOrEmpty(valorCelulaAtual)) continue; if (gruposLinhaAtual.ToString() == "") gruposLinhaAtual.AppendFormat(string.Format("{0}", valorCelulaAtual)); else { string novoValor = string.Format("{0},{1}", gruposLinhaAtual, valorCelulaAtual); gruposLinhaAtual.Clear(); gruposLinhaAtual.AppendFormat(novoValor); } } valorCelulaAtual = string.Format("{0},myContacts", gruposLinhaAtual.ToString()); if (!string.IsNullOrEmpty(valorCelulaAtual)) { string linha = string.Format("CATEGORIES:{0}", valorCelulaAtual); sbContato.AppendLine(linha); string temp = sbContato.ToString(); } grupoLinhaJaProcessado = true; } } #endregion #region Data nascimento qtdEncontrado = RetornaQtdColunasParaOCampoIndicado(dicionarioSequenciaGrid, "Data nascimento"); if (qtdEncontrado == 1) { string pegaCampo = RetornaValorCelulaPelaColuna(IndiceLinhaGrid, dicionarioSequenciaGrid, "Data nascimento"); DateTime objDate; if (DateTime.TryParse(pegaCampo, out objDate)) { //Se é uma data válida string linha = string.Format("BDAY:{0}", pegaCampo.ToDateTime().Date.ToString("dd/MM/yyyy")); sbContato.AppendLine(linha); string temp = sbContato.ToString(); } } #endregion #region Sexo qtdEncontrado = RetornaQtdColunasParaOCampoIndicado(dicionarioSequenciaGrid, "Sexo"); if (qtdEncontrado == 1) { string pegaCampo = RetornaValorCelulaPelaColuna(IndiceLinhaGrid, dicionarioSequenciaGrid, "Sexo"); if (pegaCampo.ToUpper() == "M" || pegaCampo.ToUpper() == "MASCULINO") { string linha = string.Format("GENDER:{0}", "M"); sbContato.AppendLine(linha); } if (pegaCampo.ToUpper() == "F" || pegaCampo.ToUpper() == "FEMININO") { string linha = string.Format("GENDER:{0}", "F"); sbContato.AppendLine(linha); } string temp = sbContato.ToString(); } #endregion #region Empresa qtdEncontrado = RetornaQtdColunasParaOCampoIndicado(dicionarioSequenciaGrid, "Empresa"); if (qtdEncontrado == 1) { string pegaCampo = RetornaValorCelulaPelaColuna(IndiceLinhaGrid, dicionarioSequenciaGrid, "Empresa"); if (!string.IsNullOrEmpty(pegaCampo)) { string linha = string.Format("ORG:{0};", pegaCampo); sbContato.AppendLine(linha); string temp = sbContato.ToString(); } } #endregion #region Cargo/Funcão qtdEncontrado = RetornaQtdColunasParaOCampoIndicado(dicionarioSequenciaGrid, "Cargo/Funcão"); if (qtdEncontrado == 1) { string pegaCampo = RetornaValorCelulaPelaColuna(IndiceLinhaGrid, dicionarioSequenciaGrid, "Cargo/Funcão"); if (!string.IsNullOrEmpty(pegaCampo)) { string linha = string.Format("TITLE:{0}", pegaCampo); sbContato.AppendLine(linha); string temp = sbContato.ToString(); } } #endregion #region Nota/Histórico qtdEncontrado = RetornaQtdColunasParaOCampoIndicado(dicionarioSequenciaGrid, "Nota/Histórico"); if (qtdEncontrado == 1) { string pegaCampo = RetornaValorCelulaPelaColuna(IndiceLinhaGrid, dicionarioSequenciaGrid, "Nota/Histórico"); if (!string.IsNullOrEmpty(pegaCampo)) { string linha = string.Format("NOTE:{0}", pegaCampo); sbContato.AppendLine(linha); string temp = sbContato.ToString(); } } #endregion #region Email Pessoal qtdEncontrado = RetornaQtdColunasParaOCampoIndicado(dicionarioSequenciaGrid, "Email Pessoal"); if (qtdEncontrado == 1) { string pegaCampo = RetornaValorCelulaPelaColuna(IndiceLinhaGrid, dicionarioSequenciaGrid, "Email Pessoal"); if (!string.IsNullOrEmpty(pegaCampo)) { string linha = string.Format("EMAIL;TYPE=INTERNET;TYPE=Pessoal;type=pref:{0}", pegaCampo); sbContato.AppendLine(linha); sbContato.AppendLine(linha); string temp = sbContato.ToString(); } } #endregion #region Email Comercial qtdEncontrado = RetornaQtdColunasParaOCampoIndicado(dicionarioSequenciaGrid, "Email Comercial"); if (qtdEncontrado == 1) { string pegaCampo = RetornaValorCelulaPelaColuna(IndiceLinhaGrid, dicionarioSequenciaGrid, "Email Comercial"); if (!string.IsNullOrEmpty(pegaCampo)) { string linha = string.Format("EMAIL;TYPE=INTERNET;TYPE=WORK:{0}", pegaCampo); sbContato.AppendLine(linha); string temp = sbContato.ToString(); } } #endregion #region Telefone Principal qtdEncontrado = RetornaQtdColunasParaOCampoIndicado(dicionarioSequenciaGrid, "Telefone Principal"); if (qtdEncontrado == 1) { string pegaCampo = RetornaValorCelulaPelaColuna(IndiceLinhaGrid, dicionarioSequenciaGrid, "Telefone Principal"); if (!string.IsNullOrEmpty(pegaCampo)) { string linha = string.Format("TEL;type=Telefone1;type=pref:{0}", pegaCampo); sbContato.AppendLine(linha); string temp = sbContato.ToString(); } } #endregion #region Telefone 2 qtdEncontrado = RetornaQtdColunasParaOCampoIndicado(dicionarioSequenciaGrid, "Telefone 2"); if (qtdEncontrado == 1) { string pegaCampo = RetornaValorCelulaPelaColuna(IndiceLinhaGrid, dicionarioSequenciaGrid, "Telefone 2"); if (!string.IsNullOrEmpty(pegaCampo)) { string linha = string.Format("TEL;type=Telefone2:{0}", pegaCampo); sbContato.AppendLine(linha); string temp = sbContato.ToString(); } } #endregion #region Telefone 3 qtdEncontrado = RetornaQtdColunasParaOCampoIndicado(dicionarioSequenciaGrid, "Telefone 3"); if (qtdEncontrado == 1) { string pegaCampo = RetornaValorCelulaPelaColuna(IndiceLinhaGrid, dicionarioSequenciaGrid, "Telefone 3"); if (!string.IsNullOrEmpty(pegaCampo)) { string linha = string.Format("TEL;type=Telefone3:{0}", pegaCampo); sbContato.AppendLine(linha); string temp = sbContato.ToString(); } } #endregion #region Telefone 4 qtdEncontrado = RetornaQtdColunasParaOCampoIndicado(dicionarioSequenciaGrid, "Telefone 4"); if (qtdEncontrado == 1) { string pegaCampo = RetornaValorCelulaPelaColuna(IndiceLinhaGrid, dicionarioSequenciaGrid, "Telefone 4"); if (!string.IsNullOrEmpty(pegaCampo)) { string linha = string.Format("TEL;type=Telefone4:{0}", pegaCampo); sbContato.AppendLine(linha); string temp = sbContato.ToString(); } } #endregion #region Telefone 5 qtdEncontrado = RetornaQtdColunasParaOCampoIndicado(dicionarioSequenciaGrid, "Telefone 5"); if (qtdEncontrado == 1) { string pegaCampo = RetornaValorCelulaPelaColuna(IndiceLinhaGrid, dicionarioSequenciaGrid, "Telefone 5"); if (!string.IsNullOrEmpty(pegaCampo)) { string linha = string.Format("TEL;type=Telefone5:{0}", pegaCampo); sbContato.AppendLine(linha); string temp = sbContato.ToString(); } } #endregion #region Telefone 6 qtdEncontrado = RetornaQtdColunasParaOCampoIndicado(dicionarioSequenciaGrid, "Telefone 6"); if (qtdEncontrado == 1) { string pegaCampo = RetornaValorCelulaPelaColuna(IndiceLinhaGrid, dicionarioSequenciaGrid, "Telefone 6"); if (!string.IsNullOrEmpty(pegaCampo)) { string linha = string.Format("TEL;type=Telefone6:{0}", pegaCampo); sbContato.AppendLine(linha); string temp = sbContato.ToString(); } } #endregion int i = 1; #region Trata Endereço Res. //qtdEncontrado = RetornaQtdColunasParaOCampoIndicado(dicionarioSequenciaGrid, "Endereço Res."); //if (qtdEncontrado == 1) //{ // string pegaCampoEnderecoRes = RetornaValorCelulaPelaColuna(IndiceLinhaGrid, dicionarioSequenciaGrid, "Endereço Res."); // //string pegaCampoNumeroRes = RetornaValorCelulaPelaColuna(IndiceLinhaGrid, dicionarioSequenciaGrid, "Endereço Res."); // string pegaCampoBairroRes = RetornaValorCelulaPelaColuna(IndiceLinhaGrid, dicionarioSequenciaGrid, "Bairro Res."); // string pegaCampoCidadeRes = RetornaValorCelulaPelaColuna(IndiceLinhaGrid, dicionarioSequenciaGrid, "Cidade Res."); // string pegaCampoEstadoRes = RetornaValorCelulaPelaColuna(IndiceLinhaGrid, dicionarioSequenciaGrid, "Estado Res.").TrocaEstadoPorSegla(); // string pegaCampoCEPRes = RetornaValorCelulaPelaColuna(IndiceLinhaGrid, dicionarioSequenciaGrid, "CEP Res."); // string pegaCampoPaisRes = RetornaValorCelulaPelaColuna(IndiceLinhaGrid, dicionarioSequenciaGrid, "País Res."); // if (pegaCampoPaisRes.ToUpper() == "Brasil".ToUpper()) pegaCampoPaisRes = "BRAZIL"; // string linha = string.Format("item{6}.ADR;type=HOME;type=pref:;;{0} {1};{2};{3};{4};{5}", // pegaCampoEnderecoRes == "" ? "-" : pegaCampoEnderecoRes, // pegaCampoBairroRes == "" ? "-" : pegaCampoBairroRes, // pegaCampoCidadeRes == "" ? "-" : pegaCampoCidadeRes, // pegaCampoEstadoRes == "" ? "-" : pegaCampoEstadoRes, // pegaCampoCEPRes == "" ? "-" : pegaCampoCEPRes, // pegaCampoPaisRes == "" ? "-" : pegaCampoPaisRes, // i); // sbContato.AppendLine(linha); // sbContato.AppendLine(string.Format("item{0}.X-ABADR:BR", i)); // string temp = sbContato.ToString(); // i++; //} qtdEncontrado = RetornaQtdColunasParaOCampoIndicado(dicionarioSequenciaGrid, "Endereço Res."); if (qtdEncontrado == 1) { string pegaCampoEnderecoRes = RetornaValorCelulaPelaColuna(IndiceLinhaGrid, dicionarioSequenciaGrid, "Endereço Res."); string pegaCampoNumeroRes = RetornaValorCelulaPelaColuna(IndiceLinhaGrid, dicionarioSequenciaGrid, "Endereço Res. Núm."); string pegaCampoBairroRes = RetornaValorCelulaPelaColuna(IndiceLinhaGrid, dicionarioSequenciaGrid, "Bairro Res."); string pegaCampoCidadeRes = RetornaValorCelulaPelaColuna(IndiceLinhaGrid, dicionarioSequenciaGrid, "Cidade Res."); //string pegaCampoEstadoRes = RetornaValorCelulaPelaColuna(IndiceLinhaGrid, dicionarioSequenciaGrid, "Estado Res.").TrocaEstadoPorSegla(); string pegaCampoEstadoRes = RetornaValorCelulaPelaColuna(IndiceLinhaGrid, dicionarioSequenciaGrid, "Estado Res."); string pegaCampoCEPRes = RetornaValorCelulaPelaColuna(IndiceLinhaGrid, dicionarioSequenciaGrid, "CEP Res."); string pegaCampoPaisRes = RetornaValorCelulaPelaColuna(IndiceLinhaGrid, dicionarioSequenciaGrid, "País Res."); if (pegaCampoPaisRes.ToUpper() == "".ToUpper() || pegaCampoPaisRes.ToUpper() == "Brasil".ToUpper()) pegaCampoPaisRes = "BRAZIL"; //item2.ADR:NUMERO0;BAIRRO1;RUA2;CIDADE3;Tocantins4;CEP5;Brazil6 //item2.X - ABLabel: string linha = string.Format("item{7}.ADR:{0};{1};{2};{3};{4};{5};{6}", pegaCampoNumeroRes == "" ? "" : pegaCampoNumeroRes, pegaCampoBairroRes == "" ? "" : pegaCampoBairroRes, pegaCampoEnderecoRes == "" ? "" : pegaCampoEnderecoRes, pegaCampoCidadeRes == "" ? "" : pegaCampoCidadeRes, pegaCampoEstadoRes == "" ? "" : pegaCampoEstadoRes, pegaCampoCEPRes == "" ? "" : pegaCampoCEPRes, pegaCampoPaisRes == "" ? "" : pegaCampoPaisRes, i); sbContato.AppendLine(linha); sbContato.AppendLine(string.Format("item{0}.X-ABLabel", i)); string temp = sbContato.ToString(); i++; } #endregion #region Trata Endereço Com. qtdEncontrado = RetornaQtdColunasParaOCampoIndicado(dicionarioSequenciaGrid, "Endereço Res."); if (qtdEncontrado == 1) { string pegaCampoEnderecoCom = RetornaValorCelulaPelaColuna(IndiceLinhaGrid, dicionarioSequenciaGrid, "Endereço Com."); string pegaCampoNumeroCom = RetornaValorCelulaPelaColuna(IndiceLinhaGrid, dicionarioSequenciaGrid, "Endereço Com. Núm."); string pegaCampoBairroCom = RetornaValorCelulaPelaColuna(IndiceLinhaGrid, dicionarioSequenciaGrid, "Bairro Com."); string pegaCampoCidadeCom = RetornaValorCelulaPelaColuna(IndiceLinhaGrid, dicionarioSequenciaGrid, "Cidade Com."); string pegaCampoEstadoCom = RetornaValorCelulaPelaColuna(IndiceLinhaGrid, dicionarioSequenciaGrid, "Estado Com.").TrocaEstadoPorSegla(); string pegaCampoCEPCom = RetornaValorCelulaPelaColuna(IndiceLinhaGrid, dicionarioSequenciaGrid, "CEP Com."); string pegaCampoPaisCom = RetornaValorCelulaPelaColuna(IndiceLinhaGrid, dicionarioSequenciaGrid, "País Com."); if (pegaCampoPaisCom.ToUpper() == "Brasil".ToUpper()) pegaCampoPaisCom = "BRAZIL"; string linha = string.Format("item{7}.ADR;type=WORK:{0};{1};{2};{3};{4};{5};{6}", pegaCampoNumeroCom == "" ? "" : pegaCampoNumeroCom, pegaCampoBairroCom == "" ? "" : pegaCampoBairroCom, pegaCampoEnderecoCom == "" ? "" : pegaCampoEnderecoCom, pegaCampoCidadeCom == "" ? "" : pegaCampoCidadeCom, pegaCampoEstadoCom == "" ? "" : pegaCampoEstadoCom, pegaCampoCEPCom == "" ? "" : pegaCampoCEPCom, pegaCampoPaisCom == "" ? "" : pegaCampoPaisCom, i); sbContato.AppendLine(linha); sbContato.AppendLine(string.Format("item{0}.X-ABLabel", i)); string temp = sbContato.ToString(); i++; } #endregion #region Site Pessoal qtdEncontrado = RetornaQtdColunasParaOCampoIndicado(dicionarioSequenciaGrid, "Site Pessoal"); if (qtdEncontrado == 1) { string pegaCampo = RetornaValorCelulaPelaColuna(IndiceLinhaGrid, dicionarioSequenciaGrid, "Site Pessoal"); if (!string.IsNullOrEmpty(pegaCampo)) { string linha = string.Format("item{0}.URL;type=pref:{1}", i, pegaCampo); sbContato.AppendLine(linha); sbContato.AppendLine(string.Format("item{0}.X-ABLabel:_$!<HomePage>!$_", i)); string temp = sbContato.ToString(); i++; } } #endregion #region Site Comercial qtdEncontrado = RetornaQtdColunasParaOCampoIndicado(dicionarioSequenciaGrid, "Site Comercial"); if (qtdEncontrado == 1) { string pegaCampo = RetornaValorCelulaPelaColuna(IndiceLinhaGrid, dicionarioSequenciaGrid, "Site Comercial"); if (!string.IsNullOrEmpty(pegaCampo)) { string linha = string.Format("item{0}.URL:{1}", i, pegaCampo); sbContato.AppendLine(linha); sbContato.AppendLine(string.Format("item{0}.X-ABLabel:Comercial", i)); string temp = sbContato.ToString(); i++; } } #endregion #region Data aniv. Cônjuge qtdEncontrado = RetornaQtdColunasParaOCampoIndicado(dicionarioSequenciaGrid, "Data aniv. Cônjuge"); if (qtdEncontrado == 1) { string pegaCampo = RetornaValorCelulaPelaColuna(IndiceLinhaGrid, dicionarioSequenciaGrid, "Data aniv. Cônjuge"); DateTime objDate; if (DateTime.TryParse(pegaCampo, out objDate)) { //Se é uma data válida string linha = string.Format("item{1}.X-ABDATE:{0}", pegaCampo.ToDateTime().Date.ToString("yyyyMMdd"), i); sbContato.AppendLine(linha); sbContato.AppendLine(string.Format("item{0}.X-ABLabel:Aniversário da Esposa", i)); string temp = sbContato.ToString(); i++; } } #endregion #region Nome Cônjuge qtdEncontrado = RetornaQtdColunasParaOCampoIndicado(dicionarioSequenciaGrid, "Nome Cônjuge"); if (qtdEncontrado == 1) { string pegaCampo = RetornaValorCelulaPelaColuna(IndiceLinhaGrid, dicionarioSequenciaGrid, "Nome Cônjuge"); if (!string.IsNullOrEmpty(pegaCampo)) { string linha = string.Format("item{1}.X-ABRELATEDNAMES;type=pref:{0}", pegaCampo, i); sbContato.AppendLine(linha); sbContato.AppendLine(string.Format("item{0}.X-ABLabel:_$!<Spouse>!$_", i)); string temp = sbContato.ToString(); i++; } } #endregion #region Nome do pai qtdEncontrado = RetornaQtdColunasParaOCampoIndicado(dicionarioSequenciaGrid, "Nome do pai"); if (qtdEncontrado == 1) { string pegaCampo = RetornaValorCelulaPelaColuna(IndiceLinhaGrid, dicionarioSequenciaGrid, "Nome do pai"); if (!string.IsNullOrEmpty(pegaCampo)) { string linha = string.Format("item{1}.X-ABRELATEDNAMES:{0}", pegaCampo, i); sbContato.AppendLine(linha); sbContato.AppendLine(string.Format("item{0}.X-ABLabel:_$!<Father>!$_", i)); string temp = sbContato.ToString(); i++; } } #endregion #region Nome da mãe qtdEncontrado = RetornaQtdColunasParaOCampoIndicado(dicionarioSequenciaGrid, "Nome da mãe"); if (qtdEncontrado == 1) { string pegaCampo = RetornaValorCelulaPelaColuna(IndiceLinhaGrid, dicionarioSequenciaGrid, "Nome da mãe"); if (!string.IsNullOrEmpty(pegaCampo)) { string linha = string.Format("item{1}.X-ABRELATEDNAMES:{0}", pegaCampo, i); sbContato.AppendLine(linha); sbContato.AppendLine(string.Format("item{0}.X-ABLabel:_$!<Mother>!$_", i)); string temp = sbContato.ToString(); i++; } } #endregion sbContato.AppendLine("END:VCARD"); } string tempo = sbContato.ToString(); sbFinalTXT.AppendLine(sbContato.ToString()); string final = sbFinalTXT.ToString();//teste } private void button1_Click(object sender, EventArgs e) { valorIndiceLinhaGrid = 0; sbContato = new StringBuilder(); sbFinalTXT = new StringBuilder(); //int: indice da coluna Grid / string: Nome Combo Selecionado dicionarioSequenciaGrid = new Dictionary<int, string>(); for (int indice = 0; indice < dataGridView1.Columns.Count; indice++) { string valorCombo = dataGridView1.Rows[0].Cells[indice].FormattedValue.ToString(); if (dataGridView1.Rows[0].Cells[indice].Value.ToString() == "0") continue; dicionarioSequenciaGrid.Add(indice, valorCombo); } if (dataGridView1.Rows.Count == 0) { Mensagens.Informa("Nenhuma linha na seleção atual.\nBusque um fonte de dados e tente novamente."); return; } if (dicionarioSequenciaGrid.Count == 0) { Mensagens.Informa("Nenhuma coluna foi modificada."); return; } using (FormWaiting frm = new FormWaiting(Processando)) { frm.ShowDialog(this); } //----------------------------------------------------- //define o titulo saveFileDialog1.Title = "Salvar Arquivo Texto"; //Define as extensões permitidas //saveFileDialog1.Filter = "Arquivo vCard|.vcf"; saveFileDialog1.Filter = "Arquivo vCard (*.vcf)|*.vcf"; //define o indice do filtro saveFileDialog1.FilterIndex = 0; //Atribui um valor vazio ao nome do arquivo saveFileDialog1.FileName = "ContatosExportados_" + DateTime.Now.ToString("ddMMyyyy_HHmmss"); //Define a extensão padrão como .txt saveFileDialog1.DefaultExt = ".vcf"; //define o diretório padrão //saveFileDialog1.InitialDirectory = @"c:\dados"; //restaura o diretorio atual antes de fechar a janela saveFileDialog1.RestoreDirectory = true; //Abre a caixa de dialogo e determina qual botão foi pressionado DialogResult resultado = saveFileDialog1.ShowDialog(); //Se o ousuário pressionar o botão Salvar if (resultado == DialogResult.OK) { //cria um stream usando o nome do arquivo System.IO.FileStream fs = new System.IO.FileStream(saveFileDialog1.FileName, System.IO.FileMode.Create); //cria um escrito que irá escrever no stream System.IO.StreamWriter writer = new System.IO.StreamWriter(fs); //escreve o conteúdo da caixa de texto no stream writer.Write(sbFinalTXT.ToString()); //fecha o escrito e o stream writer.Close(); //string caminhoArquivo = @"C:\Projetos\KEMUEL\ContatosExportados.vcf"; //caminho completo //System.IO.File.WriteAllText(saveFileDialog1.FileName, sbFinalTXT.ToString()); Mensagens.Informa("Exportação concluída com sucesso!"); } else { //exibe mensagem informando que a operação foi cancelada //MessageBox.Show("Operação cancelada"); return; } } private static int RetornaQtdColunasParaOCampoIndicado(Dictionary<int, string> dicionarioSequenciaGrid, string nomeCampo) { int qtdEncontrado = dicionarioSequenciaGrid.AsEnumerable().Count(pair => pair.Value == nomeCampo).ToInt(); return qtdEncontrado; } private string RetornaValorCelulaPelaColuna(int IndiceLinhaGrid, Dictionary<int, string> dicionarioSequenciaGrid, string CampoComboBox) { string pegaCampo = ""; if (dicionarioSequenciaGrid.AsEnumerable().Any(pair => pair.Value == CampoComboBox)) { var indiceCampo = dicionarioSequenciaGrid.AsEnumerable().First(pair => pair.Value == CampoComboBox);//pega qual coluna tem o campo pegaCampo = dataGridView1.Rows[IndiceLinhaGrid].Cells[indiceCampo.Key].FormattedValue.ToString(); } return pegaCampo; } private string TrataCondicoesEspecificas(string valorCelulaAtual, string value) { string retorno = ""; switch (value) { case "Nome completo": retorno = string.Format("N:;{0};;[Tratamento];", valorCelulaAtual); break; case "Tratamento": break; case "Apelido": break; case "Data nascimento": break; case "Sexo": break; case "Telefone Principal": break; case "Telefone 2": break; case "Telefone 3": break; case "Telefone 4": break; case "Telefone 5": break; case "telefone 6": break; case "Email Pessoal": break; case "Email Comercial": break; case "Endereço Res.": break; case "Bairro Res.": break; case "Cidade Res.": break; case "Estado Res.": break; case "CEP Res.": break; case "País Res.": break; case "Endereço Com.": break; case "Bairro Com.": break; case "Cidade Com.": break; case "Estado Com.": break; case "CEP Com.": break; case "País Com.": break; case "Empresa": break; case "Cargo/Funcão": break; case "Nota/Histórico": break; case "Site Pessoal": break; case "Site Comercial": break; case "Nome Cônjuge": break; case "Data aniv. Cônjuge": break; case "Nome do pai": break; case "Nome da mãe": break; case "Grupos": break; default: retorno = valorCelulaAtual; break; } return retorno; } } }
47.333333
704
0.497829
[ "MIT" ]
MarquesFonseca/ExportadorContatosGoogle
ExportadorContatosGoogle/FormGerenciadorContatosVCardV3.cs
56,767
C#
using System; using System.Collections.Generic; #nullable disable namespace DbFirst.Models { public partial class CustomerAndSuppliersByCity { public string City { get; set; } public string CompanyName { get; set; } public string ContactName { get; set; } public string Relationship { get; set; } } }
22.6875
52
0.636364
[ "MIT" ]
firatalcin/CSharp-.NetCore-Works
FullStackDotNetCore-Lessons/DbFirst/DbFirst/Models/CustomerAndSuppliersByCity.cs
365
C#
using System.Linq; using System.Xml.Linq; using AD.Xml; using JetBrains.Annotations; namespace AD.OpenXml.Elements { /// <summary> /// Extension methods to removes &lt;rPr [...] /&gt; nodes from &lt;pPr [...] /&gt; nodes. /// </summary> [PublicAPI] public static class RemoveRunPropertiesFromParagraphPropertiesExtensions { private static readonly XNamespace W = XNamespaces.OpenXmlWordprocessingmlMain; /// <summary> /// Removes &lt;rPr [...] /&gt; nodes from &lt;pPr [...] /&gt; nodes. /// This method works on the existing <see cref="XElement"/> and returns a reference to it for a fluent syntax. /// </summary> /// <param name="element">The element to search for descendants.</param> /// <returns>A reference to the existing <see cref="XElement"/>. This is returned for use with fluent syntax calls.</returns> /// <exception cref="System.ArgumentException"/> /// <exception cref="System.ArgumentNullException"/> public static XElement RemoveRunPropertiesFromParagraphProperties(this XElement element) { element.Descendants(W + "rPr") .Where(x => x.Parent?.Name == W + "pPr") .Remove(); return element; } } }
39.424242
133
0.619523
[ "MIT" ]
meryemdemirkaya/AD.OpenXml
src/AD.OpenXml/Elements/RemoveRunPropertiesFromParagraphProperties.cs
1,303
C#
// Decompiled with JetBrains decompiler // Type: MoneyWadScript // Assembly: Assembly-CSharp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // MVID: 5F8D6662-C74B-4D30-A4EA-D74F7A9A95B9 // Assembly location: C:\YandereSimulator\YandereSimulator_Data\Managed\Assembly-CSharp.dll using UnityEngine; public class MoneyWadScript : MonoBehaviour { public PromptScript Prompt; private void Update() { if ((double) this.Prompt.Circle[0].fillAmount != 0.0) return; this.Prompt.Yandere.Inventory.Money += 20f; this.Prompt.Yandere.Inventory.UpdateMoney(); if ((double) this.Prompt.Yandere.Inventory.Money > 1000.0 && !GameGlobals.Debug) PlayerPrefs.SetInt("RichGirl", 1); Object.Destroy((Object) this.gameObject); } }
31.666667
91
0.734211
[ "Unlicense" ]
JaydenB14/YandereSimulatorDecompiled
Assembly-CSharp/MoneyWadScript.cs
762
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Base.IO { public interface ITextReadable { TextReader OpenTextReader(); } }
16.066667
36
0.726141
[ "MIT" ]
dotnet-toolset/Base
Base.IO/ITextReadable.cs
243
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Web; using LibrarySystem.Services.Common.Contracts; using Microsoft.AspNet.Identity; namespace LibrarySystem.Services.Common { public class IdentityService : IIdentityService { private readonly HttpContextBase httpContext; public IdentityService(HttpContextBase httpContext) { this.httpContext = httpContext; } public Guid GetUserId() { return Guid.Parse(this.httpContext.User.Identity.GetUserId()); } public string GetUsername() { return this.httpContext.User.Identity.GetUserName(); } } }
23.53125
74
0.673307
[ "MIT" ]
ArnaudovSt/LibrarySystem
LibrarySystem/LibrarySystem.Services/Common/IdentityService.cs
755
C#
using PaZword.Api; using PaZword.Api.Security; using PaZword.Api.Settings; using PaZword.Core; using PaZword.Core.Threading; using PaZword.Core.UI; using PaZword.Localization; using System; using System.Composition; using System.Text.RegularExpressions; using Windows.System; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; namespace PaZword.ViewModels.Dialog { /// <summary> /// Interaction logic for <see cref="SetupTwoFactorAuthenticationDialog"/> /// </summary> [Export(typeof(SetupTwoFactorAuthenticationDialogViewModel))] public sealed class SetupTwoFactorAuthenticationDialogViewModel : ViewModelBase { private const string SaveEvent = "SetupTwoFactorAuthentication.Save.Command"; private const string EmailAddressPasteEvent = "SetupTwoFactorAuthentication.EmailAddress.Paste"; private const string TextBoxKeyDownEvent = "SetupTwoFactorAuthentication.TextBox.KeyDown"; private readonly ILogger _logger; private readonly ISettingsProvider _settingsProvider; private readonly ITwoFactorAuthProvider _twoFactorAuthProvider; private readonly DispatcherTimer _timer; private readonly Regex _emailRegex = new Regex(@"\A(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)\Z", RegexOptions.IgnoreCase | RegexOptions.Compiled); private bool _dataValidated; private string _verificationCode; private string _emailAddress; private string _confirmEmailAddress; private ImageSource _qrCode; /// <summary> /// Gets the texts for this view. /// </summary> internal SetupTwoFactorAuthenticationStrings Strings => LanguageManager.Instance.SetupTwoFactorAuthentication; /// <summary> /// Gets the size of the QRCode, in pixels. /// </summary> internal int QRCodeSize => 150; /// <summary> /// Gets the QRCode to display. /// </summary> internal ImageSource QRCode { get => _qrCode; private set { _qrCode = value; RaisePropertyChanged(); } } /// <summary> /// Gets a value that definew whether the user data are valid. /// </summary> internal bool DataValidated { get => _dataValidated; private set { _dataValidated = value; RaisePropertyChanged(); } } /// <summary> /// Gets or sets the verification code. /// </summary> internal string VerificationCode { get => _verificationCode; set { _verificationCode = value; RaisePropertyChanged(); } } /// <summary> /// Gets or sets the email address. /// </summary> internal string EmailAddress { get => _emailAddress; set { _emailAddress = value; RaisePropertyChanged(); } } /// <summary> /// Gets or sets the email address confirmation. /// </summary> internal string ConfirmEmailAddress { get => _confirmEmailAddress; set { _confirmEmailAddress = value; RaisePropertyChanged(); } } /// <summary> /// Raised when the dialog should close. /// </summary> internal event EventHandler CloseDialog; [ImportingConstructor] public SetupTwoFactorAuthenticationDialogViewModel( ILogger logger, ISettingsProvider settingsProvider, ITwoFactorAuthProvider twoFactorAuthProvider) { _logger = Arguments.NotNull(logger, nameof(logger)); _settingsProvider = Arguments.NotNull(settingsProvider, nameof(settingsProvider)); _twoFactorAuthProvider = Arguments.NotNull(twoFactorAuthProvider, nameof(twoFactorAuthProvider)); PrimaryButtonClickCommand = new ActionCommand<object>(_logger, SaveEvent, ExecutePrimaryButtonClickCommand); EmailAddressBoxPasteCommand = new ActionCommand<TextControlPasteEventArgs>(_logger, EmailAddressPasteEvent, ExecuteEmailAddressBoxPasteCommand); TextBoxKeyDownCommand = new ActionCommand<KeyRoutedEventArgs>(_logger, TextBoxKeyDownEvent, ExecuteTextBoxKeyDownCommand); _timer = new DispatcherTimer(); _timer.Tick += Timer_Tick; _timer.Interval = TimeSpan.FromMilliseconds(100); _timer.Start(); } #region PrimaryButtonClickCommand internal ActionCommand<object> PrimaryButtonClickCommand { get; } private void ExecutePrimaryButtonClickCommand(object parameter) { Save(); } #endregion #region EmailAddressBoxPasteCommand internal ActionCommand<TextControlPasteEventArgs> EmailAddressBoxPasteCommand { get; } private void ExecuteEmailAddressBoxPasteCommand(TextControlPasteEventArgs parameter) { parameter.Handled = true; // Prevent the user from pasting in the Email/Confirm Email address. } #endregion #region TextBoxKeyDownCommand internal ActionCommand<KeyRoutedEventArgs> TextBoxKeyDownCommand { get; } private void ExecuteTextBoxKeyDownCommand(KeyRoutedEventArgs parameter) { if (parameter.Key == VirtualKey.Enter && DataValidated) { Save(); CloseDialog?.Invoke(this, EventArgs.Empty); } } #endregion internal void Closed() { _timer.Stop(); } private void Timer_Tick(object sender, object e) { TaskHelper.ThrowIfNotOnUIThread(); bool isValidEmail = !string.IsNullOrWhiteSpace(EmailAddress) && !string.IsNullOrWhiteSpace(ConfirmEmailAddress) && string.Equals(EmailAddress.Trim(), ConfirmEmailAddress.Trim(), StringComparison.Ordinal) && _emailRegex.IsMatch(EmailAddress.Trim()); DataValidated = isValidEmail && _twoFactorAuthProvider.ValidatePin(VerificationCode); if (!isValidEmail) { QRCode = null; } else if (QRCode == null) { QRCode = _twoFactorAuthProvider.GetQRCode(QRCodeSize, QRCodeSize, EmailAddress.Trim()); } } private void Save() { _twoFactorAuthProvider.PersistRecoveryEmailAddressToPasswordVault(EmailAddress); _settingsProvider.SetSetting(SettingsDefinitions.UseTwoFactorAuthentication, true); } } }
33.336493
250
0.610321
[ "MIT" ]
Christophe-Ch/PaZword
Windows/Impl/PaZword/ViewModels/Dialog/SetupTwoFactorAuthenticationDialogViewModel.cs
7,036
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using AccessibilityInsights.SetupLibrary; using AccessibilityInsights.SharedUx.Enums; using AccessibilityInsights.SharedUx.Settings; using Axe.Windows.Core.Enums; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Globalization; using System.IO; using System.Linq; namespace AccessibilityInsights.SharedUxTests.Settings { /// <summary> /// Tests for ConfigurationModel /// </summary> [TestClass()] public class ConfigurationModelTests { private static FixedConfigSettingsProvider testProvider; [ClassInitialize()] public static void ClassInit(TestContext context) { string testBaseDirectory = Path.Combine(context.TestRunDirectory, context.FullyQualifiedTestClassName); var configDir = Path.Combine(testBaseDirectory, "config"); var userDir = Path.Combine(testBaseDirectory, "user"); testProvider = new FixedConfigSettingsProvider(configDir, userDir); Directory.CreateDirectory(testProvider.ConfigurationFolderPath); } /// <summary> /// Check serialization of selected properties /// </summary> [TestMethod()] public void ConfigurationModelTest() { string path = Path.Combine(testProvider.ConfigurationFolderPath, "config.test"); var coreProps = PropertySettings.DefaultCoreProperties; ConfigurationModel config = new ConfigurationModel { CoreProperties = coreProps, Version = ConfigurationModel.CurrentVersion }; config.SerializeInJSON(path); var newConfig = ConfigurationModel.LoadFromJSON(path, testProvider); File.Delete(path); Assert.IsTrue(coreProps.SequenceEqual(newConfig.CoreProperties)); } [TestMethod()] public void GetCurrentConfigurationTest() { const string expectedHotKeyForRecord = "Recording HotKey"; const string expectedMainWindowActivation = "Main Window Activation HotKey"; string path = Path.Combine(testProvider.ConfigurationFolderPath, "config.test2"); ConfigurationModel config = new ConfigurationModel { HotKeyForRecord = expectedHotKeyForRecord, HotKeyForActivatingMainWindow = expectedMainWindowActivation, Version = "1.0" }; config.SerializeInJSON(path); var nc = ConfigurationModel.LoadFromJSON(path, testProvider); File.Delete(path); Assert.AreEqual(ConfigurationModel.CurrentVersion, nc.Version); Assert.AreEqual(expectedHotKeyForRecord, nc.HotKeyForRecord); Assert.AreEqual(expectedMainWindowActivation, nc.HotKeyForActivatingMainWindow); } [TestMethod] public void LoadFromJSON_FileDoesNotExist_DataIsCorrect() { ConfigurationModel config = GetDefaultConfig(); Assert.IsTrue(config.AlwaysOnTop); Assert.AreEqual("1.1.", config.AppVersion.Substring(0, 4)); ConfirmEnumerablesMatchExpectations( new int[] { 30005, 30003, 30004, 30009, 30001, 30007, 30006, 30013, 30102, 30101 }, config.CoreProperties.ToArray()); ConfirmEnumerablesMatchExpectations(new int[] { }, config.CoreTPAttributes.ToArray()); Assert.IsFalse(config.DisableTestsInSnapMode); Assert.IsFalse(config.DisableDarkMode); Assert.IsTrue(config.EnableTelemetry); Assert.IsTrue(config.EventRecordPath.Equals(testProvider.UserDataFolderPath)); Assert.AreEqual(FontSize.Standard, config.FontSize); Assert.AreEqual(HighlighterMode.HighlighterBeakerTooltip, config.HighlighterMode); Assert.AreEqual("Shift + F9", config.HotKeyForActivatingMainWindow); Assert.AreEqual("Control,Shift + F7", config.HotKeyForMoveToFirstChild); Assert.AreEqual("Control,Shift + F9", config.HotKeyForMoveToLastChild); Assert.AreEqual("Control,Shift + F8", config.HotKeyForMoveToNextSibling); Assert.AreEqual("Control,Shift + F6", config.HotKeyForMoveToParent); Assert.AreEqual("Control,Shift + F5", config.HotKeyForMoveToPreviousSibling); Assert.AreEqual("Shift + F5", config.HotKeyForPause); Assert.AreEqual("Shift + F7", config.HotKeyForRecord); Assert.AreEqual("Shift + F8", config.HotKeyForSnap); Assert.IsTrue(config.IsHighlighterOn); Assert.IsNull(config.IssueReporterSerializedConfigs); Assert.IsTrue(config.IsUnderElementScope); Assert.AreEqual(100, config.MouseSelectionDelayMilliSeconds); Assert.IsFalse(config.PlayScanningSound); Assert.AreEqual(ReleaseChannel.Production, config.ReleaseChannel); Assert.AreEqual(Guid.Empty, config.SelectedIssueReporter); Assert.IsTrue(config.SelectionByFocus); Assert.IsTrue(config.SelectionByMouse); Assert.IsFalse(config.ShowAllProperties); Assert.IsTrue(config.ShowAncestry); Assert.IsTrue(config.ShowTelemetryDialog); Assert.IsFalse(config.ShowUncertain); Assert.IsTrue(config.ShowWelcomeScreenOnLaunch); Assert.IsFalse(config.ShowWhitespaceInTextPatternViewer); Assert.IsTrue(config.TestReportPath.Equals(testProvider.UserDataFolderPath)); Assert.AreEqual(TreeViewMode.Control, config.TreeViewMode); Assert.AreEqual(ReleaseChannel.Production, config.ReleaseChannel); Assert.AreEqual("1.1.10", config.Version); Assert.AreEqual(37, typeof(ConfigurationModel).GetProperties().Length, "Count of ConfigurationModel properties has changed! Please ensure that you are testing the default value for all properties, then update the expected value"); } [TestMethod] public void LoadFronJSON_LegacyFormat_DataIsCorrect() { ConfigurationModel config = ConfigurationModel.LoadFromJSON(@".\Resources\LegacyConfigSettings.json", testProvider); ConfirmOverrideConfigMatchesExpectation(config); } [TestMethod] public void LoadFronJSON_CurrentFormat_DataIsCorrect() { ConfigurationModel config = ConfigurationModel.LoadFromJSON(@".\Resources\ConfigSettings.json", testProvider); ConfirmOverrideConfigMatchesExpectation(config, disableDarkMode: true, issueReporterSerializedConfigs: @"{""27f21dff-2fb3-4833-be55-25787fce3e17"":""hello world""}", selectedIssueReporter: new Guid("{27f21dff-2fb3-4833-be55-25787fce3e17}"), releaseChannel: ReleaseChannel.Canary ); } private static ConfigurationModel GetDefaultConfig() { return ConfigurationModel.LoadFromJSON(null, testProvider); } private static void ConfirmOverrideConfigMatchesExpectation(ConfigurationModel config, Guid? selectedIssueReporter = null, string issueReporterSerializedConfigs = null, ReleaseChannel? releaseChannel = null, bool disableDarkMode = false) { Assert.IsFalse(config.AlwaysOnTop); Assert.AreEqual("1.1.", config.AppVersion.Substring(0, 4)); Assert.AreNotEqual("1.1.700.1", config.AppVersion); ConfirmEnumerablesMatchExpectations( new int[] { 30005, 30003, 30004, 30009, 30001, 30007, 30006, 30013, 30102, 30101 }, config.CoreProperties.ToArray()); ConfirmEnumerablesMatchExpectations( new int[] { }, config.CoreTPAttributes.ToArray()); Assert.IsFalse(config.DisableTestsInSnapMode); Assert.AreEqual(config.DisableDarkMode, disableDarkMode); Assert.IsFalse(config.EnableTelemetry); Assert.AreEqual(@"C:\blah\AccessibilityInsightsEventFiles", config.EventRecordPath); Assert.AreEqual(FontSize.Small, config.FontSize); Assert.AreEqual(HighlighterMode.HighlighterTooltip, config.HighlighterMode); Assert.AreEqual("Alt + F4", config.HotKeyForActivatingMainWindow); Assert.AreEqual("Alt + F6", config.HotKeyForMoveToFirstChild); Assert.AreEqual("Alt + F7", config.HotKeyForMoveToLastChild); Assert.AreEqual("Alt + F8", config.HotKeyForMoveToNextSibling); Assert.AreEqual("Alt + F5", config.HotKeyForMoveToParent); Assert.AreEqual("Alt + F9", config.HotKeyForMoveToPreviousSibling); Assert.AreEqual("Alt + F2", config.HotKeyForPause); Assert.AreEqual("Alt + F1", config.HotKeyForRecord); Assert.AreEqual("Alt + F3", config.HotKeyForSnap); Assert.IsTrue(config.IsHighlighterOn); Assert.AreEqual(issueReporterSerializedConfigs, config.IssueReporterSerializedConfigs); Assert.IsTrue(config.IsUnderElementScope); Assert.AreEqual(200, config.MouseSelectionDelayMilliSeconds); Assert.IsFalse(config.PlayScanningSound); Assert.AreEqual(releaseChannel ?? ReleaseChannel.Production, config.ReleaseChannel); Assert.AreEqual(selectedIssueReporter ?? Guid.Empty, config.SelectedIssueReporter); Assert.IsTrue(config.SelectionByFocus); Assert.IsTrue(config.SelectionByMouse); Assert.IsFalse(config.ShowAllProperties); Assert.IsTrue(config.ShowAncestry); Assert.IsFalse(config.ShowTelemetryDialog); Assert.IsFalse(config.ShowUncertain); Assert.IsTrue(config.ShowWelcomeScreenOnLaunch); Assert.IsFalse(config.ShowWhitespaceInTextPatternViewer); Assert.AreEqual(@"C:\blah\AccessibilityInsightsTestFiles", config.TestReportPath); Assert.AreEqual(TreeViewMode.Content, config.TreeViewMode); Assert.AreEqual("1.1.10", config.Version); } private static void ConfirmEnumerablesMatchExpectations(int[] expected, int[] actual) { Assert.AreEqual(expected.Length, actual.Length); for (int loop = 0; loop < expected.Length; loop++) { Assert.AreEqual(expected[loop], actual[loop], "Index = " + loop.ToString(CultureInfo.InvariantCulture)); } } } }
50.934272
243
0.658863
[ "MIT" ]
QPC-database/accessibility-insights-windows
src/AccessibilityInsights.SharedUxTests/Settings/ConfigurationModelTests.cs
10,637
C#
using System; using System.Text.RegularExpressions; namespace Padi.Vies.Validators { /// <summary> /// /// </summary> public sealed class SEVatValidator : VatValidatorAbstract { private const string RegexPattern =@"^\d{10}01$"; private static readonly int[] Multipliers = {2, 1, 2, 1, 2, 1, 2, 1, 2}; public SEVatValidator() { Regex = new Regex(RegexPattern, RegexOptions.Compiled); CountryCode = nameof(EuCountryCode.SE); } protected override VatValidationResult OnValidate(string vat) { var index = 0; var sum = 0; foreach (var m in Multipliers) { var temp = vat[index++].ToInt() * m; sum += temp > 9 ? (int) Math.Floor(temp / 10D) + temp % 10 : temp; } var checkDigit = 10 - sum % 10; if (checkDigit == 10) { checkDigit = 0; } var isValid = checkDigit == vat[9].ToInt(); return !isValid ? VatValidationResult.Failed("Invalid SE vat: checkValue") : VatValidationResult.Success(); } } }
28.930233
82
0.502412
[ "Apache-2.0" ]
LXBdev/vies-dotnet
src/vies/Validators/SEVatValidator.cs
1,244
C#
using System; using System.Collections.Generic; namespace HerosDB.Entities { public partial class Superpeople { public Superpeople() { EnemiesHero = new HashSet<Enemies>(); EnemiesVillain = new HashSet<Enemies>(); Powers = new HashSet<Powers>(); } public int Id { get; set; } public string Realname { get; set; } public string Workname { get; set; } public string Hideout { get; set; } public int? Chartype { get; set; } public virtual Charactertype ChartypeNavigation { get; set; } public virtual ICollection<Enemies> EnemiesHero { get; set; } public virtual ICollection<Enemies> EnemiesVillain { get; set; } public virtual ICollection<Powers> Powers { get; set; } } }
30.296296
72
0.610024
[ "MIT" ]
201019-UiPath/JenningsJacob-code
2-SQL/HerosApp-DBFirst/HerosDB/Entities/Superpeople.cs
820
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. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void AddPairwise_Vector64_Byte() { var test = new SimpleBinaryOpTest__AddPairwise_Vector64_Byte(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); } // Validates passing a static member works test.RunClsVarScenario(); if (AdvSimd.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__AddPairwise_Vector64_Byte { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Byte[] inArray1, Byte[] inArray2, Byte[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Byte>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Byte>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Byte>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Byte, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Byte, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector64<Byte> _fld1; public Vector64<Byte> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Byte>, byte>(ref testStruct._fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Byte>, byte>(ref testStruct._fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Byte>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__AddPairwise_Vector64_Byte testClass) { var result = AdvSimd.AddPairwise(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__AddPairwise_Vector64_Byte testClass) { fixed (Vector64<Byte>* pFld1 = &_fld1) fixed (Vector64<Byte>* pFld2 = &_fld2) { var result = AdvSimd.AddPairwise( AdvSimd.LoadVector64((Byte*)(pFld1)), AdvSimd.LoadVector64((Byte*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 8; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<Byte>>() / sizeof(Byte); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector64<Byte>>() / sizeof(Byte); private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<Byte>>() / sizeof(Byte); private static Byte[] _data1 = new Byte[Op1ElementCount]; private static Byte[] _data2 = new Byte[Op2ElementCount]; private static Vector64<Byte> _clsVar1; private static Vector64<Byte> _clsVar2; private Vector64<Byte> _fld1; private Vector64<Byte> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__AddPairwise_Vector64_Byte() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Byte>, byte>(ref _clsVar1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Byte>, byte>(ref _clsVar2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Byte>>()); } public SimpleBinaryOpTest__AddPairwise_Vector64_Byte() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Byte>, byte>(ref _fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Byte>, byte>(ref _fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Byte>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } _dataTable = new DataTable(_data1, _data2, new Byte[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.AddPairwise( Unsafe.Read<Vector64<Byte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<Byte>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.AddPairwise( AdvSimd.LoadVector64((Byte*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((Byte*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.AddPairwise), new Type[] { typeof(Vector64<Byte>), typeof(Vector64<Byte>) }) .Invoke(null, new object[] { Unsafe.Read<Vector64<Byte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<Byte>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Byte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.AddPairwise), new Type[] { typeof(Vector64<Byte>), typeof(Vector64<Byte>) }) .Invoke(null, new object[] { AdvSimd.LoadVector64((Byte*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((Byte*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Byte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.AddPairwise( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector64<Byte>* pClsVar1 = &_clsVar1) fixed (Vector64<Byte>* pClsVar2 = &_clsVar2) { var result = AdvSimd.AddPairwise( AdvSimd.LoadVector64((Byte*)(pClsVar1)), AdvSimd.LoadVector64((Byte*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector64<Byte>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector64<Byte>>(_dataTable.inArray2Ptr); var result = AdvSimd.AddPairwise(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector64((Byte*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector64((Byte*)(_dataTable.inArray2Ptr)); var result = AdvSimd.AddPairwise(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__AddPairwise_Vector64_Byte(); var result = AdvSimd.AddPairwise(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleBinaryOpTest__AddPairwise_Vector64_Byte(); fixed (Vector64<Byte>* pFld1 = &test._fld1) fixed (Vector64<Byte>* pFld2 = &test._fld2) { var result = AdvSimd.AddPairwise( AdvSimd.LoadVector64((Byte*)(pFld1)), AdvSimd.LoadVector64((Byte*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.AddPairwise(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector64<Byte>* pFld1 = &_fld1) fixed (Vector64<Byte>* pFld2 = &_fld2) { var result = AdvSimd.AddPairwise( AdvSimd.LoadVector64((Byte*)(pFld1)), AdvSimd.LoadVector64((Byte*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.AddPairwise(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.AddPairwise( AdvSimd.LoadVector64((Byte*)(&test._fld1)), AdvSimd.LoadVector64((Byte*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector64<Byte> op1, Vector64<Byte> op2, void* result, [CallerMemberName] string method = "") { Byte[] inArray1 = new Byte[Op1ElementCount]; Byte[] inArray2 = new Byte[Op2ElementCount]; Byte[] outArray = new Byte[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Byte>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Byte[] inArray1 = new Byte[Op1ElementCount]; Byte[] inArray2 = new Byte[Op2ElementCount]; Byte[] outArray = new Byte[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<Byte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector64<Byte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Byte>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Byte[] left, Byte[] right, Byte[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.AddPairwise(left, right, i) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.AddPairwise)}<Byte>(Vector64<Byte>, Vector64<Byte>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
41.736347
182
0.581581
[ "MIT" ]
06needhamt/runtime
src/coreclr/tests/src/JIT/HardwareIntrinsics/Arm/AdvSimd/AddPairwise.Vector64.Byte.cs
22,162
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web.Mvc; using Orchard.Core.Contents.Controllers; using Orchard.Localization; using Orchard.Logging; using Orchard.Mvc.Extensions; using Orchard.Roles.Models; using Orchard.Roles.Services; using Orchard.Roles.ViewModels; using Orchard.Security; using Orchard.UI.Notify; using Orchard.Utility.Extensions; namespace Orchard.Roles.Controllers { [ValidateInput(false)] public class AdminController : Controller { private readonly IRoleService _roleService; private readonly IAuthorizationService _authorizationService; public AdminController( IOrchardServices services, IRoleService roleService, INotifier notifier, IAuthorizationService authorizationService) { Services = services; _roleService = roleService; _authorizationService = authorizationService; T = NullLocalizer.Instance; Logger = NullLogger.Instance; } public IOrchardServices Services { get; set; } public Localizer T { get; set; } public ILogger Logger { get; set; } public ActionResult Index() { if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to manage roles"))) return new HttpUnauthorizedResult(); var model = new RolesIndexViewModel { Rows = _roleService.GetRoles().OrderBy(r => r.Name).ToList() }; return View(model); } [HttpPost, ActionName("Index")] public ActionResult IndexPOST() { if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to manage roles"))) return new HttpUnauthorizedResult(); foreach (string key in Request.Form.Keys) { if (key.StartsWith("Checkbox.") && Request.Form[key] == "true") { int roleId = Convert.ToInt32(key.Substring("Checkbox.".Length)); _roleService.DeleteRole(roleId); } } return RedirectToAction("Index"); } public ActionResult Create() { if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to manage roles"))) return new HttpUnauthorizedResult(); var model = new RoleCreateViewModel { FeaturePermissions = _roleService.GetInstalledPermissions() }; return View(model); } [HttpPost, ActionName("Create")] public ActionResult CreatePOST() { if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to manage roles"))) return new HttpUnauthorizedResult(); var viewModel = new RoleCreateViewModel(); TryUpdateModel(viewModel); if(String.IsNullOrEmpty(viewModel.Name)) { ModelState.AddModelError("Name", T("Role name can't be empty")); } var role = _roleService.GetRoleByName(viewModel.Name); if (role != null) { ModelState.AddModelError("Name", T("Role with same name already exists")); } if (!ModelState.IsValid) { viewModel.FeaturePermissions = _roleService.GetInstalledPermissions(); return View(viewModel); } _roleService.CreateRole(viewModel.Name); foreach (string key in Request.Form.Keys) { if (key.StartsWith("Checkbox.") && Request.Form[key] == "true") { string permissionName = key.Substring("Checkbox.".Length); _roleService.CreatePermissionForRole(viewModel.Name, permissionName); } } return RedirectToAction("Index"); } public ActionResult Edit(int id) { if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to manage roles"))) return new HttpUnauthorizedResult(); var role = _roleService.GetRole(id); if (role == null) { return HttpNotFound(); } var model = new RoleEditViewModel { Name = role.Name, Id = role.Id, RoleCategoryPermissions = _roleService.GetInstalledPermissions(), CurrentPermissions = _roleService.GetPermissionsForRole(id)}; var simulation = UserSimulation.Create(role.Name); model.EffectivePermissions = model.RoleCategoryPermissions .SelectMany(group => group.Value) .Where(permission => _authorizationService.TryCheckAccess(permission, simulation, null)) .Select(permission=>permission.Name) .Distinct() .ToList(); return View(model); } [HttpPost, ActionName("Edit")] [FormValueRequired("submit.Save")] public ActionResult EditSavePOST(int id) { if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to manage roles"))) return new HttpUnauthorizedResult(); var viewModel = new RoleEditViewModel(); TryUpdateModel(viewModel); if (String.IsNullOrEmpty(viewModel.Name)) { ModelState.AddModelError("Name", T("Role name can't be empty")); } var role = _roleService.GetRoleByName(viewModel.Name); if (role != null && role.Id != id) { ModelState.AddModelError("Name", T("Role with same name already exists")); } if (!ModelState.IsValid) { return Edit(id); } // Save List<string> rolePermissions = new List<string>(); foreach (string key in Request.Form.Keys) { if (key.StartsWith("Checkbox.") && Request.Form[key] == "true") { string permissionName = key.Substring("Checkbox.".Length); rolePermissions.Add(permissionName); } } _roleService.UpdateRole(viewModel.Id, viewModel.Name, rolePermissions); Services.Notifier.Information(T("Your Role has been saved.")); return RedirectToAction("Edit", new { id }); } [HttpPost, ActionName("Edit")] [FormValueRequired("submit.Delete")] public ActionResult EditDeletePOST(int id) { return Delete(id, null); } [HttpPost] public ActionResult Delete(int id, string returnUrl) { if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to manage roles"))) return new HttpUnauthorizedResult(); _roleService.DeleteRole(id); Services.Notifier.Information(T("Role was successfully deleted.")); return this.RedirectLocal(returnUrl, () => RedirectToAction("Index")); } } }
40.546961
116
0.57719
[ "BSD-3-Clause" ]
akovsh/Orchard
build/MsDeploy/Orchard/Modules/Orchard.Roles/Controllers/AdminController.cs
7,341
C#
using System; using System.Collections.Generic; using System.Linq; using Common; namespace Common.Extensions { public static class EnumerableExtensions { /// <summary> /// Select a random element from a collection /// </summary> /// <typeparam name="T"></typeparam> /// <param name="enumerable"></param> /// <returns></returns> public static T Random<T>(this IEnumerable<T> enumerable) { if (enumerable == null) { throw new ArgumentNullException(nameof(enumerable)); } if(!enumerable.Any()) { throw new Exception("Collection cannot be empty"); } // note: creating a Random instance each call may not be correct for you, // consider a thread-safe static instance var r = new Random(); var list = enumerable as IList<T> ?? enumerable.ToList(); return list.Count == 0 ? default : list[r.Next(0, list.Count)]; } public static IEnumerable<IEnumerable<T>> ChunkRandom<T>(this IEnumerable<T> source, int chunksize) { var r = new Random(); while (source.OrderBy(_ => r.Next()).Any()) { yield return source.Take(chunksize); source = source.Skip(chunksize); } } public static IEnumerable<T> ConcatenateCollection<T>(this IEnumerable<IEnumerable<T>> sequences) { return sequences.SelectMany(x => x); } public static T2 Transpose<T, T2>(this IEnumerable<T> sequence, Func<IEnumerable<T>, T2> function) { return function(sequence); } public static IEnumerable<T> ToIEnumerable<T>(this IEnumerator<T> enumerator) { while(enumerator.MoveNext()) { yield return enumerator.Current; } } public static int IndexOf<T>(this IEnumerable<T> enumerable, Func<T, bool> criteria) { int index = enumerable.TakeWhile(x => !criteria(x)).Count(); return index == enumerable.Count() ? -1 : index; } } }
26.705882
101
0.673458
[ "Apache-2.0" ]
cowtrix/supportbot
Common/Extensions/EnumerableExtensions.cs
1,818
C#
using System; using System.IO; using System.IO.Pipes; using System.Linq; namespace IpcAnonymousPipes { /// <summary> /// IPC client /// </summary> public class PipeClient : PipeCommon { #region Fields private readonly AnonymousPipeClientStream _inPipe; private readonly AnonymousPipeClientStream _outPipe; #endregion Fields #region Constructor /// <summary> /// Creates a new instance of PipeClient using the specified pipe handles. /// </summary> /// <param name="inputPipeHandle">The value from PipeServer.ClientInputHandle property.</param> /// <param name="outputPipeHandle">The value from PipeServer.ClientOutputHandle property.</param> public PipeClient(string inputPipeHandle, string outputPipeHandle) { _inPipe = new AnonymousPipeClientStream(PipeDirection.In, inputPipeHandle); _outPipe = new AnonymousPipeClientStream(PipeDirection.Out, outputPipeHandle); // Send connect byte to the pipe server, so it will know that the client is alive. _outPipe.WriteByte(ControlByte.Connect); _outPipe.Flush(); IsConnected = true; } /// <summary> /// Creates a new instance of PipeClient using handles automatically from command line arguments. /// </summary> public PipeClient() : this(ParseCommandLineArg(InPipeHandleArg), ParseCommandLineArg(OutPipeHandleArg)) { } #endregion Constructor #region Public Methods /// <summary> /// Sends bytes to the pipe /// </summary> /// <param name="data"></param> public override void Send(byte[] data) { SendBytes(_outPipe, data); } /// <summary> /// Sends bytes to the pipe /// </summary> /// <param name="stream"></param> public override void Send(Stream stream) { SendStream(_outPipe, stream); } /// <summary> /// Wait until pipes finish transmission /// </summary> public override void WaitForTransmissionEnd() { Ensure(); lock (_syncRoot) { _outPipe.WaitForPipeDrain(); WaitForReceiveOrSend(); } } /// <summary> /// Disposes this instance /// </summary> protected override void OnDispose() { try { SendDisconnect(_outPipe); } catch { } try { _inPipe.Dispose(); } catch { } try { _outPipe.Dispose(); } catch { } } #endregion Public Methods #region Protected methods /// <summary> /// Checks connection. /// </summary> /// <returns></returns> protected override bool PipesAreConnected() { return _inPipe?.IsConnected == true && _outPipe?.IsConnected == true; } /// <summary> /// Runs the messaging on the current thread, so blocks until the pipe is closed. /// </summary> protected override void ReceiveInternal() { _outPipe.WaitForPipeDrain(); // Make sure that the pipe server received the connect byte ReceiverLoop(_inPipe); } #endregion Protected methods #region Private methods private static string ParseCommandLineArg(string prefix) { try { var args = Environment.GetCommandLineArgs(); string value = args.First(x => x.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)).Remove(0, prefix.Length); return value; } catch { throw new ArgumentException($"Cannot parse command line argument: {prefix}"); } } #endregion Private methods } }
29.641791
130
0.565458
[ "MIT" ]
geloczigeri/ipc-anonymouspipes
IpcAnonymousPipes/PipeClient.cs
3,974
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 xray-2016-04-12.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.XRay.Model { /// <summary> /// This is the response object from the GetSamplingStatisticSummaries operation. /// </summary> public partial class GetSamplingStatisticSummariesResponse : AmazonWebServiceResponse { private string _nextToken; private List<SamplingStatisticSummary> _samplingStatisticSummaries = new List<SamplingStatisticSummary>(); /// <summary> /// Gets and sets the property NextToken. /// <para> /// Pagination token. Not used. /// </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 SamplingStatisticSummaries. /// <para> /// Information about the number of requests instrumented for each sampling rule. /// </para> /// </summary> public List<SamplingStatisticSummary> SamplingStatisticSummaries { get { return this._samplingStatisticSummaries; } set { this._samplingStatisticSummaries = value; } } // Check to see if SamplingStatisticSummaries property is set internal bool IsSetSamplingStatisticSummaries() { return this._samplingStatisticSummaries != null && this._samplingStatisticSummaries.Count > 0; } } }
32.866667
114
0.657201
[ "Apache-2.0" ]
Bio2hazard/aws-sdk-net
sdk/src/Services/XRay/Generated/Model/GetSamplingStatisticSummariesResponse.cs
2,465
C#
namespace Demo.ConsoleAppNorthwind.Models2 { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.Spatial; [Table("Customer and Suppliers by City")] public partial class Customer_and_Suppliers_by_City { [StringLength(15)] public string City { get; set; } [Key] [Column(Order = 0)] [StringLength(40)] public string CompanyName { get; set; } [StringLength(30)] public string ContactName { get; set; } [Key] [Column(Order = 1)] [StringLength(9)] public string Relationship { get; set; } } }
25.551724
55
0.630229
[ "MIT" ]
carlos94colina/Ejercicios-Curso-HTML
Demo.ConsoleAppNorthwind/Models2/Customer_and_Suppliers_by_City.cs
741
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 comprehend-2017-11-27.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.Comprehend.Model { /// <summary> /// This is the response object from the DetectDominantLanguage operation. /// </summary> public partial class DetectDominantLanguageResponse : AmazonWebServiceResponse { private List<DominantLanguage> _languages = new List<DominantLanguage>(); /// <summary> /// Gets and sets the property Languages. /// <para> /// The languages that Amazon Comprehend detected in the input text. For each language, /// the response returns the RFC 5646 language code and the level of confidence that Amazon /// Comprehend has in the accuracy of its inference. For more information about RFC 5646, /// see <a href="https://tools.ietf.org/html/rfc5646">Tags for Identifying Languages</a> /// on the <i>IETF Tools</i> web site. /// </para> /// </summary> public List<DominantLanguage> Languages { get { return this._languages; } set { this._languages = value; } } // Check to see if Languages property is set internal bool IsSetLanguages() { return this._languages != null && this._languages.Count > 0; } } }
35.131148
108
0.671955
[ "Apache-2.0" ]
DetlefGolze/aws-sdk-net
sdk/src/Services/Comprehend/Generated/Model/DetectDominantLanguageResponse.cs
2,143
C#
using GoSport.Core.Constants; using System.ComponentModel.DataAnnotations; namespace GoSport.Core.ViewModel.Town { public class TownViewModel { public int Id { get; set; } [Required] [MinLength(ConstViewModel.MinTownNameLength, ErrorMessage = ConstViewModel.TownNameMinErrorMessage)] [MaxLength(ConstViewModel.MaxTownNameLength, ErrorMessage = ConstViewModel.TownNameMaxErrorMessage)] [RegularExpression(ConstViewModel.TownReg, ErrorMessage = ConstViewModel.TownRegErrorMessage)] public string Name { get; set; } [Range(ConstViewModel.zipMin, ConstViewModel.zipMax, ErrorMessage = ConstViewModel.zipErrorMessage)] public int zipCode { get; set; } } }
34.857143
108
0.734973
[ "MIT" ]
ErsanYashar/GoSport
Src/GoSport.Core/ViewModel/Town/TownViewModel.cs
734
C#
// Copyright (c) Josef Pihrt. All rights reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.IO; namespace Roslynator.CommandLine { internal static class ConsoleHelpers { public static IEnumerable<string> ReadRedirectedInputAsLines() { if (Console.IsInputRedirected) { using (Stream stream = Console.OpenStandardInput()) using (var streamReader = new StreamReader(stream, Console.InputEncoding)) { string line; while ((line = streamReader.ReadLine()) != null) yield return line; } } } } }
30.407407
160
0.587089
[ "Apache-2.0" ]
JosefPihrt/Roslynator
src/CommandLine/ConsoleHelpers.cs
823
C#
using System.Collections.Immutable; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace OmniSharp.Extensions.JsonRpc.Generators.Contexts { record ExtensionMethodContext( AttributeData AttributeData, TypeDeclarationSyntax TypeDeclaration, INamedTypeSymbol TypeSymbol, TypeSyntax Item, ImmutableArray<TypeSyntax> RelatedItems ) { public bool IsProxy { get; init; } public bool IsRegistry { get; init; } } }
26.842105
58
0.715686
[ "MIT" ]
Devils-Knight/csharp-language-server-protocol
src/JsonRpc.Generators/Contexts/ExtensionMethodContext.cs
510
C#
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) // This code is distributed under the GNU LGPL (for details please see \doc\license.txt) using System; using ICSharpCode.SharpDevelop.Gui; namespace ICSharpCode.CodeCoverage { /// <summary> /// Represents an assembly in the code coverage tree view. /// </summary> public class CodeCoverageModuleTreeNode : CodeCoverageTreeNode { CodeCoverageModule module; public CodeCoverageModuleTreeNode(CodeCoverageModule module) : base(module, CodeCoverageImageListIndex.Module) { this.module = module; AddDummyNodeIfModuleHasNoMethods(); } void AddDummyNodeIfModuleHasNoMethods() { if (module.Methods.Count > 0) { AddDummyNode(); } } void AddDummyNode() { Nodes.Add(new ExtTreeNode()); } protected override void Initialize() { Nodes.Clear(); foreach (string namespaceName in module.RootNamespaces) { CodeCoverageNamespaceTreeNode node = new CodeCoverageNamespaceTreeNode(namespaceName, CodeCoverageMethod.GetAllMethods(module.Methods, namespaceName)); node.AddTo(this); } // Add any classes that have no namespace. foreach (string className in CodeCoverageMethod.GetClassNames(module.Methods, String.Empty)) { CodeCoverageClassTreeNode classNode = new CodeCoverageClassTreeNode(className, CodeCoverageMethod.GetMethods(module.Methods, String.Empty, className)); classNode.AddTo(this); } // Sort these nodes. SortChildNodes(); } } }
28.537037
155
0.741077
[ "MIT" ]
Plankankul/SharpDevelop-w-Framework
src/AddIns/Analysis/CodeCoverage/Project/Src/CodeCoverageModuleTreeNode.cs
1,543
C#
namespace WhereToFly.Geo { /// <summary> /// Geospatial constants /// </summary> public static class Constants { /// <summary> /// Earth radius, in meter (accepted by WGS84 standard) /// </summary> public static readonly double EarthRadiusInMeter = 6378137; /// <summary> /// Factor to convert from m/s to km/h /// </summary> public static readonly double FactorMeterPerSecondToKilometerPerHour = 3.6; /// <summary> /// Factor to convert feet to meter /// </summary> public static readonly double FactorFeetToMeter = 0.3048; /// <summary> /// Factor to convert nautical miles (nm) to meter /// </summary> public static readonly double FactorNauticalMilesToMeter = 1852.0; } }
28.689655
83
0.58774
[ "BSD-2-Clause" ]
vividos/WhereToFly
src/Geo/Constants.cs
834
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. namespace Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20220301 { using static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Extensions; /// <summary>Parameters to reconcile to the GitRepository source kind type.</summary> public partial class BucketPatchDefinition : Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20220301.IBucketPatchDefinition, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20220301.IBucketPatchDefinitionInternal { /// <summary>Backing field for <see cref="AccessKey" /> property.</summary> private System.Security.SecureString _accessKey; /// <summary>Plaintext access key used to securely access the S3 bucket</summary> [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.PropertyOrigin.Owned)] public System.Security.SecureString AccessKey { get => this._accessKey; set => this._accessKey = value; } /// <summary>Backing field for <see cref="BucketName" /> property.</summary> private string _bucketName; /// <summary>The bucket name to sync from the url endpoint for the flux configuration.</summary> [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.PropertyOrigin.Owned)] public string BucketName { get => this._bucketName; set => this._bucketName = value; } /// <summary>Backing field for <see cref="Insecure" /> property.</summary> private bool? _insecure; /// <summary> /// Specify whether to use insecure communication when puling data from the S3 bucket. /// </summary> [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.PropertyOrigin.Owned)] public bool? Insecure { get => this._insecure; set => this._insecure = value; } /// <summary>Backing field for <see cref="LocalAuthRef" /> property.</summary> private string _localAuthRef; /// <summary> /// Name of a local secret on the Kubernetes cluster to use as the authentication secret rather than the managed or user-provided /// configuration secrets. /// </summary> [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.PropertyOrigin.Owned)] public string LocalAuthRef { get => this._localAuthRef; set => this._localAuthRef = value; } /// <summary>Backing field for <see cref="SyncIntervalInSecond" /> property.</summary> private long? _syncIntervalInSecond; /// <summary> /// The interval at which to re-reconcile the cluster git repository source with the remote. /// </summary> [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.PropertyOrigin.Owned)] public long? SyncIntervalInSecond { get => this._syncIntervalInSecond; set => this._syncIntervalInSecond = value; } /// <summary>Backing field for <see cref="TimeoutInSecond" /> property.</summary> private long? _timeoutInSecond; /// <summary> /// The maximum time to attempt to reconcile the cluster git repository source with the remote. /// </summary> [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.PropertyOrigin.Owned)] public long? TimeoutInSecond { get => this._timeoutInSecond; set => this._timeoutInSecond = value; } /// <summary>Backing field for <see cref="Url" /> property.</summary> private string _url; /// <summary>The URL to sync for the flux configuration S3 bucket.</summary> [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.PropertyOrigin.Owned)] public string Url { get => this._url; set => this._url = value; } /// <summary>Creates an new <see cref="BucketPatchDefinition" /> instance.</summary> public BucketPatchDefinition() { } } /// Parameters to reconcile to the GitRepository source kind type. public partial interface IBucketPatchDefinition : Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IJsonSerializable { /// <summary>Plaintext access key used to securely access the S3 bucket</summary> [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( Required = false, ReadOnly = false, Description = @"Plaintext access key used to securely access the S3 bucket", SerializedName = @"accessKey", PossibleTypes = new [] { typeof(System.Security.SecureString) })] System.Security.SecureString AccessKey { get; set; } /// <summary>The bucket name to sync from the url endpoint for the flux configuration.</summary> [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( Required = false, ReadOnly = false, Description = @"The bucket name to sync from the url endpoint for the flux configuration.", SerializedName = @"bucketName", PossibleTypes = new [] { typeof(string) })] string BucketName { get; set; } /// <summary> /// Specify whether to use insecure communication when puling data from the S3 bucket. /// </summary> [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( Required = false, ReadOnly = false, Description = @"Specify whether to use insecure communication when puling data from the S3 bucket.", SerializedName = @"insecure", PossibleTypes = new [] { typeof(bool) })] bool? Insecure { get; set; } /// <summary> /// Name of a local secret on the Kubernetes cluster to use as the authentication secret rather than the managed or user-provided /// configuration secrets. /// </summary> [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( Required = false, ReadOnly = false, Description = @"Name of a local secret on the Kubernetes cluster to use as the authentication secret rather than the managed or user-provided configuration secrets.", SerializedName = @"localAuthRef", PossibleTypes = new [] { typeof(string) })] string LocalAuthRef { get; set; } /// <summary> /// The interval at which to re-reconcile the cluster git repository source with the remote. /// </summary> [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( Required = false, ReadOnly = false, Description = @"The interval at which to re-reconcile the cluster git repository source with the remote.", SerializedName = @"syncIntervalInSeconds", PossibleTypes = new [] { typeof(long) })] long? SyncIntervalInSecond { get; set; } /// <summary> /// The maximum time to attempt to reconcile the cluster git repository source with the remote. /// </summary> [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( Required = false, ReadOnly = false, Description = @"The maximum time to attempt to reconcile the cluster git repository source with the remote.", SerializedName = @"timeoutInSeconds", PossibleTypes = new [] { typeof(long) })] long? TimeoutInSecond { get; set; } /// <summary>The URL to sync for the flux configuration S3 bucket.</summary> [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( Required = false, ReadOnly = false, Description = @"The URL to sync for the flux configuration S3 bucket.", SerializedName = @"url", PossibleTypes = new [] { typeof(string) })] string Url { get; set; } } /// Parameters to reconcile to the GitRepository source kind type. internal partial interface IBucketPatchDefinitionInternal { /// <summary>Plaintext access key used to securely access the S3 bucket</summary> System.Security.SecureString AccessKey { get; set; } /// <summary>The bucket name to sync from the url endpoint for the flux configuration.</summary> string BucketName { get; set; } /// <summary> /// Specify whether to use insecure communication when puling data from the S3 bucket. /// </summary> bool? Insecure { get; set; } /// <summary> /// Name of a local secret on the Kubernetes cluster to use as the authentication secret rather than the managed or user-provided /// configuration secrets. /// </summary> string LocalAuthRef { get; set; } /// <summary> /// The interval at which to re-reconcile the cluster git repository source with the remote. /// </summary> long? SyncIntervalInSecond { get; set; } /// <summary> /// The maximum time to attempt to reconcile the cluster git repository source with the remote. /// </summary> long? TimeoutInSecond { get; set; } /// <summary>The URL to sync for the flux configuration S3 bucket.</summary> string Url { get; set; } } }
55.988889
175
0.671859
[ "MIT" ]
AlanFlorance/azure-powershell
src/KubernetesConfiguration/generated/api/Models/Api20220301/BucketPatchDefinition.cs
9,899
C#
using System.Collections.Generic; using Newtonsoft.Json; namespace NeoModules.RPC.DTOs { public class Asset { [JsonProperty("type")] public string Type { get; set; } [JsonProperty("name")] public List<Name> Name { get; set; } [JsonProperty("amount")] public string Amount { get; set; } [JsonProperty("precision")] public int Precision { get; set; } [JsonProperty("owner")] public string Owner { get; set; } [JsonProperty("admin")] public string Admin { get; set; } } }
21.592593
44
0.574614
[ "MIT" ]
CityOfZion/Neo-RPC-SharpClient
src/NeoModules.RPC/DTOs/Asset.cs
583
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace CodeCompendium.BinarySerialization { /// <summary> /// Converts objects to/from byte arrays. /// </summary> internal class Converter { #region Fields private const string _typeNotSupported = "Serializing/Deserializing properties of type {0} is not supported at this time."; private static readonly Type _stringType = typeof(string); private readonly Endianness _systemEndianness = BitConverter.IsLittleEndian ? Endianness.LittleEndian : Endianness.BigEndian; #endregion #region Protected Methods /// <summary> /// Gets a byte array representing the value. /// </summary> protected byte[] GetBytes<T>(T value, Endianness endianness) { byte[] bytes = null; bool reverseIfNeeded = true; if (value is bool boolValue) { bytes = BitConverter.GetBytes(boolValue); } else if (value is byte byteValue) { bytes = new byte[] { byteValue }; } else if (value is char charValue) { bytes = BitConverter.GetBytes(charValue); } else if (value is decimal decimalValue) { reverseIfNeeded = false; List<byte> decimalBytes = new List<byte>(); foreach (int bit in Decimal.GetBits(decimalValue)) { decimalBytes.AddRange(GetBytes(bit, endianness)); } bytes = decimalBytes.ToArray(); } else if (value is double doubleValue) { bytes = BitConverter.GetBytes(doubleValue); } else if (value is float floatValue) { bytes = BitConverter.GetBytes(floatValue); } else if (value is int intValue) { bytes = BitConverter.GetBytes(intValue); } else if (value is uint uintValue) { bytes = BitConverter.GetBytes(uintValue); } else if (value is long longValue) { bytes = BitConverter.GetBytes(longValue); } else if (value is ulong ulongValue) { bytes = BitConverter.GetBytes(ulongValue); } else if (value is short shortValue) { bytes = BitConverter.GetBytes(shortValue); } else if (value is ushort ushortValue) { bytes = BitConverter.GetBytes(ushortValue); } else if (value is string stringValue) { reverseIfNeeded = false; byte[] stringBytes = Encoding.Unicode.GetBytes(stringValue).ToArray(); byte[] lengthBytes = GetBytes(stringBytes.Length, endianness); if (endianness != _systemEndianness) { stringBytes = stringBytes.Reverse().ToArray(); } List<byte> combined = new List<byte>(lengthBytes); combined.AddRange(stringBytes); bytes = combined.ToArray(); } else if (value is Guid guid) { bytes = guid.ToByteArray(); } else if (value is DateTime dateTime) { bytes = GetBytes(dateTime.Ticks, endianness); } else if (value is Enum enumValue) { bytes = BitConverter.GetBytes((int)(object)enumValue); } else { throw new NotSupportedException(String.Format(_typeNotSupported, typeof(T).Name)); } if (reverseIfNeeded) { if (_systemEndianness != endianness) { bytes = bytes.Reverse().ToArray(); } } return bytes; } /// <summary> /// Gets a value of the selected type from the byte array. /// </summary> protected T GetValue<T>(byte[] bytes, Endianness endianness) { return (T)GetValue(typeof(T), bytes, endianness); } /// <summary> /// Gets a value of the selected type from the byte array. /// </summary> protected object GetValue(Type type, byte[] bytes, Endianness endianness) { object value = default; if (type == typeof(decimal)) { List<int> bits = new List<int>(); for (int i = 0; i < 4; ++i) { bits.Add(GetValue<int>(bytes.Skip(i * 4).Take(4).ToArray(), endianness)); } value = new Decimal(bits.ToArray()); } else if (type == typeof(string)) { using (MemoryStream memoryStream = new MemoryStream(bytes)) { using (BinaryReader reader = new BinaryReader(memoryStream)) { value = GetNextString(reader, endianness); } } } else { if (_systemEndianness != endianness) { bytes = bytes.Reverse().ToArray(); } if (type == typeof(bool)) { value = BitConverter.ToBoolean(bytes, 0); } else if (type == typeof(byte)) { value = bytes[0]; } else if (type == typeof(char)) { value = BitConverter.ToChar(bytes, 0); } else if (type == typeof(double)) { value = BitConverter.ToDouble(bytes, 0); } else if (type == typeof(float)) { value = BitConverter.ToSingle(bytes, 0); } else if (type == typeof(int)) { value = BitConverter.ToInt32(bytes, 0); } else if (type == typeof(uint)) { value = BitConverter.ToUInt32(bytes, 0); } else if (type == typeof(long)) { value = BitConverter.ToInt64(bytes, 0); } else if (type == typeof(ulong)) { value = BitConverter.ToUInt64(bytes, 0); } else if (type == typeof(short)) { value = BitConverter.ToInt16(bytes, 0); } else if (type == typeof(ushort)) { value = BitConverter.ToUInt16(bytes, 0); } else if (type == typeof(Guid)) { value = new Guid(bytes); } else if (type == typeof(DateTime)) { value = new DateTime(BitConverter.ToInt64(bytes, 0)); } else if (type?.BaseType == typeof(Enum)) { value = Enum.ToObject(type, BitConverter.ToInt32(bytes, 0)); } else { throw new NotSupportedException(String.Format(_typeNotSupported, type.Name)); } } return value; } /// <summary> /// Gets the next string from the reader's stream. /// </summary> protected string GetNextString(BinaryReader reader, Endianness endianness) { string value = null; int length = GetValue<int>(reader.ReadBytes(4), endianness); byte[] stringBytes = reader.ReadBytes(length); if (_systemEndianness != endianness) { stringBytes = stringBytes.Reverse().ToArray(); } value = Encoding.Unicode.GetString(stringBytes); return value; } /// <summary> /// Returns true if the type is a primitive or value type supported by this converted. /// </summary> protected bool IsValueType(Type type) { return type != null && (type.IsPrimitive || type == typeof(decimal) || type == typeof(string) || type == typeof(Guid) || type == typeof(DateTime)) || type?.BaseType == typeof(Enum); } /// <summary> /// Returns true if the type name is a primitive or value type supported by this converted. /// </summary> protected bool IsValueType(string typeName) { return IsValueType(Type.GetType(typeName)); } /// <summary> /// Returns true if the type name matches the type name for string. /// </summary> protected bool IsStringType(Type type) { return type == _stringType; } /// <summary> /// Gets the size of the type. /// </summary> protected int TypeSize(Type type) { int size = 0; if (type == typeof(bool)) { size = sizeof(bool); } else if (type == typeof(byte)) { size = sizeof(byte); } else if (type == typeof(char)) { size = sizeof(char); } else if (type == typeof(decimal)) { size = sizeof(decimal); } else if (type == typeof(double)) { size = sizeof(double); } else if (type == typeof(float)) { size = sizeof(float); } else if (type == typeof(int)) { size = sizeof(int); } else if (type == typeof(uint)) { size = sizeof(uint); } else if (type == typeof(long)) { size = sizeof(long); } else if (type == typeof(ulong)) { size = sizeof(ulong); } else if (type == typeof(short)) { size = sizeof(short); } else if (type == typeof(ushort)) { size = sizeof(ushort); } else if (type == typeof(Guid)) { size = 16; } else if (type == typeof(DateTime)) { size = sizeof(long); } else if (type == typeof(DateTime)) { size = sizeof(long); } else if (type?.BaseType == typeof(Enum)) { size = sizeof(int); } return size; } /// <summary> /// Gets the size of the type. /// </summary> protected int TypeSize(string typeName) { return TypeSize(Type.GetType(typeName)); } #endregion } }
28.112
131
0.485107
[ "MIT" ]
rthomasv3/BinarySerializer
BinarySerializer/Converter.cs
10,544
C#
namespace StyleChecker.Test.Size.LongLine { using Microsoft.VisualStudio.TestTools.UnitTesting; using StyleChecker.Size.LongLine; using StyleChecker.Test.Framework; [TestClass] public sealed class AnalyzerTest : DiagnosticVerifier { public AnalyzerTest() : base(new Analyzer()) { } [TestMethod] public void Empty() => VerifyDiagnostic("", Atmosphere.Default); [TestMethod] public void Okay() => VerifyDiagnostic(ReadText("Okay"), Atmosphere.Default); [TestMethod] public void Code() { var code = ReadText("Code"); Result Expected(Belief b) => b.ToResult(Analyzer.DiagnosticId, ToDetail); VerifyDiagnostic(code, Atmosphere.Default, Expected); } [TestMethod] public void DocumentComment() { var code = ReadText("DocumentComment"); Result Expected(Belief b) => b.ToResult(Analyzer.DiagnosticId, ToDetail); VerifyDiagnostic(code, Atmosphere.Default, Expected); } [TestMethod] public void Config() { var code = ReadText("Code20"); Result Expected(Belief b) => b.ToResult(Analyzer.DiagnosticId, ToDetail); var configText = ReadText("MaxLineLength20", "xml"); VerifyDiagnostic( code, Atmosphere.Default.WithConfigText(configText), Expected); } private string ToDetail(string m) => $"The length of this line must be less than {m}."; } }
27.721311
70
0.560024
[ "BSD-2-Clause" ]
MatthewL246/StyleChecker
StyleChecker/StyleChecker.Test/Size/LongLine/AnalyzerTest.cs
1,691
C#
// ------------------------------------------------------------------------------ // <auto-generated> // Generated by Xsd2Code. Version 3.4.0.18239 Microsoft Reciprocal License (Ms-RL) // <NameSpace>Mim.V6301</NameSpace><Collection>Array</Collection><codeType>CSharp</codeType><EnableDataBinding>False</EnableDataBinding><EnableLazyLoading>False</EnableLazyLoading><TrackingChangesEnable>False</TrackingChangesEnable><GenTrackingClasses>False</GenTrackingClasses><HidePrivateFieldInIDE>False</HidePrivateFieldInIDE><EnableSummaryComment>True</EnableSummaryComment><VirtualProp>False</VirtualProp><IncludeSerializeMethod>True</IncludeSerializeMethod><UseBaseClass>False</UseBaseClass><GenBaseClass>False</GenBaseClass><GenerateCloneMethod>True</GenerateCloneMethod><GenerateDataContracts>False</GenerateDataContracts><CodeBaseTag>Net35</CodeBaseTag><SerializeMethodName>Serialize</SerializeMethodName><DeserializeMethodName>Deserialize</DeserializeMethodName><SaveToFileMethodName>SaveToFile</SaveToFileMethodName><LoadFromFileMethodName>LoadFromFile</LoadFromFileMethodName><GenerateXMLAttributes>True</GenerateXMLAttributes><OrderXMLAttrib>False</OrderXMLAttrib><EnableEncoding>False</EnableEncoding><AutomaticProperties>False</AutomaticProperties><GenerateShouldSerialize>False</GenerateShouldSerialize><DisableDebug>False</DisableDebug><PropNameSpecified>Default</PropNameSpecified><Encoder>UTF8</Encoder><CustomUsings></CustomUsings><ExcludeIncludedTypes>True</ExcludeIncludedTypes><EnableInitializeFields>False</EnableInitializeFields> // </auto-generated> // ------------------------------------------------------------------------------ namespace Mim.V6301 { using System; using System.Diagnostics; using System.Xml.Serialization; using System.Collections; using System.Xml.Schema; using System.ComponentModel; using System.IO; using System.Text; [System.CodeDom.Compiler.GeneratedCodeAttribute("Xsd2Code", "3.4.0.18239")] [System.SerializableAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.XmlTypeAttribute(TypeName="PORX_MT122003UK30.ActRef", Namespace="urn:hl7-org:v3")] [System.Xml.Serialization.XmlRootAttribute("PORX_MT122003UK30.ActRef", Namespace="urn:hl7-org:v3")] public partial class PORX_MT122003UK30ActRef { private II idField; private string typeField; private string classCodeField; private string moodCodeField; private string[] typeIDField; private string[] realmCodeField; private string nullFlavorField; private static System.Xml.Serialization.XmlSerializer serializer; public PORX_MT122003UK30ActRef() { this.typeField = "ActHeir"; this.classCodeField = "ACT"; } public II id { get { return this.idField; } set { this.idField = value; } } [System.Xml.Serialization.XmlAttributeAttribute(DataType="token")] public string type { get { return this.typeField; } set { this.typeField = value; } } [System.Xml.Serialization.XmlAttributeAttribute()] public string classCode { get { return this.classCodeField; } set { this.classCodeField = value; } } [System.Xml.Serialization.XmlAttributeAttribute()] public string moodCode { get { return this.moodCodeField; } set { this.moodCodeField = value; } } [System.Xml.Serialization.XmlAttributeAttribute()] public string[] typeID { get { return this.typeIDField; } set { this.typeIDField = value; } } [System.Xml.Serialization.XmlAttributeAttribute(DataType="token")] public string[] realmCode { get { return this.realmCodeField; } set { this.realmCodeField = value; } } [System.Xml.Serialization.XmlAttributeAttribute(DataType="token")] public string nullFlavor { get { return this.nullFlavorField; } set { this.nullFlavorField = value; } } private static System.Xml.Serialization.XmlSerializer Serializer { get { if ((serializer == null)) { serializer = new System.Xml.Serialization.XmlSerializer(typeof(PORX_MT122003UK30ActRef)); } return serializer; } } #region Serialize/Deserialize /// <summary> /// Serializes current PORX_MT122003UK30ActRef object into an XML document /// </summary> /// <returns>string XML value</returns> public virtual string Serialize() { System.IO.StreamReader streamReader = null; System.IO.MemoryStream memoryStream = null; try { memoryStream = new System.IO.MemoryStream(); Serializer.Serialize(memoryStream, this); memoryStream.Seek(0, System.IO.SeekOrigin.Begin); streamReader = new System.IO.StreamReader(memoryStream); return streamReader.ReadToEnd(); } finally { if ((streamReader != null)) { streamReader.Dispose(); } if ((memoryStream != null)) { memoryStream.Dispose(); } } } /// <summary> /// Deserializes workflow markup into an PORX_MT122003UK30ActRef object /// </summary> /// <param name="xml">string workflow markup to deserialize</param> /// <param name="obj">Output PORX_MT122003UK30ActRef object</param> /// <param name="exception">output Exception value if deserialize failed</param> /// <returns>true if this XmlSerializer can deserialize the object; otherwise, false</returns> public static bool Deserialize(string xml, out PORX_MT122003UK30ActRef obj, out System.Exception exception) { exception = null; obj = default(PORX_MT122003UK30ActRef); try { obj = Deserialize(xml); return true; } catch (System.Exception ex) { exception = ex; return false; } } public static bool Deserialize(string xml, out PORX_MT122003UK30ActRef obj) { System.Exception exception = null; return Deserialize(xml, out obj, out exception); } public static PORX_MT122003UK30ActRef Deserialize(string xml) { System.IO.StringReader stringReader = null; try { stringReader = new System.IO.StringReader(xml); return ((PORX_MT122003UK30ActRef)(Serializer.Deserialize(System.Xml.XmlReader.Create(stringReader)))); } finally { if ((stringReader != null)) { stringReader.Dispose(); } } } /// <summary> /// Serializes current PORX_MT122003UK30ActRef object into file /// </summary> /// <param name="fileName">full path of outupt xml file</param> /// <param name="exception">output Exception value if failed</param> /// <returns>true if can serialize and save into file; otherwise, false</returns> public virtual bool SaveToFile(string fileName, out System.Exception exception) { exception = null; try { SaveToFile(fileName); return true; } catch (System.Exception e) { exception = e; return false; } } public virtual void SaveToFile(string fileName) { System.IO.StreamWriter streamWriter = null; try { string xmlString = Serialize(); System.IO.FileInfo xmlFile = new System.IO.FileInfo(fileName); streamWriter = xmlFile.CreateText(); streamWriter.WriteLine(xmlString); streamWriter.Close(); } finally { if ((streamWriter != null)) { streamWriter.Dispose(); } } } /// <summary> /// Deserializes xml markup from file into an PORX_MT122003UK30ActRef object /// </summary> /// <param name="fileName">string xml file to load and deserialize</param> /// <param name="obj">Output PORX_MT122003UK30ActRef object</param> /// <param name="exception">output Exception value if deserialize failed</param> /// <returns>true if this XmlSerializer can deserialize the object; otherwise, false</returns> public static bool LoadFromFile(string fileName, out PORX_MT122003UK30ActRef obj, out System.Exception exception) { exception = null; obj = default(PORX_MT122003UK30ActRef); try { obj = LoadFromFile(fileName); return true; } catch (System.Exception ex) { exception = ex; return false; } } public static bool LoadFromFile(string fileName, out PORX_MT122003UK30ActRef obj) { System.Exception exception = null; return LoadFromFile(fileName, out obj, out exception); } public static PORX_MT122003UK30ActRef LoadFromFile(string fileName) { System.IO.FileStream file = null; System.IO.StreamReader sr = null; try { file = new System.IO.FileStream(fileName, FileMode.Open, FileAccess.Read); sr = new System.IO.StreamReader(file); string xmlString = sr.ReadToEnd(); sr.Close(); file.Close(); return Deserialize(xmlString); } finally { if ((file != null)) { file.Dispose(); } if ((sr != null)) { sr.Dispose(); } } } #endregion #region Clone method /// <summary> /// Create a clone of this PORX_MT122003UK30ActRef object /// </summary> public virtual PORX_MT122003UK30ActRef Clone() { return ((PORX_MT122003UK30ActRef)(this.MemberwiseClone())); } #endregion } }
40.122302
1,358
0.56464
[ "MIT" ]
Kusnaditjung/MimDms
src/Mim.V6301/Generated/PORX_MT122003UK30ActRef.cs
11,154
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Project.GUI.Widgets.ChartHeideable { public class Factory_ChartHideable : IFactory_ChartHideable { public IChartHideable Get_IChartHideable() { var result = new ChartHideable(); result.Dock = DockStyle.Fill; return result; } } }
21.818182
64
0.645833
[ "MIT" ]
govorukhin/Union_AppCtrlr_MVP
Union/Union/Project/GUI/Widgets/ChartHeideable/Factory/Factory_ChartHideable.cs
482
C#
using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Windows; // 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("Panels")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Panels")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] //In order to begin building localizable applications, set //<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file //inside a <PropertyGroup>. For example, if you are using US english //in your source files, set the <UICulture> to en-US. Then uncomment //the NeutralResourceLanguage attribute below. Update the "en-US" in //the line below to match the UICulture setting in the project file. //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located //(used if a resource is not found in the page, // or application resource dictionaries) ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located //(used if a resource is not found in the page, // app, or any theme specific resource dictionaries) )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
42.142857
98
0.708051
[ "MIT" ]
manupstairs/Notepad
Notepad/Panels/Properties/AssemblyInfo.cs
2,363
C#
using System; using System.Collections.Generic; using System.Text; using Infrastructure.Commands; namespace eShop.Marketing.Campaign.Events { public interface Defined : IStampedEvent { Guid CampaignId { get; set; } string Name { get; set; } string Description { get; set; } } }
19.8125
44
0.671924
[ "MIT" ]
charlessolar/eShopOnContainersDDD
src/Contexts/Marketing/Language/Campaign/Events/Defined.cs
319
C#
/* Copyright 2019 Dicky Suryadi Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using Microsoft.Extensions.Configuration; namespace DotNetify.Pulse { public class PulseConfiguration { internal static readonly string SECTION = "DotNetifyPulse"; // Absolute path to the folder containing UI static files. public string UIPath { get; set; } // Minimum interval between push updates in milliseconds. public int PushUpdateInterval { get; set; } = 100; public IConfigurationSection Providers { get; set; } public T GetProvider<T>(string key) where T : class => Providers?.GetSection(key).Get<T>() ?? Activator.CreateInstance<T>(); } }
35.69697
130
0.741935
[ "Apache-2.0" ]
dsuryd/dotNetify-Pulse
DotNetifyLib.Pulse/PulseConfiguration.cs
1,180
C#
using AntShares.Cryptography; namespace AntShares.Core.Scripts { public static class Helper { /// <summary> /// 计算脚本的散列值,先使用sha256,然后再计算一次ripemd160 /// </summary> /// <param name="script">要计算散列值的脚本</param> /// <returns>返回脚本的散列值</returns> public static UInt160 ToScriptHash(this byte[] script) { return new UInt160(script.Sha256().RIPEMD160()); } } }
24.444444
62
0.586364
[ "MIT" ]
DavidthePangwaer/AntShares
AntSharesCore/Core/Scripts/Helper.cs
516
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using PlatHak.FlowCode.FlowItems; namespace PlatHak.FlowCode { public class FlowCodeBuilder { public List<FlowItem> FlowItems { get; set; } public FlowCodeBuilder() { FlowItems = new List<FlowItem>(); } public override string ToString() { var stringbuilder = new CodeBuilder(); foreach (var usingItem in FlowItems.OfType<UsingItem>()) { usingItem.AppendString(stringbuilder); } foreach (var usingItem in FlowItems.Where(x=> !(x is UsingItem))) { usingItem.AppendString(stringbuilder); } return stringbuilder.ToString(); } } }
25.117647
77
0.583138
[ "CC0-1.0" ]
coman3/PlatHak
PlatHak.Tests/PlatHak.FlowCode/FlowCodeBuilder.cs
856
C#
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ using System; using System.Collections.Generic; using System.Fabric.Test; using System.Linq; using System.Text; using System.Threading.Tasks; namespace System.Fabric.Setup { public class Structs { private Dictionary<string, StructObject> infos = new Dictionary<string, StructObject>(); public Structs() { } public StructObject this[string name] { get { return this.infos.ContainsKey(name) ? this.infos[name] : null; } set { if (infos.ContainsKey(name)) { this.infos[name] = value; } } } public int Count { get { return GetCount(); } } public Dictionary<string, StructObject> Infos { get { return this.infos; } } public bool ContainsName(string name) { return this.infos.ContainsKey(name); } public int GetCount() { return this.infos.Count; } public void Add(string name, StructObject io) { this.infos.Add(name, io); } public List<string> Compare(Structs target) { if (this.Count == 0 || target == null || target.Count == 0) { return null; } List<string> differences = new List<string>(); // Search structs which defined in previous release from current build // If it is found, compare the struct // If the content of same struct are differrent // Compare and output the different members foreach (KeyValuePair<string, StructObject> pair in this.infos) { if (ValidationIgnoreList .ValidationIgnoreListStructs .ContainsKey(pair.Key)) { // Ignore a set of STRUCTS from this validation. continue; } string name = pair.Key; if (target.infos.ContainsKey(name)) { StructObject cur = target[name]; StructObject pre = pair.Value; if (!pre.Equals(cur)) { Members curMethods = ValidationHelper.ParseMemberInformation(cur.Body); Members preMethods = ValidationHelper.ParseMemberInformation(pre.Body); string difference = preMethods.Compare(curMethods); LogHelper.Log("Differences of {0}:", name); LogHelper.Log(difference); differences.Add(difference); } } } return differences; } } }
28.991228
100
0.465053
[ "MIT" ]
AndreyTretyak/service-fabric
src/prod/test/IDLValidation/Structs.cs
3,305
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.Collections; using System.Collections.Generic; using System.Linq; using DotNetNuke.Common; using DotNetNuke.Common.Utilities; using DotNetNuke.Data; using DotNetNuke.Entities.Modules; using DotNetNuke.Entities.Portals; using DotNetNuke.Entities.Tabs.TabVersions; using DotNetNuke.Framework; using DotNetNuke.UI.Skins; namespace DotNetNuke.Entities.Tabs { public class TabModulesController: ServiceLocator<ITabModulesController, TabModulesController>, ITabModulesController { #region Public Methods public ArrayList GetTabModules(TabInfo tab) { var objPaneModules = new Dictionary<string, int>(); var modules = GetModules(tab); var configuredModules = new ArrayList(); foreach (var configuringModule in modules) { ConfigureModule(configuringModule, tab); if (objPaneModules.ContainsKey(configuringModule.PaneName) == false) { objPaneModules.Add(configuringModule.PaneName, 0); } configuringModule.PaneModuleCount = 0; if (!configuringModule.IsDeleted) { objPaneModules[configuringModule.PaneName] = objPaneModules[configuringModule.PaneName] + 1; configuringModule.PaneModuleIndex = objPaneModules[configuringModule.PaneName] - 1; } configuredModules.Add(configuringModule); } foreach (ModuleInfo module in configuredModules) { module.PaneModuleCount = objPaneModules[module.PaneName]; } return configuredModules; } public Dictionary<int,string> GetTabModuleSettingsByName(string settingName) { var portalId = PortalSettings.Current.PortalId; var dataProvider = DataProvider.Instance(); var cacheKey = string.Format(DataCache.TabModuleSettingsNameCacheKey, portalId, settingName); var cachedItems = CBO.GetCachedObject<Dictionary<int, string>>( new CacheItemArgs(cacheKey, DataCache.TabModuleCacheTimeOut, DataCache.TabModuleCachePriority), c => { using (var dr = dataProvider.GetTabModuleSettingsByName(portalId, settingName)) { var result = new Dictionary<int, string>(); while (dr.Read()) { result[dr.GetInt32(0)] = dr.GetString(1); } return result; } }); return cachedItems; } public IList<int> GetTabModuleIdsBySetting(string settingName, string expectedValue) { var items = this.GetTabModuleSettingsByName(settingName); var matches = items.Where(e => e.Value.Equals(expectedValue, StringComparison.CurrentCultureIgnoreCase)); var keyValuePairs = matches as KeyValuePair<int, string>[] ?? matches.ToArray(); if (keyValuePairs.Any()) { return keyValuePairs.Select(kpv => kpv.Key).ToList(); } // this is fallback in case a new value was added but not in the cache yet var dataProvider = DataProvider.Instance(); using (var dr = dataProvider.GetTabModuleIdsBySettingNameAndValue(PortalSettings.Current.PortalId, settingName, expectedValue)) { var result = new List<int>(); while (dr.Read()) { result.Add(dr.GetInt32(0)); } return result; } } #endregion #region Private Methods private static void ConfigureModule(ModuleInfo cloneModule, TabInfo tab) { if (Null.IsNull(cloneModule.StartDate)) { cloneModule.StartDate = DateTime.MinValue; } if (Null.IsNull(cloneModule.EndDate)) { cloneModule.EndDate = DateTime.MaxValue; } if (String.IsNullOrEmpty(cloneModule.ContainerSrc)) { cloneModule.ContainerSrc = tab.ContainerSrc; } cloneModule.ContainerSrc = SkinController.FormatSkinSrc(cloneModule.ContainerSrc, PortalSettings.Current); cloneModule.ContainerPath = SkinController.FormatSkinPath(cloneModule.ContainerSrc); } private static IEnumerable<ModuleInfo> GetModules(TabInfo tab) { int urlVersion; if (TabVersionUtils.TryGetUrlVersion(out urlVersion)) { return TabVersionBuilder.Instance.GetVersionModules(tab.TabID, urlVersion); } if (Globals.IsEditMode()) { return TabVersionBuilder.Instance.GetUnPublishedVersionModules(tab.TabID); } return TabVersionBuilder.Instance.GetCurrentModules(tab.TabID); } #endregion protected override Func<ITabModulesController> GetFactory() { return () => new TabModulesController(); } } }
38.041379
139
0.593546
[ "MIT" ]
MaiklT/Dnn.Platform
DNN Platform/Library/Entities/Tabs/TabModulesController.cs
5,518
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace ManagementAgent { public partial class MainForm : Form { UInt32 last_rec = 0; UInt32 last_sent = 0; bool isUsetStop = false; public MainForm() { InitializeComponent(); } private void MainForm_Load(object sender, EventArgs e) { LoadConfig(); } private void timerStatus_Tick(object sender, EventArgs e) { Services.Config.Load(); Process p = null; try { p = Process.GetProcessById(Services.Config.ProcessID); } catch { } if (p == null || Services.Config.ProcessID == 0) { lblStatus.Text = "Stoped"; lblStatus.BackColor = Color.OrangeRed; btnStartStop.Text = "Start"; txtUpTime.Text = "00:00:00"; lblConnectionStatus.Text = "Disconnected"; lblConnectionStatus.BackColor = Color.OrangeRed; if (!isUsetStop && cbAutoconnect.Checked) btnStartStop_Click(null, null); } else { lblStatus.Text = "Runing"; lblStatus.BackColor = Color.GreenYellow; btnStartStop.Text = "Stop"; var ts = new TimeSpan(DateTime.Now.Ticks) - new TimeSpan(Services.Config.StartTime); txtUpTime.Text = ts.TotalHours.ToString("00") + ":" + ts.Minutes.ToString("00") + ":" + ts.Seconds.ToString("00"); Services.Memory.OpenMem(); if (Services.Memory.Connected > 0) { lblConnectionStatus.Text = "Connected"; lblConnectionStatus.BackColor = Color.GreenYellow; //lblDataSent.Text = GetBytesCount(Services.Memory.DataSent); //lblDataRec.Text = GetBytesCount(Services.Memory.DataRec); lblClients.Text = Services.Memory.CLients.ToString(); CalcSpeed(); } else { lblConnectionStatus.Text = "Disconnected"; lblConnectionStatus.BackColor = Color.OrangeRed; } } } private string GetBytesCount(UInt32 _bytes) { if (_bytes < 1024) { return _bytes.ToString() + " B"; } if (_bytes < (1024*1024)) { return (_bytes/1024).ToString("#.0") + " KB"; } if (_bytes < (1024 * 1024 * 1024)) { return (_bytes / (1024*1024)).ToString("#.0") + " MB"; } return (_bytes / (1024 * 1024 * 1024)).ToString("#.0") + " GB"; } private string GetBytesSpeed(UInt32 _bytes) { if (_bytes < 1024) { return _bytes.ToString() + " Bps"; } if (_bytes < (1024 * 1024)) { return (_bytes / 1024).ToString("#.0") + " KBps"; } if (_bytes < (1024 * 1024 * 1024)) { return (_bytes / (1024 * 1024)).ToString("#.0") + " MBps"; } return (_bytes / (1024 * 1024 * 1024)).ToString("#.0") + " GBpS"; } private void CalcSpeed() { if (last_rec > Services.Memory.DataRec) { last_rec = Services.Memory.DataRec; } if (last_sent > Services.Memory.DataSent) { last_sent = Services.Memory.DataSent; } var send_speed = (Services.Memory.DataSent - last_sent) * 2; // read each half second var rec_speed = (Services.Memory.DataRec - last_rec) * 2;// read each half second last_rec = Services.Memory.DataRec; last_sent = Services.Memory.DataSent; lblDataSent.Text = GetBytesSpeed(send_speed); lblDataRec.Text = GetBytesSpeed(rec_speed); } private void LoadConfig() { Services.Config.Load(); txtServerIP.Text = Services.Config.CloudServer; txtPort.Text = Services.Config.CloudPort; txtPassword.Text = Services.Config.Password; txtEndpointServer.Text = Services.Config.EndpointServer; txtEndpointPort.Text = Services.Config.EndpointPort; cbAutoconnect.Checked = Services.Config.Autoconnect; } private void SaveConfig() { Services.Config.CloudServer = txtServerIP.Text; Services.Config.CloudPort = txtPort.Text; Services.Config.Password = txtPassword.Text; Services.Config.EndpointServer= txtEndpointServer.Text; Services.Config.EndpointPort = txtEndpointPort.Text; Services.Config.Save(); } private void groupBox2_Enter(object sender, EventArgs e) { } private void btnStartStop_Click(object sender, EventArgs e) { switch (btnStartStop.Text) { case "Start": Services.Config.StartProcess(); isUsetStop = false; break; case "Stop": isUsetStop = true; Services.Config.StopProcess(); break; default: break; } } private void btnSave_Click(object sender, EventArgs e) { SaveConfig(); } private void btnClose_Click(object sender, EventArgs e) { Close(); } private void cbAutoconnect_CheckedChanged(object sender, EventArgs e) { try { Services.Config.Autoconnect = cbAutoconnect.Checked; Services.Config.Save(); } catch { } } } }
29.811321
130
0.497943
[ "Unlicense" ]
ahmed-eg/Cloud-port-forward
ManagementAgent/MainForm.cs
6,322
C#
//////////////////////////////////////////////////////////////////////////////// //NUnit tests for "EF Core Provider for LCPI OLE DB" // IBProvider and Contributors. 09.04.2021. using System; using System.Data; 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.Operators.SET_002__AS_STR.Divide.Complete.Double.NullableDouble{ //////////////////////////////////////////////////////////////////////////////// using T_DATA1 =System.Double; using T_DATA2 =System.Nullable<System.Double>; //////////////////////////////////////////////////////////////////////////////// //class TestSet_6VN00__param public static class TestSet_6VN00__param { private const string c_NameOf__TABLE ="DUAL"; private sealed class MyContext:TestBaseDbContext { [Table(c_NameOf__TABLE)] public sealed class TEST_RECORD { [Key] [Column("ID")] public System.Int32? TEST_ID { 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)) { T_DATA1 vv1=7; T_DATA2 vv2=null; var recs=db.testTable.Where(r => (string)(object)(vv1/vv2)==null); int nRecs=0; foreach(var r in recs) { Assert.AreEqual (0, nRecs); ++nRecs; Assert.IsTrue (r.TEST_ID.HasValue); Assert.AreEqual (1, r.TEST_ID.Value); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("d","ID").EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL() .T("WHERE ").P_BOOL("__Exec_V_V_0")); Assert.AreEqual (1, nRecs); }//using db tr.Commit(); }//using tr }//using cn }//Test_001 };//class TestSet_6VN00__param //////////////////////////////////////////////////////////////////////////////// }//namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D1.Query.Operators.SET_002__AS_STR.Divide.Complete.Double.NullableDouble
26.825243
143
0.533478
[ "MIT" ]
ibprovider/Lcpi.EFCore.LcpiOleDb
Tests/General/Source/Work/DBMS/Firebird/V03_0_0/D1/Query/Operators/SET_002__AS_STR/Divide/Complete/Double/NullableDouble/TestSet_6VN00__param.cs
2,765
C#
using System; using System.Collections; using System.Collections.Generic; using System.Reflection; namespace ServiceStack.Text.Common { internal class JsReader<TSerializer> where TSerializer : ITypeSerializer { private static readonly ITypeSerializer Serializer = JsWriter.GetTypeSerializer<TSerializer>(); public ParseStringDelegate GetParseFn<T>() { var type = Nullable.GetUnderlyingType(typeof(T)) ?? typeof(T); if (type.GetTypeInfo().IsEnum) { return x => EnumUtils.Parse<T>(x, true); } if (type == typeof(string)) return Serializer.ParseString; if (type == typeof(object)) return DeserializeType<TSerializer>.ObjectStringToType; var specialParseFn = ParseUtils.GetSpecialParseMethod(type); if (specialParseFn != null) return specialParseFn; if (type.IsArray) { return DeserializeArray<T, TSerializer>.Parse; } var builtInMethod = DeserializeBuiltin<T>.Parse; if (builtInMethod != null) return value => builtInMethod(Serializer.ParseRawString(value)); if (JsConfig<T>.SerializeFn != null) return value => JsConfig<T>.ParseFn(Serializer.ParseRawString(value)); if (type.IsGenericType()) { if (type.IsOrHasGenericInterfaceTypeOf(typeof(IList<>))) return DeserializeList<T, TSerializer>.Parse; if (type.IsOrHasGenericInterfaceTypeOf(typeof(IDictionary<,>))) return DeserializeDictionary<TSerializer>.GetParseMethod(type); if (type.IsOrHasGenericInterfaceTypeOf(typeof(ICollection<>))) return DeserializeCollection<TSerializer>.GetParseMethod(type); if (type.HasAnyTypeDefinitionsOf(typeof(Queue<>)) || type.HasAnyTypeDefinitionsOf(typeof(Stack<>))) return DeserializeSpecializedCollections<T, TSerializer>.Parse; if (type.IsOrHasGenericInterfaceTypeOf(typeof(IEnumerable<>))) return DeserializeEnumerable<T, TSerializer>.Parse; } var isCollection = typeof(T).IsOrHasGenericInterfaceTypeOf(typeof(ICollection)); if (isCollection) { var isDictionary = typeof(T).IsAssignableFrom(typeof(IDictionary)) || typeof(T).HasInterface(typeof(IDictionary)); if (isDictionary) { return DeserializeDictionary<TSerializer>.GetParseMethod(type); } return DeserializeEnumerable<T, TSerializer>.Parse; } var isEnumerable = typeof(T).IsAssignableFrom(typeof(IEnumerable)) || typeof(T).HasInterface(typeof(IEnumerable)); if (isEnumerable) { var parseFn = DeserializeSpecializedCollections<T, TSerializer>.Parse; if (parseFn != null) return parseFn; } if (type.GetTypeInfo().IsValueType) { var staticParseMethod = StaticParseMethod<T>.Parse; if (staticParseMethod != null) return value => staticParseMethod(Serializer.ParseRawString(value)); } else { var staticParseMethod = StaticParseRefTypeMethod<TSerializer, T>.Parse; if (staticParseMethod != null) return value => staticParseMethod(Serializer.ParseRawString(value)); } var typeConstructor = DeserializeType<TSerializer>.GetParseMethod(TypeConfig<T>.GetState()); if (typeConstructor != null) return typeConstructor; var stringConstructor = DeserializeTypeUtils.GetParseMethod(type); if (stringConstructor != null) return stringConstructor; return DeserializeType<TSerializer>.ParseAbstractType<T>; } } }
31.587156
98
0.708103
[ "BSD-3-Clause" ]
scopely/ServiceStack.Text
src/ServiceStack.Text/Common/JsReader.cs
3,443
C#
using DanpheEMR.Core.Parameters; using DanpheEMR.ServerModel; using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DanpheEMR.DalLayer { public class MaternityDbContext : DbContext { public DbSet<PatientModel> Patients { get; set; } public DbSet<AdminParametersModel> AdminParameters { get; set; } public DbSet<EmployeeModel> Employee { get; set; } public DbSet<CountrySubDivisionModel> CountrySubdivisions { get; set; } public DbSet<MaternityPatient> MaternityPatients { get; set; } public DbSet<MaternityRegister> MaternityRegister { get; set; } public DbSet<MaternityANC> MaternityANC { get; set; } public DbSet<MaternityFileUploads> MaternityFiles { get; set; } public DbSet<MaternityPayment> MaternityPatientPayments { get; set; } public DbSet<BillingFiscalYear> BillingFiscalYears { get; set; } public DbSet<EmpCashTransactionModel> EmpCashTransactions { get; set; } public MaternityDbContext(string conn) : base(conn) { this.Configuration.LazyLoadingEnabled = true; this.Configuration.ProxyCreationEnabled = false; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<PatientModel>().ToTable("PAT_Patient"); modelBuilder.Entity<AdminParametersModel>().ToTable("CORE_CFG_Parameters"); modelBuilder.Entity<EmployeeModel>().ToTable("EMP_Employee"); modelBuilder.Entity<CountrySubDivisionModel>().ToTable("MST_CountrySubDivision"); modelBuilder.Entity<MaternityPatient>().ToTable("MAT_Patient"); modelBuilder.Entity<MaternityRegister>().ToTable("MAT_Register"); modelBuilder.Entity<MaternityANC>().ToTable("MAT_MaternityANC"); modelBuilder.Entity<MaternityFileUploads>().ToTable("MAT_FileUploads"); modelBuilder.Entity<MaternityPayment>().ToTable("MAT_TXN_PatientPayments"); modelBuilder.Entity<BillingFiscalYear>().ToTable("BIL_CFG_FiscalYears"); modelBuilder.Entity<EmpCashTransactionModel>().ToTable("TXN_EmpCashTransaction"); } } }
43.207547
93
0.703493
[ "MIT" ]
MenkaChaugule/hospital-management-emr
Code/Components/DanpheEMR.DalLayer/MaternityDbContext.cs
2,292
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Runtime.CompilerServices; using Tesseract.Core.Native; using Tesseract.OpenGL.Native; namespace Tesseract.OpenGL { public class GL15 : GL14 { public GL15Functions FunctionsGL15 { get; } = new(); public GL15(GL gl, IGLContext context) : base(gl, context) { Library.LoadFunctions(context.GetGLProcAddress, FunctionsGL15); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void BeginQuery(GLQueryTarget target, uint id) => FunctionsGL15.glBeginQuery((uint)target, id); [MethodImpl(MethodImplOptions.AggressiveInlining)] public void BindBuffer(GLBufferTarget target, uint id) => FunctionsGL15.glBindBuffer((uint)target, id); [MethodImpl(MethodImplOptions.AggressiveInlining)] public void BufferData(GLBufferTarget target, nint size, IntPtr data, GLBufferUsage usage) => FunctionsGL15.glBufferData((uint)target, size, data, (uint)usage); [MethodImpl(MethodImplOptions.AggressiveInlining)] public void BufferData<T>(GLBufferTarget target, GLBufferUsage usage, in ReadOnlySpan<T> data) where T : unmanaged { unsafe { fixed(T* pData = data) { BufferData(target, (IntPtr)(data.Length * sizeof(T)), (IntPtr)pData, usage); } } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void BufferData<T>(GLBufferTarget target, GLBufferUsage usage, params T[] data) where T : unmanaged { unsafe { fixed (T* pData = data) { BufferData(target, (IntPtr)(data.Length * sizeof(T)), (IntPtr)pData, usage); } } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void BufferSubData(GLBufferTarget target, nint offset, nint size, IntPtr data) => FunctionsGL15.glBufferSubData((uint)target, offset, size, data); [MethodImpl(MethodImplOptions.AggressiveInlining)] public void BufferSubData<T>(GLBufferTarget target, nint offset, in ReadOnlySpan<T> data) where T : unmanaged { unsafe { fixed (T* pData = data) { BufferSubData(target, offset, data.Length * (nint)sizeof(T), (IntPtr)pData); } } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void BufferSubData<T>(GLBufferTarget target, nint offset, params T[] data) where T : unmanaged { unsafe { fixed (T* pData = data) { BufferSubData(target, offset, data.Length * (nint)sizeof(T), (IntPtr)pData); } } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void DeleteBuffers(int n, IntPtr buffers) => FunctionsGL15.glDeleteBuffers(n, buffers); [MethodImpl(MethodImplOptions.AggressiveInlining)] public void DeleteBuffers(in ReadOnlySpan<uint> buffers) { unsafe { fixed(uint* pBuffers = buffers) { FunctionsGL15.glDeleteBuffers(buffers.Length, (IntPtr)pBuffers); } } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void DeleteBuffers(params uint[] buffers) { unsafe { fixed (uint* pBuffers = buffers) { FunctionsGL15.glDeleteBuffers(buffers.Length, (IntPtr)pBuffers); } } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void DeleteBuffers(uint buffer) { unsafe { FunctionsGL15.glDeleteBuffers(1, (IntPtr)(&buffer)); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void DeleteQueries(int n, IntPtr ids) => FunctionsGL15.glDeleteQueries(n, ids); [MethodImpl(MethodImplOptions.AggressiveInlining)] public void DeleteQueries(in ReadOnlySpan<uint> ids) { unsafe { fixed (uint* pIds = ids) { FunctionsGL15.glDeleteQueries(ids.Length, (IntPtr)pIds); } } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void DeleteQueries(params uint[] ids) { unsafe { fixed (uint* pIds = ids) { FunctionsGL15.glDeleteQueries(ids.Length, (IntPtr)pIds); } } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void DeleteQueries(uint query) { unsafe { FunctionsGL15.glDeleteQueries(1, (IntPtr)(&query)); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void EndQuery(GLQueryTarget target) => FunctionsGL15.glEndQuery((uint)target); [MethodImpl(MethodImplOptions.AggressiveInlining)] public void GenBuffers(int n, IntPtr buffers) => FunctionsGL15.glGenBuffers(n, buffers); [MethodImpl(MethodImplOptions.AggressiveInlining)] public Span<uint> GenBuffers(in Span<uint> buffers) { unsafe { fixed (uint* pBuffers = buffers) { FunctionsGL15.glGenBuffers(buffers.Length, (IntPtr)pBuffers); } } return buffers; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public uint[] GenBuffers(int n) { uint[] buffers = new uint[n]; unsafe { fixed (uint* pBuffers = buffers) { FunctionsGL15.glGenBuffers(buffers.Length, (IntPtr)pBuffers); } } return buffers; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public uint GenBuffers() => GenBuffers(stackalloc uint[1])[0]; [MethodImpl(MethodImplOptions.AggressiveInlining)] public void GenQueries(int n, IntPtr ids) => FunctionsGL15.glGenQueries(n, ids); [MethodImpl(MethodImplOptions.AggressiveInlining)] public Span<uint> GenQueries(in Span<uint> ids) { unsafe { fixed (uint* pIds = ids) { FunctionsGL15.glGenQueries(ids.Length, (IntPtr)pIds); } } return ids; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public uint[] GenQueries(int n) { uint[] ids = new uint[n]; unsafe { fixed (uint* pIds = ids) { FunctionsGL15.glGenQueries(n, (IntPtr)pIds); } } return ids; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public uint GenQueries() => GenQueries(stackalloc uint[1])[0]; [MethodImpl(MethodImplOptions.AggressiveInlining)] public int GetBufferParameteri(GLBufferTarget target, GLGetBufferParameter pname) { unsafe { int param = 0; FunctionsGL15.glGetBufferParameteriv((uint)target, (uint)pname, (IntPtr)(&param)); return param; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public IntPtr GetBufferPointer(GLBufferTarget target, GLGetBufferPointer pname) { unsafe { IntPtr param = IntPtr.Zero; FunctionsGL15.glGetBufferPointerv((uint)target, (uint)pname, (IntPtr)(&param)); return param; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void GetBufferSubData(GLBufferTarget target, nint offset, nint size, IntPtr data) => FunctionsGL15.glGetBufferSubData((uint)target, offset, size, data); [MethodImpl(MethodImplOptions.AggressiveInlining)] public Span<T> GetBufferSubData<T>(GLBufferTarget target, nint offset, in Span<T> data) where T : unmanaged { unsafe { fixed(T* pData = data) { FunctionsGL15.glGetBufferSubData((uint)target, offset, (nint)sizeof(T) * data.Length, (IntPtr)pData); } } return data; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public T[] GetBufferSubData<T>(GLBufferTarget target, nint offset, T[] data) where T : unmanaged { unsafe { fixed (T* pData = data) { FunctionsGL15.glGetBufferSubData((uint)target, offset, (nint)sizeof(T) * data.Length, (IntPtr)pData); } } return data; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public T[] GetBufferSubData<T>(GLBufferTarget target, nint offset, int count) where T : unmanaged => GetBufferSubData(target, offset, new T[count]); [MethodImpl(MethodImplOptions.AggressiveInlining)] public int GetQueryObjecti(uint id, GLGetQueryObject pname) { unsafe { int value = 0; FunctionsGL15.glGetQueryObjectiv(id, (uint)pname, (IntPtr)(&value)); return value; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void GetQueryObjecti(uint id, GLGetQueryObject pname, nint offset) => FunctionsGL15.glGetQueryObjectiv(id, (uint)pname, offset); [MethodImpl(MethodImplOptions.AggressiveInlining)] public uint GetQueryObjectui(uint id, GLGetQueryObject pname) { unsafe { uint value = 0; FunctionsGL15.glGetQueryObjectuiv(id, (uint)pname, (IntPtr)(&value)); return value; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void GetQueryObjectui(uint id, GLGetQueryObject pname, nint offset) => FunctionsGL15.glGetQueryObjectuiv(id, (uint)pname, offset); [MethodImpl(MethodImplOptions.AggressiveInlining)] public int GetQueryi(GLGetQueryTarget target, GLGetQuery pname) { unsafe { int value = 0; FunctionsGL15.glGetQueryiv((uint)target, (uint)pname, (IntPtr)(&value)); return value; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool IsBuffer(uint buffer) => FunctionsGL15.glIsBuffer(buffer) != 0; [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool IsQuery(uint id) => FunctionsGL15.glIsQuery(id) != 0; [MethodImpl(MethodImplOptions.AggressiveInlining)] public IntPtr MapBuffer(GLBufferTarget target, GLAccess access) => FunctionsGL15.glMapBuffer((uint)target, (uint)access); [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool UnmapBuffer(GLBufferTarget target) => FunctionsGL15.glUnmapBuffer((uint)target) != 0; } }
33.518382
162
0.729955
[ "Apache-2.0" ]
Zekrom64/TesseractEngine
TesseractEngine-GL/OpenGL/GL15.cs
9,119
C#
using Autofac; using ExchangeRates.Domain.Services; using ExchangeRates.Services.Factories; using ExchangeRates.Services.Services; namespace ExchangeRates.Binder.Modules { public class ServicesModule : Module { protected override void Load(ContainerBuilder builder) { builder.RegisterType<CurrencyService>().As<ICurrencyService>(); builder.RegisterType<HttpClientFactory>(); } } }
24.666667
75
0.709459
[ "MIT" ]
zbigniewmarszolik/ExchangeRates
ExchangeRates/ExchangeRates.Binder/Modules/ServicesModule.cs
446
C#
using System; using System.Collections.Generic; namespace ManualDi.Main.Disposing { public class BindingDisposer : IBindingDisposer { private readonly List<Action> disposeActions = new List<Action>(); private bool disposing = false; public void QueueDispose(Action disposeAction) { if (disposing) { throw new InvalidOperationException( "Tried to register a dispose action while disposing" ); } disposeActions.Add(disposeAction); } public void DisposeAll() { disposing = true; foreach (Action action in disposeActions) { action.Invoke(); } disposing = false; disposeActions.Clear(); } } }
23.153846
75
0.509413
[ "MIT" ]
GabLeRoux/ManualDi.Main
ManualDi.Main/Disposing/BindingDisposer.cs
905
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Runtime.ExceptionServices; using System.Text; using System.Threading; using System.Threading.Tasks; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using NuGet.Commands; using NuGet.Common; using NuGet.Configuration; using NuGet.Frameworks; using NuGet.Packaging; using NuGet.Packaging.Core; using NuGet.ProjectManagement; using NuGet.ProjectManagement.Projects; using NuGet.ProjectModel; using NuGet.Protocol; using NuGet.Protocol.Core.Types; using NuGet.Resolver; using NuGet.Versioning; namespace NuGet.PackageManagement { /// <summary> /// NuGetPackageManager orchestrates a nuget package operation such as an install or uninstall /// It is to be called by various NuGet Clients including the custom third-party ones /// </summary> public class NuGetPackageManager { private IReadOnlyList<SourceRepository> _globalPackageFolderRepositories; private ISourceRepositoryProvider SourceRepositoryProvider { get; } private ISolutionManager SolutionManager { get; } private Configuration.ISettings Settings { get; } public IDeleteOnRestartManager DeleteOnRestartManager { get; } public FolderNuGetProject PackagesFolderNuGetProject { get; set; } public SourceRepository PackagesFolderSourceRepository { get; set; } public IInstallationCompatibility InstallationCompatibility { get; set; } /// <summary> /// Event to be raised when batch processing of install/ uninstall packages starts at a project level /// </summary> public event EventHandler<PackageProjectEventArgs> BatchStart; /// <summary> /// Event to be raised when batch processing of install/ uninstall packages ends at a project level /// </summary> public event EventHandler<PackageProjectEventArgs> BatchEnd; /// <summary> /// To construct a NuGetPackageManager that does not need a SolutionManager like NuGet.exe /// </summary> public NuGetPackageManager( ISourceRepositoryProvider sourceRepositoryProvider, Configuration.ISettings settings, string packagesFolderPath) : this(sourceRepositoryProvider, settings, packagesFolderPath, excludeVersion: false) { } public NuGetPackageManager( ISourceRepositoryProvider sourceRepositoryProvider, Configuration.ISettings settings, string packagesFolderPath, bool excludeVersion) { if (sourceRepositoryProvider == null) { throw new ArgumentNullException(nameof(sourceRepositoryProvider)); } if (settings == null) { throw new ArgumentNullException(nameof(settings)); } if (packagesFolderPath == null) { throw new ArgumentNullException(nameof(packagesFolderPath)); } SourceRepositoryProvider = sourceRepositoryProvider; Settings = settings; InstallationCompatibility = PackageManagement.InstallationCompatibility.Instance; InitializePackagesFolderInfo(packagesFolderPath, excludeVersion); } /// <summary> /// To construct a NuGetPackageManager with a mandatory SolutionManager lke VS /// </summary> public NuGetPackageManager( ISourceRepositoryProvider sourceRepositoryProvider, Configuration.ISettings settings, ISolutionManager solutionManager, IDeleteOnRestartManager deleteOnRestartManager) : this(sourceRepositoryProvider, settings, solutionManager, deleteOnRestartManager, excludeVersion: false) { } public NuGetPackageManager( ISourceRepositoryProvider sourceRepositoryProvider, Configuration.ISettings settings, ISolutionManager solutionManager, IDeleteOnRestartManager deleteOnRestartManager, bool excludeVersion) { if (sourceRepositoryProvider == null) { throw new ArgumentNullException(nameof(sourceRepositoryProvider)); } if (settings == null) { throw new ArgumentNullException(nameof(settings)); } if (solutionManager == null) { throw new ArgumentNullException(nameof(solutionManager)); } if (deleteOnRestartManager == null) { throw new ArgumentNullException(nameof(deleteOnRestartManager)); } SourceRepositoryProvider = sourceRepositoryProvider; Settings = settings; SolutionManager = solutionManager; InstallationCompatibility = PackageManagement.InstallationCompatibility.Instance; InitializePackagesFolderInfo(PackagesFolderPathUtility.GetPackagesFolderPath(SolutionManager, Settings), excludeVersion); DeleteOnRestartManager = deleteOnRestartManager; } /// <summary> /// SourceRepositories for the user global package folder and all fallback package folders. /// </summary> public IReadOnlyList<SourceRepository> GlobalPackageFolderRepositories { get { if (_globalPackageFolderRepositories == null) { var sources = new List<SourceRepository>(); // Read package folders from settings var pathContext = NuGetPathContext.Create(Settings); var folders = new List<string>(); folders.Add(pathContext.UserPackageFolder); folders.AddRange(pathContext.FallbackPackageFolders); foreach (var folder in folders) { // Create a repo for each folder var source = SourceRepositoryProvider.CreateRepository( new PackageSource(folder), FeedType.FileSystemV3); sources.Add(source); } _globalPackageFolderRepositories = sources; } return _globalPackageFolderRepositories; } } private void InitializePackagesFolderInfo(string packagesFolderPath, bool excludeVersion = false) { // FileSystemPackagesConfig supports id.version formats, if the version is excluded use the normal v2 format var feedType = excludeVersion ? FeedType.FileSystemV2 : FeedType.FileSystemPackagesConfig; PackagesFolderNuGetProject = new FolderNuGetProject(packagesFolderPath, excludeVersion); // Capturing it locally is important since it allows for the instance to cache packages for the lifetime // of the closure \ NuGetPackageManager. PackagesFolderSourceRepository = SourceRepositoryProvider.CreateRepository( new PackageSource(packagesFolderPath), feedType); } /// <summary> /// Installs the latest version of the given <paramref name="packageId" /> to NuGetProject /// <paramref name="nuGetProject" /> <paramref name="resolutionContext" /> and /// <paramref name="nuGetProjectContext" /> are used in the process. /// </summary> public Task InstallPackageAsync(NuGetProject nuGetProject, string packageId, ResolutionContext resolutionContext, INuGetProjectContext nuGetProjectContext, SourceRepository primarySourceRepository, IEnumerable<SourceRepository> secondarySources, CancellationToken token) { return InstallPackageAsync(nuGetProject, packageId, resolutionContext, nuGetProjectContext, new List<SourceRepository> { primarySourceRepository }, secondarySources, token); } /// <summary> /// Installs the latest version of the given /// <paramref name="packageId" /> to NuGetProject <paramref name="nuGetProject" /> /// <paramref name="resolutionContext" /> and <paramref name="nuGetProjectContext" /> are used in the process. /// </summary> public async Task InstallPackageAsync(NuGetProject nuGetProject, string packageId, ResolutionContext resolutionContext, INuGetProjectContext nuGetProjectContext, IEnumerable<SourceRepository> primarySources, IEnumerable<SourceRepository> secondarySources, CancellationToken token) { var log = new LoggerAdapter(nuGetProjectContext); // Step-1 : Get latest version for packageId var latestVersion = await GetLatestVersionAsync( packageId, nuGetProject, resolutionContext, primarySources, log, token); if (latestVersion == null) { throw new InvalidOperationException(string.Format(Strings.NoLatestVersionFound, packageId)); } // Step-2 : Call InstallPackageAsync(project, packageIdentity) await InstallPackageAsync(nuGetProject, new PackageIdentity(packageId, latestVersion), resolutionContext, nuGetProjectContext, primarySources, secondarySources, token); } /// <summary> /// Installs given <paramref name="packageIdentity" /> to NuGetProject <paramref name="nuGetProject" /> /// <paramref name="resolutionContext" /> and <paramref name="nuGetProjectContext" /> are used in the process. /// </summary> public Task InstallPackageAsync(NuGetProject nuGetProject, PackageIdentity packageIdentity, ResolutionContext resolutionContext, INuGetProjectContext nuGetProjectContext, SourceRepository primarySourceRepository, IEnumerable<SourceRepository> secondarySources, CancellationToken token) { return InstallPackageAsync(nuGetProject, packageIdentity, resolutionContext, nuGetProjectContext, new List<SourceRepository> { primarySourceRepository }, secondarySources, token); } /// <summary> /// Installs given <paramref name="packageIdentity" /> to NuGetProject <paramref name="nuGetProject" /> /// <paramref name="resolutionContext" /> and <paramref name="nuGetProjectContext" /> are used in the process. /// </summary> public async Task InstallPackageAsync(NuGetProject nuGetProject, PackageIdentity packageIdentity, ResolutionContext resolutionContext, INuGetProjectContext nuGetProjectContext, IEnumerable<SourceRepository> primarySources, IEnumerable<SourceRepository> secondarySources, CancellationToken token) { ActivityCorrelationContext.StartNew(); // Step-1 : Call PreviewInstallPackageAsync to get all the nuGetProjectActions var nuGetProjectActions = await PreviewInstallPackageAsync(nuGetProject, packageIdentity, resolutionContext, nuGetProjectContext, primarySources, secondarySources, token); SetDirectInstall(packageIdentity, nuGetProjectContext); // Step-2 : Execute all the nuGetProjectActions await ExecuteNuGetProjectActionsAsync(nuGetProject, nuGetProjectActions, nuGetProjectContext, token); ClearDirectInstall(nuGetProjectContext); } public async Task UninstallPackageAsync(NuGetProject nuGetProject, string packageId, UninstallationContext uninstallationContext, INuGetProjectContext nuGetProjectContext, CancellationToken token) { ActivityCorrelationContext.StartNew(); // Step-1 : Call PreviewUninstallPackagesAsync to get all the nuGetProjectActions var nuGetProjectActions = await PreviewUninstallPackageAsync(nuGetProject, packageId, uninstallationContext, nuGetProjectContext, token); // Step-2 : Execute all the nuGetProjectActions await ExecuteNuGetProjectActionsAsync(nuGetProject, nuGetProjectActions, nuGetProjectContext, token); } /// <summary> /// Gives the preview as a list of NuGetProjectActions that will be performed to install /// <paramref name="packageId" /> into <paramref name="nuGetProject" /> <paramref name="resolutionContext" /> /// and <paramref name="nuGetProjectContext" /> are used in the process. /// </summary> public Task<IEnumerable<NuGetProjectAction>> PreviewInstallPackageAsync( NuGetProject nuGetProject, string packageId, ResolutionContext resolutionContext, INuGetProjectContext nuGetProjectContext, SourceRepository primarySourceRepository, IEnumerable<SourceRepository> secondarySources, CancellationToken token) { return PreviewInstallPackageAsync(nuGetProject, packageId, resolutionContext, nuGetProjectContext, new[] { primarySourceRepository }, secondarySources, token); } /// <summary> /// Gives the preview as a list of NuGetProjectActions that will be performed to install /// <paramref name="packageId" /> into <paramref name="nuGetProject" /> <paramref name="resolutionContext" /> /// and <paramref name="nuGetProjectContext" /> are used in the process. /// </summary> public async Task<IEnumerable<NuGetProjectAction>> PreviewInstallPackageAsync( NuGetProject nuGetProject, string packageId, ResolutionContext resolutionContext, INuGetProjectContext nuGetProjectContext, IEnumerable<SourceRepository> primarySources, IEnumerable<SourceRepository> secondarySources, CancellationToken token) { if (nuGetProject == null) { throw new ArgumentNullException(nameof(nuGetProject)); } if (packageId == null) { throw new ArgumentNullException(nameof(packageId)); } if (resolutionContext == null) { throw new ArgumentNullException(nameof(resolutionContext)); } if (nuGetProjectContext == null) { throw new ArgumentNullException(nameof(nuGetProjectContext)); } var log = new LoggerAdapter(nuGetProjectContext); // Step-1 : Get latest version for packageId var latestVersion = await GetLatestVersionAsync( packageId, nuGetProject, resolutionContext, primarySources, log, token); if (latestVersion == null) { throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Strings.UnknownPackage, packageId)); } var projectInstalledPackageReferences = await nuGetProject.GetInstalledPackagesAsync(token); var installedPackageReference = projectInstalledPackageReferences.Where(pr => StringComparer.OrdinalIgnoreCase.Equals(pr.PackageIdentity.Id, packageId)).FirstOrDefault(); if (installedPackageReference != null && installedPackageReference.PackageIdentity.Version > latestVersion) { throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Strings.NewerVersionAlreadyReferenced, packageId)); } // Step-2 : Call InstallPackage(project, packageIdentity) return await PreviewInstallPackageAsync(nuGetProject, new PackageIdentity(packageId, latestVersion), resolutionContext, nuGetProjectContext, primarySources, secondarySources, token); } public Task<IEnumerable<NuGetProjectAction>> PreviewUpdatePackagesAsync( NuGetProject nuGetProject, ResolutionContext resolutionContext, INuGetProjectContext nuGetProjectContext, IEnumerable<SourceRepository> primarySources, IEnumerable<SourceRepository> secondarySources, CancellationToken token) { return PreviewUpdatePackagesAsync( packageId: null, packageIdentities: new List<PackageIdentity>(), nuGetProject: nuGetProject, resolutionContext: resolutionContext, nuGetProjectContext: nuGetProjectContext, primarySources: primarySources, secondarySources: secondarySources, token: token); } public Task<IEnumerable<NuGetProjectAction>> PreviewUpdatePackagesAsync( string packageId, NuGetProject nuGetProject, ResolutionContext resolutionContext, INuGetProjectContext nuGetProjectContext, IEnumerable<SourceRepository> primarySources, IEnumerable<SourceRepository> secondarySources, CancellationToken token) { return PreviewUpdatePackagesAsync( packageId: packageId, packageIdentities: new List<PackageIdentity>(), nuGetProject: nuGetProject, resolutionContext: resolutionContext, nuGetProjectContext: nuGetProjectContext, primarySources: primarySources, secondarySources: secondarySources, token: token); } public Task<IEnumerable<NuGetProjectAction>> PreviewUpdatePackagesAsync( PackageIdentity packageIdentity, NuGetProject nuGetProject, ResolutionContext resolutionContext, INuGetProjectContext nuGetProjectContext, IEnumerable<SourceRepository> primarySources, IEnumerable<SourceRepository> secondarySources, CancellationToken token) { return PreviewUpdatePackagesAsync( packageId: null, packageIdentities: new List<PackageIdentity> { packageIdentity }, nuGetProject: nuGetProject, resolutionContext: resolutionContext, nuGetProjectContext: nuGetProjectContext, primarySources: primarySources, secondarySources: secondarySources, token: token); } public Task<IEnumerable<NuGetProjectAction>> PreviewUpdatePackagesAsync( List<PackageIdentity> packageIdentities, NuGetProject nuGetProject, ResolutionContext resolutionContext, INuGetProjectContext nuGetProjectContext, IEnumerable<SourceRepository> primarySources, IEnumerable<SourceRepository> secondarySources, CancellationToken token) { return PreviewUpdatePackagesAsync( packageId: null, packageIdentities: packageIdentities, nuGetProject: nuGetProject, resolutionContext: resolutionContext, nuGetProjectContext: nuGetProjectContext, primarySources: primarySources, secondarySources: secondarySources, token: token); } private async Task<IEnumerable<NuGetProjectAction>> PreviewUpdatePackagesAsync( string packageId, List<PackageIdentity> packageIdentities, NuGetProject nuGetProject, ResolutionContext resolutionContext, INuGetProjectContext nuGetProjectContext, IEnumerable<SourceRepository> primarySources, IEnumerable<SourceRepository> secondarySources, CancellationToken token) { if (nuGetProject == null) { throw new ArgumentNullException(nameof(nuGetProject)); } if (resolutionContext == null) { throw new ArgumentNullException(nameof(resolutionContext)); } if (nuGetProjectContext == null) { throw new ArgumentNullException(nameof(nuGetProjectContext)); } if (primarySources == null) { throw new ArgumentNullException(nameof(primarySources)); } if (secondarySources == null) { throw new ArgumentNullException(nameof(secondarySources)); } if (nuGetProject is INuGetIntegratedProject) { // project.json based projects are handled here return await PreviewUpdatePackagesForBuildIntegratedAsync( packageId, packageIdentities, nuGetProject, resolutionContext, nuGetProjectContext, primarySources, secondarySources, token); } else { // otherwise classic style packages.config style projects are handled here return await PreviewUpdatePackagesForClassicAsync( packageId, packageIdentities, nuGetProject, resolutionContext, nuGetProjectContext, primarySources, secondarySources, token); } } /// <summary> /// Update Package logic specific to build integrated style NuGet projects /// </summary> private async Task<IEnumerable<NuGetProjectAction>> PreviewUpdatePackagesForBuildIntegratedAsync( string packageId, List<PackageIdentity> packageIdentities, NuGetProject nuGetProject, ResolutionContext resolutionContext, INuGetProjectContext nuGetProjectContext, IEnumerable<SourceRepository> primarySources, IEnumerable<SourceRepository> secondarySources, CancellationToken token) { var projectInstalledPackageReferences = await nuGetProject.GetInstalledPackagesAsync(token); var log = new LoggerAdapter(nuGetProjectContext); var actions = new List<NuGetProjectAction>(); if (packageIdentities.Count == 0 && packageId == null) { // Update-Package all //TODO: need to consider whether Update ALL simply does nothing for Build Integrated projects var lowLevelActions = new List<NuGetProjectAction>(); foreach (var installedPackage in projectInstalledPackageReferences) { NuGetVersion latestVersion = await GetLatestVersionAsync( installedPackage.PackageIdentity.Id, nuGetProject, resolutionContext, primarySources, log, token); if (latestVersion != null && latestVersion > installedPackage.PackageIdentity.Version) { lowLevelActions.Add(NuGetProjectAction.CreateUninstallProjectAction(installedPackage.PackageIdentity)); lowLevelActions.Add(NuGetProjectAction.CreateInstallProjectAction( new PackageIdentity(installedPackage.PackageIdentity.Id, latestVersion), primarySources.FirstOrDefault())); } } // If the update operation is a no-op there will be no project actions. if (lowLevelActions.Any()) { var buildIntegratedProject = nuGetProject as BuildIntegratedNuGetProject; if (buildIntegratedProject != null) { // Create a build integrated action var buildIntegratedAction = await PreviewBuildIntegratedProjectActionsAsync(buildIntegratedProject, lowLevelActions, nuGetProjectContext, token); actions.Add(buildIntegratedAction); } else { // Use the low level actions for projectK actions = lowLevelActions; } } } else { // either we have a packageId or a list of specific PackageIdentities to work with // first lets normalize this input so we are just dealing with a list if (packageIdentities.Count == 0) { NuGetVersion latestVersion = await GetLatestVersionAsync( packageId, nuGetProject, resolutionContext, primarySources, log, token); if (latestVersion == null) { throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Strings.UnknownPackage, packageId)); } var installedPackageReference = projectInstalledPackageReferences .Where(pr => StringComparer.OrdinalIgnoreCase.Equals(pr.PackageIdentity.Id, packageId)) .FirstOrDefault(); if (installedPackageReference.PackageIdentity.Version > latestVersion) { throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Strings.NewerVersionAlreadyReferenced, packageId)); } packageIdentities.Add(new PackageIdentity(packageId, latestVersion)); } // process the list of PackageIdentities var lowLevelActions = new List<NuGetProjectAction>(); foreach (var packageIdentity in packageIdentities) { var installed = projectInstalledPackageReferences .Where(pr => StringComparer.OrdinalIgnoreCase.Equals(pr.PackageIdentity.Id, packageIdentity.Id)) .FirstOrDefault(); // if the package is not currently installed ignore it if (installed != null) { lowLevelActions.Add(NuGetProjectAction.CreateUninstallProjectAction(installed.PackageIdentity)); lowLevelActions.Add(NuGetProjectAction.CreateInstallProjectAction(packageIdentity, primarySources.FirstOrDefault())); } } var buildIntegratedProject = nuGetProject as BuildIntegratedNuGetProject; if (buildIntegratedProject != null) { // Create a build integrated action var buildIntegratedAction = await PreviewBuildIntegratedProjectActionsAsync( buildIntegratedProject, lowLevelActions, nuGetProjectContext, token); actions.Add(buildIntegratedAction); } else { // Use the low level actions for projectK actions.AddRange(lowLevelActions); } } return actions; } /// <summary> /// Update Package logic specific to classic style NuGet projects /// </summary> private async Task<IEnumerable<NuGetProjectAction>> PreviewUpdatePackagesForClassicAsync( string packageId, List<PackageIdentity> packageIdentities, NuGetProject nuGetProject, ResolutionContext resolutionContext, INuGetProjectContext nuGetProjectContext, IEnumerable<SourceRepository> primarySources, IEnumerable<SourceRepository> secondarySources, CancellationToken token) { var log = new LoggerAdapter(nuGetProjectContext); var projectInstalledPackageReferences = await nuGetProject.GetInstalledPackagesAsync(token); var oldListOfInstalledPackages = projectInstalledPackageReferences.Select(p => p.PackageIdentity); bool isUpdateAll = (packageId == null && packageIdentities.Count == 0); var preferredVersions = new Dictionary<string, PackageIdentity>(StringComparer.OrdinalIgnoreCase); // By default we start by preferring everything we already have installed foreach (var installedPackage in oldListOfInstalledPackages) { preferredVersions[installedPackage.Id] = installedPackage; } var primaryTargetIds = Enumerable.Empty<string>(); var primaryTargets = Enumerable.Empty<PackageIdentity>(); // We have been given the exact PackageIdentities (id and version) to update to e.g. from PMC update-package -Id <id> -Version <version> if (packageIdentities.Count > 0) { primaryTargets = new List<PackageIdentity>(); primaryTargetIds = packageIdentities.Select(p => p.Id); // If we have been given explicit PackageIdentities to install then we will naturally prefer that foreach (var packageIdentity in packageIdentities) { // Just a check to make sure the preferredVersions created from the existing package list actually contains the target if (preferredVersions.ContainsKey(packageIdentity.Id)) { // If there was a version specified we will prefer that version if (packageIdentity.HasVersion) { preferredVersions[packageIdentity.Id] = packageIdentity; ((List<PackageIdentity>)primaryTargets).Add(packageIdentity); } // Otherwise we just have the Id and so we wil explicitly not prefer the one currently installed else { preferredVersions.Remove(packageIdentity.Id); } } } } // We have just been given the package id, in which case we will look for the highest version and attempt to move to that else if (packageId != null) { if (PrunePackageTree.IsExactVersion(resolutionContext.VersionConstraints)) { primaryTargets = new[] { preferredVersions[packageId] }; } else { primaryTargetIds = new[] { packageId }; // If we have been given just a package Id we certainly don't want the one installed - pruning will be significant preferredVersions.Remove(packageId); } } // We are apply update logic to the complete project - attempting to resolver all updates together else { primaryTargetIds = projectInstalledPackageReferences.Select(p => p.PackageIdentity.Id); // We are performing a global project-wide update - nothing is preferred - again pruning will be significant preferredVersions.Clear(); } // Note: resolver needs all the installed packages as targets too. And, metadata should be gathered for the installed packages as well var packageTargetIdsForResolver = new HashSet<string>(oldListOfInstalledPackages.Select(p => p.Id), StringComparer.OrdinalIgnoreCase); foreach (var packageIdToInstall in primaryTargetIds) { packageTargetIdsForResolver.Add(packageIdToInstall); } var projectName = NuGetProject.GetUniqueNameOrName(nuGetProject); var nuGetProjectActions = new List<NuGetProjectAction>(); if (!packageTargetIdsForResolver.Any()) { nuGetProjectContext.Log(NuGet.ProjectManagement.MessageLevel.Info, Strings.NoPackagesInProject, projectName); return nuGetProjectActions; } try { // If any targets are prerelease we should gather with prerelease on and filter afterwards var includePrereleaseInGather = resolutionContext.IncludePrerelease || (projectInstalledPackageReferences.Any(p => (p.PackageIdentity.HasVersion && p.PackageIdentity.Version.IsPrerelease))); // Create a modified resolution cache. This should include the same gather cache for multi-project // operations. var contextForGather = new ResolutionContext( resolutionContext.DependencyBehavior, includePrereleaseInGather, resolutionContext.IncludeUnlisted, VersionConstraints.None, resolutionContext.GatherCache); // Step-1 : Get metadata resources using gatherer var targetFramework = nuGetProject.GetMetadata<NuGetFramework>(NuGetProjectMetadataKeys.TargetFramework); nuGetProjectContext.Log(NuGet.ProjectManagement.MessageLevel.Info, Environment.NewLine); nuGetProjectContext.Log(NuGet.ProjectManagement.MessageLevel.Info, Strings.AttemptingToGatherDependencyInfoForMultiplePackages, projectName, targetFramework); var allSources = new List<SourceRepository>(primarySources); var primarySourcesSet = new HashSet<string>(primarySources.Select(s => s.PackageSource.Source)); foreach (var secondarySource in secondarySources) { if (!primarySourcesSet.Contains(secondarySource.PackageSource.Source)) { allSources.Add(secondarySource); } } // Unless the packageIdentity was explicitly asked for we should remove any potential downgrades var allowDowngrades = false; if (packageIdentities.Count == 1) { // Get installed package version var packageTargetsForResolver = new HashSet<PackageIdentity>(oldListOfInstalledPackages, PackageIdentity.Comparer); var installedPackageWithSameId = packageTargetsForResolver.Where(p => p.Id.Equals(packageIdentities[0].Id, StringComparison.OrdinalIgnoreCase)).FirstOrDefault(); if (installedPackageWithSameId != null) { if (installedPackageWithSameId.Version > packageIdentities[0].Version) { // Looks like the installed package is of higher version than one being installed. So, we take it that downgrade is allowed allowDowngrades = true; } } } var gatherContext = new GatherContext() { InstalledPackages = oldListOfInstalledPackages.ToList(), PrimaryTargetIds = primaryTargetIds.ToList(), PrimaryTargets = primaryTargets.ToList(), TargetFramework = targetFramework, PrimarySources = primarySources.ToList(), AllSources = allSources.ToList(), PackagesFolderSource = PackagesFolderSourceRepository, ResolutionContext = resolutionContext, AllowDowngrades = allowDowngrades, ProjectContext = nuGetProjectContext, IsUpdateAll = isUpdateAll }; var availablePackageDependencyInfoWithSourceSet = await ResolverGather.GatherAsync(gatherContext, token); if (!availablePackageDependencyInfoWithSourceSet.Any()) { throw new InvalidOperationException(Strings.UnableToGatherDependencyInfoForMultiplePackages); } // Update-Package ALL packages scenarios must always include the packages in the current project // Scenarios include: (1) a package havign been deleted from a feed (2) a source being removed from nuget config (3) an explicitly specified source if (isUpdateAll) { // BUG #1181 VS2015 : Updating from one feed fails for packages from different feed. DependencyInfoResource packagesFolderResource = await PackagesFolderSourceRepository.GetResourceAsync<DependencyInfoResource>(token); var packages = new List<SourcePackageDependencyInfo>(); foreach (var installedPackage in projectInstalledPackageReferences) { var packageInfo = await packagesFolderResource.ResolvePackage(installedPackage.PackageIdentity, targetFramework, log, token); if (packageInfo != null) { availablePackageDependencyInfoWithSourceSet.Add(packageInfo); } } } // Prune the results down to only what we would allow to be installed IEnumerable<SourcePackageDependencyInfo> prunedAvailablePackages = availablePackageDependencyInfoWithSourceSet; if (!resolutionContext.IncludePrerelease) { prunedAvailablePackages = PrunePackageTree.PrunePrereleaseExceptAllowed( prunedAvailablePackages, oldListOfInstalledPackages, isUpdateAll); } // Remove packages that do not meet the constraints specified in the UpdateConstrainst prunedAvailablePackages = PrunePackageTree.PruneByUpdateConstraints(prunedAvailablePackages, projectInstalledPackageReferences, resolutionContext.VersionConstraints); // Verify that the target is allowed by packages.config GatherExceptionHelpers.ThrowIfVersionIsDisallowedByPackagesConfig(primaryTargetIds, projectInstalledPackageReferences, prunedAvailablePackages, log); // Remove versions that do not satisfy 'allowedVersions' attribute in packages.config, if any prunedAvailablePackages = PrunePackageTree.PruneDisallowedVersions(prunedAvailablePackages, projectInstalledPackageReferences); // Remove all but the highest packages that are of the same Id as a specified packageId if (packageId != null) { prunedAvailablePackages = PrunePackageTree.PruneAllButHighest(prunedAvailablePackages, packageId); // And then verify that the installed package is not already of a higher version - this check here ensures the user get's the right error message GatherExceptionHelpers.ThrowIfNewerVersionAlreadyReferenced(packageId, projectInstalledPackageReferences, prunedAvailablePackages); } // Remove packages that are of the same Id but different version than the primartTargets prunedAvailablePackages = PrunePackageTree.PruneByPrimaryTargets(prunedAvailablePackages, primaryTargets); // Unless the packageIdentity was explicitly asked for we should remove any potential downgrades if (!allowDowngrades) { prunedAvailablePackages = PrunePackageTree.PruneDowngrades(prunedAvailablePackages, projectInstalledPackageReferences); } // Step-2 : Call PackageResolver.Resolve to get new list of installed packages var packageResolver = new PackageResolver(); var packageResolverContext = new PackageResolverContext( resolutionContext.DependencyBehavior, primaryTargetIds, packageTargetIdsForResolver, projectInstalledPackageReferences, preferredVersions.Values, prunedAvailablePackages, SourceRepositoryProvider.GetRepositories().Select(s => s.PackageSource), log); nuGetProjectContext.Log(NuGet.ProjectManagement.MessageLevel.Info, Strings.AttemptingToResolveDependenciesForMultiplePackages); var newListOfInstalledPackages = packageResolver.Resolve(packageResolverContext, token); if (newListOfInstalledPackages == null) { throw new InvalidOperationException(Strings.UnableToResolveDependencyInfoForMultiplePackages); } // if we have been asked for exact versions of packages then we should also force the uninstall/install of those packages (this corresponds to a -Reinstall) bool isReinstall = PrunePackageTree.IsExactVersion(resolutionContext.VersionConstraints); var targetIds = Enumerable.Empty<string>(); if (!isUpdateAll) { targetIds = (isReinstall ? primaryTargets.Select(p => p.Id) : primaryTargetIds); } var installedPackagesInDependencyOrder = await GetInstalledPackagesInDependencyOrder(nuGetProject, token); var isDependencyBehaviorIgnore = resolutionContext.DependencyBehavior == DependencyBehavior.Ignore; nuGetProjectActions = GetProjectActionsForUpdate( newListOfInstalledPackages, installedPackagesInDependencyOrder, prunedAvailablePackages, nuGetProjectContext, isReinstall, targetIds, isDependencyBehaviorIgnore); if (nuGetProjectActions.Count == 0) { nuGetProjectContext.Log(NuGet.ProjectManagement.MessageLevel.Info, Strings.ResolutionSuccessfulNoAction); nuGetProjectContext.Log(NuGet.ProjectManagement.MessageLevel.Info, Strings.NoUpdatesAvailable); } } catch (InvalidOperationException) { throw; } catch (AggregateException aggregateEx) { throw new InvalidOperationException(aggregateEx.Message, aggregateEx); } catch (Exception ex) { if (string.IsNullOrEmpty(ex.Message)) { throw new InvalidOperationException(Strings.PackagesCouldNotBeInstalled, ex); } throw new InvalidOperationException(ex.Message, ex); } return nuGetProjectActions; } /// <summary> /// Returns all installed packages in order of dependency. Packages with no dependencies come first. /// </summary> /// <remarks>Packages with unresolved dependencies are NOT returned since they are not valid.</remarks> public async Task<IEnumerable<PackageIdentity>> GetInstalledPackagesInDependencyOrder(NuGetProject nuGetProject, CancellationToken token) { var targetFramework = nuGetProject.GetMetadata<NuGetFramework>(NuGetProjectMetadataKeys.TargetFramework); var installedPackages = await nuGetProject.GetInstalledPackagesAsync(token); var installedPackageIdentities = installedPackages.Select(pr => pr.PackageIdentity); var dependencyInfoFromPackagesFolder = await GetDependencyInfoFromPackagesFolder(installedPackageIdentities, targetFramework); // dependencyInfoFromPackagesFolder can be null when NuGetProtocolException is thrown var resolverPackages = dependencyInfoFromPackagesFolder?.Select(package => new ResolverPackage(package.Id, package.Version, package.Dependencies, true, false)); // Use the resolver sort to find the order. Packages with no dependencies // come first, then each package that has satisfied dependencies. // Packages with missing dependencies will not be returned. if (resolverPackages != null) { return ResolverUtility.TopologicalSort(resolverPackages); } return Enumerable.Empty<PackageIdentity>(); } private static List<NuGetProjectAction> GetProjectActionsForUpdate( IEnumerable<PackageIdentity> newListOfInstalledPackages, IEnumerable<PackageIdentity> oldListOfInstalledPackages, IEnumerable<SourcePackageDependencyInfo> availablePackageDependencyInfoWithSourceSet, INuGetProjectContext nuGetProjectContext, bool isReinstall, IEnumerable<string> targetIds, bool isDependencyBehaviorIgnore) { // Step-3 : Get the list of nuGetProjectActions to perform, install/uninstall on the nugetproject // based on newPackages obtained in Step-2 and project.GetInstalledPackages var nuGetProjectActions = new List<NuGetProjectAction>(); nuGetProjectContext.Log(NuGet.ProjectManagement.MessageLevel.Info, Strings.ResolvingActionsToInstallOrUpdateMultiplePackages); // we are reinstalling everything so we just take the ordering directly from the Resolver var newPackagesToUninstall = oldListOfInstalledPackages; var newPackagesToInstall = newListOfInstalledPackages; // we are doing a reinstall of a specific package - we will also want to generate Project Actions for the dependencies if (isReinstall && targetIds.Any()) { var packageIdsToReinstall = new HashSet<string>(targetIds, StringComparer.OrdinalIgnoreCase); // Avoid getting dependencies if dependencyBehavior is set to ignore if (!isDependencyBehaviorIgnore) { packageIdsToReinstall = GetDependencies(targetIds, newListOfInstalledPackages, availablePackageDependencyInfoWithSourceSet); } newPackagesToUninstall = oldListOfInstalledPackages.Where(p => packageIdsToReinstall.Contains(p.Id)); newPackagesToInstall = newListOfInstalledPackages.Where(p => packageIdsToReinstall.Contains(p.Id)); } if (!isReinstall) { if (targetIds.Any()) { // we are targeting a particular package - there is no need therefore to alter other aspects of the project // specifically an unrelated package may have been force removed in which case we should be happy to leave things that way // It will get the list of packages which are being uninstalled to get a new version newPackagesToUninstall = oldListOfInstalledPackages.Where(oldPackage => newListOfInstalledPackages.Any(newPackage => StringComparer.OrdinalIgnoreCase.Equals(oldPackage.Id, newPackage.Id) && !oldPackage.Version.Equals(newPackage.Version))); // this will be the new set of target ids which includes current target ids as well as packages which are being updated //It fixes the issue where we were only getting dependencies for target ids ignoring other packages which are also being updated. #2724 var newTargetIds = new HashSet<string>(newPackagesToUninstall.Select(p => p.Id), StringComparer.OrdinalIgnoreCase); newTargetIds.AddRange(targetIds); var allowed = newTargetIds; // Avoid getting dependencies if dependencyBehavior is set to ignore if (!isDependencyBehaviorIgnore) { // first, we will allow all the dependencies of the package(s) beging targeted allowed = GetDependencies(newTargetIds, newListOfInstalledPackages, availablePackageDependencyInfoWithSourceSet); } // second, any package that is currently in the solution will also be allowed to change // (note this logically doesn't include packages that have been force uninstalled from the project // because we wouldn't want to just add those back in) foreach (var p in oldListOfInstalledPackages) { allowed.Add(p.Id); } newListOfInstalledPackages = newListOfInstalledPackages.Where(p => allowed.Contains(p.Id)); newPackagesToInstall = newListOfInstalledPackages.Where(p => !oldListOfInstalledPackages.Contains(p)); } else { newPackagesToUninstall = oldListOfInstalledPackages.Where(p => !newListOfInstalledPackages.Contains(p)); newPackagesToInstall = newListOfInstalledPackages.Where(p => !oldListOfInstalledPackages.Contains(p)); } } foreach (var newPackageToUninstall in newPackagesToUninstall.Reverse()) { nuGetProjectActions.Add(NuGetProjectAction.CreateUninstallProjectAction(newPackageToUninstall)); } foreach (var newPackageToInstall in newPackagesToInstall) { // find the package match based on identity var sourceDepInfo = availablePackageDependencyInfoWithSourceSet.Where(p => PackageIdentity.Comparer.Equals(p, newPackageToInstall)).SingleOrDefault(); if (sourceDepInfo == null) { // this really should never happen throw new InvalidOperationException(string.Format(CultureInfo.CurrentUICulture, Strings.PackageNotFound, newPackageToInstall)); } nuGetProjectActions.Add(NuGetProjectAction.CreateInstallProjectAction(newPackageToInstall, sourceDepInfo.Source)); } return nuGetProjectActions; } /// <summary> /// Filter down the reinstall list to just the ones we need to reinstall (i.e. the dependencies) /// </summary> private static HashSet<string> GetDependencies(IEnumerable<string> targetIds, IEnumerable<PackageIdentity> newListOfInstalledPackages, IEnumerable<SourcePackageDependencyInfo> available) { var result = new HashSet<string>(StringComparer.OrdinalIgnoreCase); foreach (var targetId in targetIds) { CollectDependencies(result, targetId, newListOfInstalledPackages, available, 0); } return result; } /// <summary> /// A walk through the dependencies to collect the additional package identities that are involved in the current set of packages to be installed /// </summary> private static void CollectDependencies(HashSet<string> result, string id, IEnumerable<PackageIdentity> packages, IEnumerable<SourcePackageDependencyInfo> available, int depth) { // we want the exact PackageIdentity for this id var packageIdentity = packages.FirstOrDefault(p => p.Id.Equals(id, StringComparison.OrdinalIgnoreCase)); if (packageIdentity == null) { throw new ArgumentException("packages"); } // now look up the dependencies of this exact package identity var sourceDepInfo = available.SingleOrDefault(p => packageIdentity.Equals(p)); if (sourceDepInfo == null) { throw new ArgumentException("available"); } result.Add(id); // iterate through all the dependencies and call recursively to collect dependencies foreach (var dependency in sourceDepInfo.Dependencies) { // check we don't fall into an infinite loop caused by bad dependency data in the packages if (depth < packages.Count()) { CollectDependencies(result, dependency.Id, packages, available, depth + 1); } } } /// <summary> /// Gives the preview as a list of NuGetProjectActions that will be performed to install /// <paramref name="packageIdentity" /> into <paramref name="nuGetProject" /> /// <paramref name="resolutionContext" /> and <paramref name="nuGetProjectContext" /> are used in the process. /// </summary> public async Task<IEnumerable<NuGetProjectAction>> PreviewInstallPackageAsync(NuGetProject nuGetProject, PackageIdentity packageIdentity, ResolutionContext resolutionContext, INuGetProjectContext nuGetProjectContext, SourceRepository primarySourceRepository, IEnumerable<SourceRepository> secondarySources, CancellationToken token) { if (nuGetProject is INuGetIntegratedProject) { var action = NuGetProjectAction.CreateInstallProjectAction(packageIdentity, primarySourceRepository); var actions = new[] { action }; var buildIntegratedProject = nuGetProject as BuildIntegratedNuGetProject; if (buildIntegratedProject != null) { actions = new[] { await PreviewBuildIntegratedProjectActionsAsync(buildIntegratedProject, actions, nuGetProjectContext, token) }; } return actions; } var primarySources = new List<SourceRepository> { primarySourceRepository }; return await PreviewInstallPackageAsync(nuGetProject, packageIdentity, resolutionContext, nuGetProjectContext, primarySources, secondarySources, token); } public async Task<IEnumerable<NuGetProjectAction>> PreviewInstallPackageAsync(NuGetProject nuGetProject, PackageIdentity packageIdentity, ResolutionContext resolutionContext, INuGetProjectContext nuGetProjectContext, IEnumerable<SourceRepository> primarySources, IEnumerable<SourceRepository> secondarySources, CancellationToken token) { if (nuGetProject == null) { throw new ArgumentNullException(nameof(nuGetProject)); } if (packageIdentity == null) { throw new ArgumentNullException(nameof(packageIdentity)); } if (resolutionContext == null) { throw new ArgumentNullException(nameof(resolutionContext)); } if (nuGetProjectContext == null) { throw new ArgumentNullException(nameof(nuGetProjectContext)); } if (primarySources == null) { throw new ArgumentNullException(nameof(primarySources)); } if (secondarySources == null) { secondarySources = SourceRepositoryProvider.GetRepositories().Where(e => e.PackageSource.IsEnabled); } if (!primarySources.Any()) { throw new ArgumentException(nameof(primarySources)); } if (packageIdentity.Version == null) { throw new ArgumentNullException("packageIdentity.Version"); } if (nuGetProject is INuGetIntegratedProject) { SourceRepository sourceRepository; if (primarySources.Count() > 1) { var logger = new ProjectContextLogger(nuGetProjectContext); sourceRepository = await GetSourceRepository(packageIdentity, primarySources, logger); } else { sourceRepository = primarySources.First(); } var action = NuGetProjectAction.CreateInstallProjectAction(packageIdentity, sourceRepository); var actions = new[] { action }; var buildIntegratedProject = nuGetProject as BuildIntegratedNuGetProject; if (buildIntegratedProject != null) { actions = new[] { await PreviewBuildIntegratedProjectActionsAsync(buildIntegratedProject, actions, nuGetProjectContext, token) }; } return actions; } var projectInstalledPackageReferences = await nuGetProject.GetInstalledPackagesAsync(token); var oldListOfInstalledPackages = projectInstalledPackageReferences.Select(p => p.PackageIdentity); if (oldListOfInstalledPackages.Any(p => p.Equals(packageIdentity))) { string projectName; nuGetProject.TryGetMetadata(NuGetProjectMetadataKeys.Name, out projectName); var alreadyInstalledMessage = string.Format(ProjectManagement.Strings.PackageAlreadyExistsInProject, packageIdentity, projectName ?? string.Empty); throw new InvalidOperationException(alreadyInstalledMessage, new PackageAlreadyInstalledException(alreadyInstalledMessage)); } var nuGetProjectActions = new List<NuGetProjectAction>(); var effectiveSources = GetEffectiveSources(primarySources, secondarySources); if (resolutionContext.DependencyBehavior != DependencyBehavior.Ignore) { try { var downgradeAllowed = false; var packageTargetsForResolver = new HashSet<PackageIdentity>(oldListOfInstalledPackages, PackageIdentity.Comparer); // Note: resolver needs all the installed packages as targets too. And, metadata should be gathered for the installed packages as well var installedPackageWithSameId = packageTargetsForResolver.Where(p => p.Id.Equals(packageIdentity.Id, StringComparison.OrdinalIgnoreCase)).FirstOrDefault(); if (installedPackageWithSameId != null) { packageTargetsForResolver.Remove(installedPackageWithSameId); if (installedPackageWithSameId.Version > packageIdentity.Version) { // Looks like the installed package is of higher version than one being installed. So, we take it that downgrade is allowed downgradeAllowed = true; } } packageTargetsForResolver.Add(packageIdentity); // Step-1 : Get metadata resources using gatherer var projectName = NuGetProject.GetUniqueNameOrName(nuGetProject); var targetFramework = nuGetProject.GetMetadata<NuGetFramework>(NuGetProjectMetadataKeys.TargetFramework); nuGetProjectContext.Log(NuGet.ProjectManagement.MessageLevel.Info, Environment.NewLine); nuGetProjectContext.Log(ProjectManagement.MessageLevel.Info, Strings.AttemptingToGatherDependencyInfo, packageIdentity, projectName, targetFramework); var primaryPackages = new List<PackageIdentity> { packageIdentity }; var gatherContext = new GatherContext() { InstalledPackages = oldListOfInstalledPackages.ToList(), PrimaryTargets = primaryPackages, TargetFramework = targetFramework, PrimarySources = primarySources.ToList(), AllSources = effectiveSources.ToList(), PackagesFolderSource = PackagesFolderSourceRepository, ResolutionContext = resolutionContext, AllowDowngrades = downgradeAllowed, ProjectContext = nuGetProjectContext }; var availablePackageDependencyInfoWithSourceSet = await ResolverGather.GatherAsync(gatherContext, token); if (!availablePackageDependencyInfoWithSourceSet.Any()) { throw new InvalidOperationException(string.Format(Strings.UnableToGatherDependencyInfo, packageIdentity)); } // Prune the results down to only what we would allow to be installed // Keep only the target package we are trying to install for that Id var prunedAvailablePackages = PrunePackageTree.RemoveAllVersionsForIdExcept(availablePackageDependencyInfoWithSourceSet, packageIdentity); if (!downgradeAllowed) { prunedAvailablePackages = PrunePackageTree.PruneDowngrades(prunedAvailablePackages, projectInstalledPackageReferences); } if (!resolutionContext.IncludePrerelease) { prunedAvailablePackages = PrunePackageTree.PrunePreleaseForStableTargets( prunedAvailablePackages, packageTargetsForResolver, new[] { packageIdentity }); } var log = new LoggerAdapter(nuGetProjectContext); // Verify that the target is allowed by packages.config GatherExceptionHelpers.ThrowIfVersionIsDisallowedByPackagesConfig(packageIdentity.Id, projectInstalledPackageReferences, prunedAvailablePackages, log); // Remove versions that do not satisfy 'allowedVersions' attribute in packages.config, if any prunedAvailablePackages = PrunePackageTree.PruneDisallowedVersions(prunedAvailablePackages, projectInstalledPackageReferences); // Step-2 : Call PackageResolver.Resolve to get new list of installed packages // Note: resolver prefers installed package versions if the satisfy the dependency version constraints // So, since we want an exact version of a package, create a new list of installed packages where the packageIdentity being installed // is present after removing the one with the same id var preferredPackageReferences = new List<Packaging.PackageReference>(projectInstalledPackageReferences.Where(pr => !pr.PackageIdentity.Id.Equals(packageIdentity.Id, StringComparison.OrdinalIgnoreCase))); preferredPackageReferences.Add(new Packaging.PackageReference(packageIdentity, targetFramework)); var packageResolverContext = new PackageResolverContext(resolutionContext.DependencyBehavior, new string[] { packageIdentity.Id }, oldListOfInstalledPackages.Select(package => package.Id), projectInstalledPackageReferences, preferredPackageReferences.Select(package => package.PackageIdentity), prunedAvailablePackages, SourceRepositoryProvider.GetRepositories().Select(s => s.PackageSource), log); nuGetProjectContext.Log(ProjectManagement.MessageLevel.Info, Strings.AttemptingToResolveDependencies, packageIdentity, resolutionContext.DependencyBehavior); var packageResolver = new PackageResolver(); var newListOfInstalledPackages = packageResolver.Resolve(packageResolverContext, token); if (newListOfInstalledPackages == null) { throw new InvalidOperationException(string.Format(Strings.UnableToResolveDependencyInfo, packageIdentity, resolutionContext.DependencyBehavior)); } // Step-3 : Get the list of nuGetProjectActions to perform, install/uninstall on the nugetproject // based on newPackages obtained in Step-2 and project.GetInstalledPackages nuGetProjectContext.Log(ProjectManagement.MessageLevel.Info, Strings.ResolvingActionsToInstallPackage, packageIdentity); var newPackagesToUninstall = new List<PackageIdentity>(); foreach (var oldInstalledPackage in oldListOfInstalledPackages) { var newPackageWithSameId = newListOfInstalledPackages .FirstOrDefault(np => oldInstalledPackage.Id.Equals(np.Id, StringComparison.OrdinalIgnoreCase) && !oldInstalledPackage.Version.Equals(np.Version)); if (newPackageWithSameId != null) { newPackagesToUninstall.Add(oldInstalledPackage); } } var newPackagesToInstall = newListOfInstalledPackages.Where(p => !oldListOfInstalledPackages.Contains(p)); foreach (var newPackageToUninstall in newPackagesToUninstall) { nuGetProjectActions.Add(NuGetProjectAction.CreateUninstallProjectAction(newPackageToUninstall)); } // created hashset of packageIds we are OK with touching // the scenario here is that the user might have done an uninstall-package -Force on a particular package // this will be the new set of target ids which includes current target ids as well as packages which are being updated //It fixes the issue where we were only getting dependencies for target ids ignoring other packages which are also being updated. #2724 var newTargetIds = new HashSet<string>(newPackagesToUninstall.Select(p => p.Id), StringComparer.OrdinalIgnoreCase); newTargetIds.Add(packageIdentity.Id); // get all dependencies of new target ids so that we can have all the required install actions. var allowed = GetDependencies(newTargetIds, newListOfInstalledPackages, prunedAvailablePackages); foreach (var newPackageToInstall in newPackagesToInstall) { // we should limit actions to just packages that are in the dependency set of the target we are installing if (allowed.Contains(newPackageToInstall.Id)) { // find the package match based on identity var sourceDepInfo = prunedAvailablePackages.SingleOrDefault(p => PackageIdentity.Comparer.Equals(p, newPackageToInstall)); if (sourceDepInfo == null) { // this really should never happen throw new InvalidOperationException(string.Format(Strings.PackageNotFound, packageIdentity)); } nuGetProjectActions.Add(NuGetProjectAction.CreateInstallProjectAction(sourceDepInfo, sourceDepInfo.Source)); } } } catch (InvalidOperationException) { throw; } catch (AggregateException aggregateEx) { throw new InvalidOperationException(aggregateEx.Message, aggregateEx); } catch (Exception ex) { if (string.IsNullOrEmpty(ex.Message)) { throw new InvalidOperationException(string.Format(Strings.PackageCouldNotBeInstalled, packageIdentity), ex); } throw new InvalidOperationException(ex.Message, ex); } } else { var logger = new ProjectContextLogger(nuGetProjectContext); var sourceRepository = await GetSourceRepository(packageIdentity, effectiveSources, logger); nuGetProjectActions.Add(NuGetProjectAction.CreateInstallProjectAction(packageIdentity, sourceRepository)); } nuGetProjectContext.Log(ProjectManagement.MessageLevel.Info, Strings.ResolvedActionsToInstallPackage, packageIdentity); return nuGetProjectActions; } /// <summary> /// Check all sources in parallel to see if the package exists while respecting the order of the list. /// This is only used by PreviewInstall with DependencyBehavior.Ignore. /// Since, resolver gather is not used when dependencies are not used, /// we simply get the source repository using MetadataResource.Exists /// </summary> private static async Task<SourceRepository> GetSourceRepository(PackageIdentity packageIdentity, IEnumerable<SourceRepository> sourceRepositories, Common.ILogger logger) { SourceRepository source = null; // TODO: move this timeout to a better place // TODO: what should the timeout be? // Give up after 5 minutes var tokenSource = new CancellationTokenSource(TimeSpan.FromMinutes(5)); var results = new Queue<KeyValuePair<SourceRepository, Task<bool>>>(); foreach (var sourceRepository in sourceRepositories) { // TODO: fetch the resource in parallel also var metadataResource = await sourceRepository.GetResourceAsync<MetadataResource>(); if (metadataResource != null) { var task = Task.Run(() => metadataResource.Exists(packageIdentity, logger, tokenSource.Token), tokenSource.Token); results.Enqueue(new KeyValuePair<SourceRepository, Task<bool>>(sourceRepository, task)); } } while (results.Count > 0) { var pair = results.Dequeue(); try { var exists = await pair.Value; // take only the first true result, but continue waiting for the remaining cancelled // tasks to keep things from getting out of control. if (source == null && exists) { source = pair.Key; // there is no need to finish trying the others tokenSource.Cancel(); } } catch (OperationCanceledException) { // ignore these } catch (Exception ex) { logger.LogWarning( string.Format(Strings.Warning_ErrorFindingRepository, pair.Key.PackageSource.Source, ExceptionUtilities.DisplayMessage(ex))); } } if (source == null) { // no matches were found throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Strings.UnknownPackageSpecificVersion, packageIdentity.Id, packageIdentity.Version)); } return source; } /// <summary> /// Gives the preview as a list of NuGetProjectActions that will be performed to uninstall /// <paramref name="packageId" /> into <paramref name="nuGetProject" /> /// <paramref name="uninstallationContext" /> and <paramref name="nuGetProjectContext" /> are used in the /// process. /// </summary> public async Task<IEnumerable<NuGetProjectAction>> PreviewUninstallPackageAsync(NuGetProject nuGetProject, string packageId, UninstallationContext uninstallationContext, INuGetProjectContext nuGetProjectContext, CancellationToken token) { if (nuGetProject == null) { throw new ArgumentNullException(nameof(nuGetProject)); } if (packageId == null) { throw new ArgumentNullException(nameof(packageId)); } if (uninstallationContext == null) { throw new ArgumentNullException(nameof(uninstallationContext)); } if (nuGetProjectContext == null) { throw new ArgumentNullException(nameof(nuGetProjectContext)); } // Step-1: Get the packageIdentity corresponding to packageId and check if it exists to be uninstalled var installedPackages = await nuGetProject.GetInstalledPackagesAsync(token); var packageReference = installedPackages.FirstOrDefault(pr => pr.PackageIdentity.Id.Equals(packageId, StringComparison.OrdinalIgnoreCase)); if (packageReference?.PackageIdentity == null) { throw new ArgumentException(string.Format(Strings.PackageToBeUninstalledCouldNotBeFound, packageId, nuGetProject.GetMetadata<string>(NuGetProjectMetadataKeys.Name))); } return await PreviewUninstallPackageAsyncPrivate(nuGetProject, packageReference, uninstallationContext, nuGetProjectContext, token); } /// <summary> /// Gives the preview as a list of <see cref="NuGetProjectAction" /> that will be performed to uninstall /// <paramref name="packageIdentity" /> into <paramref name="nuGetProject" /> /// <paramref name="uninstallationContext" /> and <paramref name="nuGetProjectContext" /> are used in the /// process. /// </summary> public async Task<IEnumerable<NuGetProjectAction>> PreviewUninstallPackageAsync(NuGetProject nuGetProject, PackageIdentity packageIdentity, UninstallationContext uninstallationContext, INuGetProjectContext nuGetProjectContext, CancellationToken token) { if (nuGetProject == null) { throw new ArgumentNullException(nameof(nuGetProject)); } if (packageIdentity == null) { throw new ArgumentNullException(nameof(packageIdentity)); } if (uninstallationContext == null) { throw new ArgumentNullException(nameof(uninstallationContext)); } if (nuGetProjectContext == null) { throw new ArgumentNullException(nameof(nuGetProjectContext)); } // Step-1: Get the packageIdentity corresponding to packageId and check if it exists to be uninstalled var installedPackages = await nuGetProject.GetInstalledPackagesAsync(token); var packageReference = installedPackages.FirstOrDefault(pr => pr.PackageIdentity.Equals(packageIdentity)); if (packageReference?.PackageIdentity == null) { throw new ArgumentException(string.Format(Strings.PackageToBeUninstalledCouldNotBeFound, packageIdentity.Id, nuGetProject.GetMetadata<string>(NuGetProjectMetadataKeys.Name))); } return await PreviewUninstallPackageAsyncPrivate(nuGetProject, packageReference, uninstallationContext, nuGetProjectContext, token); } private async Task<IEnumerable<NuGetProjectAction>> PreviewUninstallPackageAsyncPrivate(NuGetProject nuGetProject, Packaging.PackageReference packageReference, UninstallationContext uninstallationContext, INuGetProjectContext nuGetProjectContext, CancellationToken token) { if (SolutionManager == null) { throw new InvalidOperationException(Strings.SolutionManagerNotAvailableForUninstall); } if (nuGetProject is INuGetIntegratedProject) { var action = NuGetProjectAction.CreateUninstallProjectAction(packageReference.PackageIdentity); var actions = new[] { action }; var buildIntegratedProject = nuGetProject as BuildIntegratedNuGetProject; if (buildIntegratedProject != null) { actions = new[] { await PreviewBuildIntegratedProjectActionsAsync(buildIntegratedProject, actions, nuGetProjectContext, token) }; } return actions; } // Step-1 : Get the metadata resources from "packages" folder or custom repository path var packageIdentity = packageReference.PackageIdentity; var projectName = NuGetProject.GetUniqueNameOrName(nuGetProject); var packageReferenceTargetFramework = packageReference.TargetFramework; nuGetProjectContext.Log(NuGet.ProjectManagement.MessageLevel.Info, Environment.NewLine); nuGetProjectContext.Log(ProjectManagement.MessageLevel.Info, Strings.AttemptingToGatherDependencyInfo, packageIdentity, projectName, packageReferenceTargetFramework); // TODO: IncludePrerelease is a big question mark var log = new LoggerAdapter(nuGetProjectContext); var installedPackageIdentities = (await nuGetProject.GetInstalledPackagesAsync(token)).Select(pr => pr.PackageIdentity); var dependencyInfoFromPackagesFolder = await GetDependencyInfoFromPackagesFolder(installedPackageIdentities, packageReferenceTargetFramework); nuGetProjectContext.Log(ProjectManagement.MessageLevel.Info, Strings.ResolvingActionsToUninstallPackage, packageIdentity); // Step-2 : Determine if the package can be uninstalled based on the metadata resources var packagesToBeUninstalled = UninstallResolver.GetPackagesToBeUninstalled(packageIdentity, dependencyInfoFromPackagesFolder, installedPackageIdentities, uninstallationContext); var nuGetProjectActions = packagesToBeUninstalled.Select(NuGetProjectAction.CreateUninstallProjectAction); nuGetProjectContext.Log(ProjectManagement.MessageLevel.Info, Strings.ResolvedActionsToUninstallPackage, packageIdentity); return nuGetProjectActions; } private async Task<IEnumerable<PackageDependencyInfo>> GetDependencyInfoFromPackagesFolder(IEnumerable<PackageIdentity> packageIdentities, NuGetFramework nuGetFramework) { try { var results = new HashSet<PackageDependencyInfo>(PackageIdentity.Comparer); var dependencyInfoResource = await PackagesFolderSourceRepository.GetResourceAsync<DependencyInfoResource>(); foreach (var package in packageIdentities) { var packageDependencyInfo = await dependencyInfoResource.ResolvePackage(package, nuGetFramework, Common.NullLogger.Instance, CancellationToken.None); if (packageDependencyInfo != null) { results.Add(packageDependencyInfo); } } return results; } catch (NuGetProtocolException) { return null; } } /// <summary> /// Executes the list of <paramref name="nuGetProjectActions" /> on <paramref name="nuGetProject" /> , which is /// likely obtained by calling into /// <see /// cref="PreviewInstallPackageAsync(NuGetProject,string,ResolutionContext,INuGetProjectContext,SourceRepository,IEnumerable{SourceRepository},CancellationToken)" /> /// <paramref name="nuGetProjectContext" /> is used in the process. /// </summary> public async Task ExecuteNuGetProjectActionsAsync(NuGetProject nuGetProject, IEnumerable<NuGetProjectAction> nuGetProjectActions, INuGetProjectContext nuGetProjectContext, CancellationToken token) { if (nuGetProject == null) { throw new ArgumentNullException(nameof(nuGetProject)); } if (nuGetProjectActions == null) { throw new ArgumentNullException(nameof(nuGetProjectActions)); } if (nuGetProjectContext == null) { throw new ArgumentNullException(nameof(nuGetProjectContext)); } var stopWatch = new Stopwatch(); stopWatch.Start(); // DNU: Find the closure before executing the actions var buildIntegratedProject = nuGetProject as BuildIntegratedNuGetProject; if (buildIntegratedProject != null) { await ExecuteBuildIntegratedProjectActionsAsync(buildIntegratedProject, nuGetProjectActions, nuGetProjectContext, token); } else { // Set the original packages config if it exists var msbuildProject = nuGetProject as MSBuildNuGetProject; if (msbuildProject != null) { nuGetProjectContext.OriginalPackagesConfig = msbuildProject.PackagesConfigNuGetProject?.GetPackagesConfig(); } ExceptionDispatchInfo exceptionInfo = null; var executedNuGetProjectActions = new Stack<NuGetProjectAction>(); var packageWithDirectoriesToBeDeleted = new HashSet<PackageIdentity>(PackageIdentity.Comparer); var ideExecutionContext = nuGetProjectContext.ExecutionContext as IDEExecutionContext; if (ideExecutionContext != null) { await ideExecutionContext.SaveExpandedNodeStates(SolutionManager); } var logger = new ProjectContextLogger(nuGetProjectContext); Dictionary<PackageIdentity, PackagePreFetcherResult> downloadTasks = null; CancellationTokenSource downloadTokenSource = null; // batch events argument object PackageProjectEventArgs packageProjectEventArgs = null; try { // PreProcess projects await nuGetProject.PreProcessAsync(nuGetProjectContext, token); var actionsList = nuGetProjectActions.ToList(); var hasInstalls = actionsList.Any(action => action.NuGetProjectActionType == NuGetProjectActionType.Install); if (hasInstalls) { // Make this independently cancelable. downloadTokenSource = CancellationTokenSource.CreateLinkedTokenSource(token); // Download all packages up front in parallel downloadTasks = await PackagePreFetcher.GetPackagesAsync( actionsList, PackagesFolderNuGetProject, Settings, logger, downloadTokenSource.Token); // Log download information PackagePreFetcher.LogFetchMessages( downloadTasks.Values, PackagesFolderNuGetProject.Root, logger); } if (msbuildProject != null) { // raise Nuget batch start event var batchId = Guid.NewGuid().ToString(); string name; nuGetProject.TryGetMetadata(NuGetProjectMetadataKeys.Name, out name); packageProjectEventArgs = new PackageProjectEventArgs(batchId, name); BatchStart?.Invoke(this, packageProjectEventArgs); PackageProjectEventsProvider.Instance.NotifyBatchStart(packageProjectEventArgs); } foreach (var nuGetProjectAction in actionsList) { executedNuGetProjectActions.Push(nuGetProjectAction); if (nuGetProjectAction.NuGetProjectActionType == NuGetProjectActionType.Uninstall) { await ExecuteUninstallAsync(nuGetProject, nuGetProjectAction.PackageIdentity, packageWithDirectoriesToBeDeleted, nuGetProjectContext, token); } else { // Retrieve the downloaded package // This will wait on the package if it is still downloading var preFetchResult = downloadTasks[nuGetProjectAction.PackageIdentity]; using (var downloadPackageResult = await preFetchResult.GetResultAsync()) { // use the version exactly as specified in the nuspec file var packageIdentity = downloadPackageResult.PackageReader.GetIdentity(); await ExecuteInstallAsync( nuGetProject, packageIdentity, downloadPackageResult, packageWithDirectoriesToBeDeleted, nuGetProjectContext, token); } } if (nuGetProjectAction.NuGetProjectActionType == NuGetProjectActionType.Install) { var identityString = string.Format(CultureInfo.InvariantCulture, "{0} {1}", nuGetProjectAction.PackageIdentity.Id, nuGetProjectAction.PackageIdentity.Version.ToNormalizedString()); nuGetProjectContext.Log( ProjectManagement.MessageLevel.Info, Strings.SuccessfullyInstalled, identityString, nuGetProject.GetMetadata<string>(NuGetProjectMetadataKeys.Name)); } else { // uninstall nuGetProjectContext.Log( ProjectManagement.MessageLevel.Info, Strings.SuccessfullyUninstalled, nuGetProjectAction.PackageIdentity, nuGetProject.GetMetadata<string>(NuGetProjectMetadataKeys.Name)); } } // Post process await nuGetProject.PostProcessAsync(nuGetProjectContext, token); // Open readme file await OpenReadmeFile(nuGetProject, nuGetProjectContext, token); } catch (Exception ex) { exceptionInfo = ExceptionDispatchInfo.Capture(ex); } finally { if (downloadTasks != null) { // Wait for all downloads to cancel and dispose downloadTokenSource.Cancel(); foreach (var result in downloadTasks.Values) { await result.EnsureResultAsync(); result.Dispose(); } downloadTokenSource.Dispose(); } if (msbuildProject != null) { // raise nuget batch end event if (packageProjectEventArgs != null) { BatchEnd?.Invoke(this, packageProjectEventArgs); PackageProjectEventsProvider.Instance.NotifyBatchEnd(packageProjectEventArgs); } } } if (exceptionInfo != null) { await Rollback(nuGetProject, executedNuGetProjectActions, packageWithDirectoriesToBeDeleted, nuGetProjectContext, token); } if (ideExecutionContext != null) { await ideExecutionContext.CollapseAllNodes(SolutionManager); } // Delete the package directories as the last step, so that, if an uninstall had to be rolled back, we can just use the package file on the directory // Also, always perform deletion of package directories, even in a rollback, so that there are no stale package directories foreach (var packageWithDirectoryToBeDeleted in packageWithDirectoriesToBeDeleted) { var packageFolderPath = PackagesFolderNuGetProject.GetInstalledPath(packageWithDirectoryToBeDeleted); try { await DeletePackage(packageWithDirectoryToBeDeleted, nuGetProjectContext, token); } finally { if (DeleteOnRestartManager != null) { if (Directory.Exists(packageFolderPath)) { DeleteOnRestartManager.MarkPackageDirectoryForDeletion( packageWithDirectoryToBeDeleted, packageFolderPath, nuGetProjectContext); // Raise the event to notify listners to update the UI etc. DeleteOnRestartManager.CheckAndRaisePackageDirectoriesMarkedForDeletion(); } } } } // Save project SolutionManager?.SaveProject(nuGetProject); // Clear direct install SetDirectInstall(null, nuGetProjectContext); // calculate total time taken to execute all nuget actions stopWatch.Stop(); nuGetProjectContext.Log( ProjectManagement.MessageLevel.Info, Strings.NugetActionsTotalTime, DatetimeUtility.ToReadableTimeFormat(stopWatch.Elapsed)); if (exceptionInfo != null) { exceptionInfo.Throw(); } } } /// <summary> /// Run project actions for build integrated projects. /// </summary> public async Task<BuildIntegratedProjectAction> PreviewBuildIntegratedProjectActionsAsync( BuildIntegratedNuGetProject buildIntegratedProject, IEnumerable<NuGetProjectAction> nuGetProjectActions, INuGetProjectContext nuGetProjectContext, CancellationToken token) { if (nuGetProjectActions == null) { throw new ArgumentNullException(nameof(nuGetProjectActions)); } if (buildIntegratedProject == null) { throw new ArgumentNullException(nameof(buildIntegratedProject)); } if (nuGetProjectContext == null) { throw new ArgumentNullException(nameof(nuGetProjectContext)); } if (!nuGetProjectActions.Any()) { // Return null if there are no actions. return null; } // Find all sources used in the project actions var sources = new HashSet<SourceRepository>( nuGetProjectActions.Where(action => action.SourceRepository != null) .Select(action => action.SourceRepository), new SourceRepositoryComparer()); // Add all enabled sources for the existing packages var enabledSources = SourceRepositoryProvider.GetRepositories(); sources.UnionWith(enabledSources); // Read the current lock file if it exists LockFile originalLockFile = null; var lockFileFormat = new LockFileFormat(); var lockFilePath = ProjectJsonPathUtilities.GetLockFilePath(buildIntegratedProject.JsonConfigPath); if (File.Exists(lockFilePath)) { originalLockFile = lockFileFormat.Read(lockFilePath); } // Read project.json JObject rawPackageSpec; using (var streamReader = new StreamReader(buildIntegratedProject.JsonConfigPath)) { var reader = new JsonTextReader(streamReader); rawPackageSpec = JObject.Load(reader); } var logger = new ProjectContextLogger(nuGetProjectContext); var buildIntegratedContext = new ExternalProjectReferenceContext(logger); var pathContext = NuGetPathContext.Create(Settings); // For installs only use cache entries newer than the current time. // This is needed for scenarios where a new package shows up in search // but a previous cache entry does not yet have it. // So we want to capture the time once here, then pass it down to the two // restores happening in this flow. using (var cacheContext = new SourceCacheContext()) { cacheContext.ListMaxAge = DateTimeOffset.UtcNow; var providers = RestoreCommandProviders.Create( pathContext.UserPackageFolder, pathContext.FallbackPackageFolders, sources, cacheContext, logger); // If the lock file does not exist, restore before starting the operations if (originalLockFile == null) { var originalPackageSpec = JsonPackageSpecReader.GetPackageSpec( rawPackageSpec.ToString(), buildIntegratedProject.ProjectName, buildIntegratedProject.JsonConfigPath); var originalRestoreResult = await BuildIntegratedRestoreUtility.RestoreAsync( buildIntegratedProject, originalPackageSpec, buildIntegratedContext, providers, token); originalLockFile = originalRestoreResult.LockFile; } // Modify the package spec foreach (var action in nuGetProjectActions) { if (action.NuGetProjectActionType == NuGetProjectActionType.Uninstall) { JsonConfigUtility.RemoveDependency(rawPackageSpec, action.PackageIdentity.Id); } else if (action.NuGetProjectActionType == NuGetProjectActionType.Install) { JsonConfigUtility.AddDependency(rawPackageSpec, action.PackageIdentity); } } // Create a package spec from the modified json var packageSpec = JsonPackageSpecReader.GetPackageSpec(rawPackageSpec.ToString(), buildIntegratedProject.ProjectName, buildIntegratedProject.JsonConfigPath); // Restore based on the modified package spec. This operation does not write the lock file to disk. var restoreResult = await BuildIntegratedRestoreUtility.RestoreAsync( buildIntegratedProject, packageSpec, buildIntegratedContext, providers, token); InstallationCompatibility.EnsurePackageCompatibility( buildIntegratedProject, pathContext, nuGetProjectActions, restoreResult); // If this build integrated project action represents only uninstalls, mark the entire operation // as an uninstall. Otherwise, mark it as an install. This is important because install operations // are a bit more sensitive to errors (thus resulting in rollbacks). var actionType = NuGetProjectActionType.Install; if (nuGetProjectActions.All(x => x.NuGetProjectActionType == NuGetProjectActionType.Uninstall)) { actionType = NuGetProjectActionType.Uninstall; } return new BuildIntegratedProjectAction(nuGetProjectActions.First().PackageIdentity, actionType, originalLockFile, rawPackageSpec, restoreResult, sources.ToList()); } } /// <summary> /// Run project actions for build integrated projects. /// </summary> public async Task ExecuteBuildIntegratedProjectActionsAsync( BuildIntegratedNuGetProject buildIntegratedProject, IEnumerable<NuGetProjectAction> nuGetProjectActions, INuGetProjectContext nuGetProjectContext, CancellationToken token) { BuildIntegratedProjectAction projectAction = null; if (nuGetProjectActions.Count() == 1 && nuGetProjectActions.All(action => action is BuildIntegratedProjectAction)) { projectAction = nuGetProjectActions.Single() as BuildIntegratedProjectAction; } else if (nuGetProjectActions.Any()) { projectAction = await PreviewBuildIntegratedProjectActionsAsync( buildIntegratedProject, nuGetProjectActions, nuGetProjectContext, token); } else { // There are no actions, this is a no-op return; } var actions = projectAction.GetProjectActions(); // Check if all actions are uninstalls var uninstallOnly = projectAction.NuGetProjectActionType == NuGetProjectActionType.Uninstall && actions.All(action => action.NuGetProjectActionType == NuGetProjectActionType.Uninstall); var restoreResult = projectAction.RestoreResult; // Avoid committing the changes if the restore did not succeed // For uninstalls continue even if the restore failed to avoid blocking the user if (restoreResult.Success || uninstallOnly) { // Write out project.json // This can be replaced with the PackageSpec writer once it has been added to the library using (var writer = new StreamWriter( buildIntegratedProject.JsonConfigPath, append: false, encoding: Encoding.UTF8)) { await writer.WriteAsync(projectAction.UpdatedProjectJson.ToString()); } // Write out the lock file var logger = new ProjectContextLogger(nuGetProjectContext); await restoreResult.CommitAsync(logger, token); // Write out a message for each action foreach (var action in actions) { var identityString = String.Format(CultureInfo.InvariantCulture, "{0} {1}", action.PackageIdentity.Id, action.PackageIdentity.Version.ToNormalizedString()); if (action.NuGetProjectActionType == NuGetProjectActionType.Install) { nuGetProjectContext.Log( ProjectManagement.MessageLevel.Info, Strings.SuccessfullyInstalled, identityString, buildIntegratedProject.GetMetadata<string>(NuGetProjectMetadataKeys.Name)); } else { // uninstall nuGetProjectContext.Log( ProjectManagement.MessageLevel.Info, Strings.SuccessfullyUninstalled, identityString, buildIntegratedProject.GetMetadata<string>(NuGetProjectMetadataKeys.Name)); } } // Run init.ps1 scripts var sortedPackages = BuildIntegratedProjectUtility.GetOrderedProjectDependencies(buildIntegratedProject); var addedPackages = new HashSet<PackageIdentity>( BuildIntegratedRestoreUtility.GetAddedPackages( projectAction.OriginalLockFile, restoreResult.LockFile), PackageIdentity.Comparer); var pathContext = NuGetPathContext.Create(Settings); // Find all dependencies in sorted order, then using the order run init.ps1 for only the new packages. foreach (var package in sortedPackages) { if (addedPackages.Contains(package)) { var packageInstallPath = BuildIntegratedProjectUtility.GetPackagePathFromGlobalSource( pathContext.UserPackageFolder, package); await buildIntegratedProject.ExecuteInitScriptAsync( package, packageInstallPath, nuGetProjectContext, false); } } // Restore parent projects. These will be updated to include the transitive changes. var referenceContext = new ExternalProjectReferenceContext(logger); var parents = await BuildIntegratedRestoreUtility.GetParentProjectsInClosure( SolutionManager, buildIntegratedProject, referenceContext); var now = DateTime.UtcNow; Action<SourceCacheContext> cacheContextModifier = c => c.ListMaxAge = now; foreach (var parent in parents) { // Restore and commit the lock file to disk regardless of the result var parentResult = await BuildIntegratedRestoreUtility.RestoreAsync( parent, referenceContext, projectAction.Sources, pathContext.UserPackageFolder, pathContext.FallbackPackageFolders, cacheContextModifier, token); } } else { // Fail and display a rollback message to let the user know they have returned to the original state throw new InvalidOperationException( string.Format( CultureInfo.InvariantCulture, Strings.RestoreFailedRollingBack, buildIntegratedProject.ProjectName)); } await OpenReadmeFile(buildIntegratedProject, nuGetProjectContext, token); } private async Task Rollback( NuGetProject nuGetProject, Stack<NuGetProjectAction> executedNuGetProjectActions, HashSet<PackageIdentity> packageWithDirectoriesToBeDeleted, INuGetProjectContext nuGetProjectContext, CancellationToken token) { if (executedNuGetProjectActions.Count > 0) { // Only print the rollback warning if we have something to rollback nuGetProjectContext.Log(ProjectManagement.MessageLevel.Warning, Strings.Warning_RollingBack); } while (executedNuGetProjectActions.Count > 0) { var nuGetProjectAction = executedNuGetProjectActions.Pop(); try { if (nuGetProjectAction.NuGetProjectActionType == NuGetProjectActionType.Install) { // Rolling back an install would be to uninstall the package await ExecuteUninstallAsync(nuGetProject, nuGetProjectAction.PackageIdentity, packageWithDirectoriesToBeDeleted, nuGetProjectContext, token); } else { packageWithDirectoriesToBeDeleted.Remove(nuGetProjectAction.PackageIdentity); var packagePath = PackagesFolderNuGetProject.GetInstalledPackageFilePath(nuGetProjectAction.PackageIdentity); if (File.Exists(packagePath)) { using (var downloadResourceResult = new DownloadResourceResult(File.OpenRead(packagePath))) { await ExecuteInstallAsync(nuGetProject, nuGetProjectAction.PackageIdentity, downloadResourceResult, packageWithDirectoriesToBeDeleted, nuGetProjectContext, token); } } } } catch (Exception) { // TODO: We are ignoring exceptions on rollback. Is this OK? } } } private Task OpenReadmeFile(NuGetProject nuGetProject, INuGetProjectContext nuGetProjectContext, CancellationToken token) { var executionContext = nuGetProjectContext.ExecutionContext; if (executionContext != null && executionContext.DirectInstall != null) { //packagesPath is different for project.json vs Packages.config scenarios. So check if the project is a build-integrated project var buildIntegratedProject = nuGetProject as BuildIntegratedNuGetProject; var readmeFilePath = String.Empty; if (buildIntegratedProject != null) { var packageFolderPath = BuildIntegratedProjectUtility.GetPackagePathFromGlobalSource( Configuration.SettingsUtility.GetGlobalPackagesFolder(Settings), nuGetProjectContext.ExecutionContext.DirectInstall); if (Directory.Exists(packageFolderPath)) { readmeFilePath = Path.Combine(packageFolderPath, ProjectManagement.Constants.ReadmeFileName); } } else { var packagePath = PackagesFolderNuGetProject.GetInstalledPackageFilePath(executionContext.DirectInstall); if (File.Exists(packagePath)) { readmeFilePath = Path.Combine(Path.GetDirectoryName(packagePath), ProjectManagement.Constants.ReadmeFileName); } } if (File.Exists(readmeFilePath) && !token.IsCancellationRequested) { return executionContext.OpenFile(readmeFilePath); } } return Task.FromResult(false); } /// <summary> /// RestorePackage is only allowed on a folderNuGetProject. In most cases, one will simply use the /// packagesFolderPath from NuGetPackageManager /// to create a folderNuGetProject before calling into this method /// </summary> public async Task<bool> RestorePackageAsync(PackageIdentity packageIdentity, INuGetProjectContext nuGetProjectContext, IEnumerable<SourceRepository> sourceRepositories, CancellationToken token) { token.ThrowIfCancellationRequested(); if (PackageExistsInPackagesFolder(packageIdentity, nuGetProjectContext.PackageExtractionContext.PackageSaveMode)) { return false; } token.ThrowIfCancellationRequested(); nuGetProjectContext.Log(ProjectManagement.MessageLevel.Info, string.Format(Strings.RestoringPackage, packageIdentity)); var enabledSources = (sourceRepositories != null && sourceRepositories.Any()) ? sourceRepositories : SourceRepositoryProvider.GetRepositories().Where(e => e.PackageSource.IsEnabled); token.ThrowIfCancellationRequested(); using (var downloadResult = await PackageDownloader.GetDownloadResourceResultAsync(enabledSources, packageIdentity, Settings, new ProjectContextLogger(nuGetProjectContext), token)) { packageIdentity = downloadResult.PackageReader.GetIdentity(); // If you already downloaded the package, just restore it, don't cancel the operation now await PackagesFolderNuGetProject.InstallPackageAsync(packageIdentity, downloadResult, nuGetProjectContext, token); } return true; } public Task<bool> CopySatelliteFilesAsync(PackageIdentity packageIdentity, INuGetProjectContext nuGetProjectContext, CancellationToken token) { return PackagesFolderNuGetProject.CopySatelliteFilesAsync(packageIdentity, nuGetProjectContext, token); } /// <summary> /// Checks whether package exists in packages folder and verifies that nupkg and nuspec are present as specified by packageSaveMode /// </summary> public bool PackageExistsInPackagesFolder(PackageIdentity packageIdentity, PackageSaveMode packageSaveMode) { return PackagesFolderNuGetProject.PackageExists(packageIdentity, packageSaveMode); } public bool PackageExistsInPackagesFolder(PackageIdentity packageIdentity) { return PackagesFolderNuGetProject.PackageExists(packageIdentity); } private Task ExecuteInstallAsync( NuGetProject nuGetProject, PackageIdentity packageIdentity, DownloadResourceResult resourceResult, HashSet<PackageIdentity> packageWithDirectoriesToBeDeleted, INuGetProjectContext nuGetProjectContext, CancellationToken token) { // TODO: EnsurePackageCompatibility check should be performed in preview. Can easily avoid a lot of rollback InstallationCompatibility.EnsurePackageCompatibility(nuGetProject, packageIdentity, resourceResult); packageWithDirectoriesToBeDeleted.Remove(packageIdentity); return nuGetProject.InstallPackageAsync(packageIdentity, resourceResult, nuGetProjectContext, token); } private async Task ExecuteUninstallAsync(NuGetProject nuGetProject, PackageIdentity packageIdentity, HashSet<PackageIdentity> packageWithDirectoriesToBeDeleted, INuGetProjectContext nuGetProjectContext, CancellationToken token) { // Step-1: Call nuGetProject.UninstallPackage await nuGetProject.UninstallPackageAsync(packageIdentity, nuGetProjectContext, token); // Step-2: Check if the package directory could be deleted if (!(nuGetProject is INuGetIntegratedProject) && !await PackageExistsInAnotherNuGetProject(nuGetProject, packageIdentity, SolutionManager, token)) { packageWithDirectoriesToBeDeleted.Add(packageIdentity); } // TODO: Consider using CancelEventArgs instead of a regular EventArgs?? //if (packageOperationEventArgs.Cancel) //{ // return; //} } /// <summary> /// Checks if package <paramref name="packageIdentity" /> that is installed in /// project <paramref name="nuGetProject" /> is also installed in any /// other projects in the solution. /// </summary> public static async Task<bool> PackageExistsInAnotherNuGetProject(NuGetProject nuGetProject, PackageIdentity packageIdentity, ISolutionManager solutionManager, CancellationToken token) { if (nuGetProject == null) { throw new ArgumentNullException(nameof(nuGetProject)); } if (packageIdentity == null) { throw new ArgumentNullException(nameof(packageIdentity)); } if (solutionManager == null) { // If the solution manager is null, simply assume that the // package exists on another nuget project to not delete it return true; } var nuGetProjectName = NuGetProject.GetUniqueNameOrName(nuGetProject); foreach (var otherNuGetProject in solutionManager.GetNuGetProjects()) { var otherNuGetProjectName = NuGetProject.GetUniqueNameOrName(otherNuGetProject); if (!otherNuGetProjectName.Equals(nuGetProjectName, StringComparison.OrdinalIgnoreCase)) { var packageExistsInAnotherNuGetProject = (await otherNuGetProject.GetInstalledPackagesAsync(token)).Any(pr => pr.PackageIdentity.Equals(packageIdentity)); if (packageExistsInAnotherNuGetProject) { return true; } } } return false; } private async Task<bool> DeletePackage(PackageIdentity packageIdentity, INuGetProjectContext nuGetProjectContext, CancellationToken token) { if (packageIdentity == null) { throw new ArgumentNullException(nameof(packageIdentity)); } if (nuGetProjectContext == null) { throw new ArgumentNullException(nameof(nuGetProjectContext)); } // 1. Check if the Package exists at root, if not, return false if (!PackagesFolderNuGetProject.PackageExists(packageIdentity)) { nuGetProjectContext.Log(ProjectManagement.MessageLevel.Warning, ProjectManagement.Strings.PackageDoesNotExistInFolder, packageIdentity, PackagesFolderNuGetProject.Root); return false; } nuGetProjectContext.Log(ProjectManagement.MessageLevel.Info, ProjectManagement.Strings.RemovingPackageFromFolder, packageIdentity, PackagesFolderNuGetProject.Root); // 2. Delete the package folder and files from the root directory of this FileSystemNuGetProject // Remember that the following code may throw System.UnauthorizedAccessException await PackagesFolderNuGetProject.DeletePackage(packageIdentity, nuGetProjectContext, token); nuGetProjectContext.Log(ProjectManagement.MessageLevel.Info, ProjectManagement.Strings.RemovedPackageFromFolder, packageIdentity, PackagesFolderNuGetProject.Root); return true; } public static Task<NuGetVersion> GetLatestVersionAsync( string packageId, NuGetFramework framework, ResolutionContext resolutionContext, SourceRepository primarySourceRepository, Common.ILogger log, CancellationToken token) { return GetLatestVersionAsync( packageId, framework, resolutionContext, new List<SourceRepository> { primarySourceRepository }, log, token); } public static Task<NuGetVersion> GetLatestVersionAsync( string packageId, NuGetProject project, ResolutionContext resolutionContext, SourceRepository primarySourceRepository, Common.ILogger log, CancellationToken token) { NuGetFramework framework; if (!project.TryGetMetadata<NuGetFramework>(NuGetProjectMetadataKeys.TargetFramework, out framework)) { // Default to the any framework if the project does not specify a framework. framework = NuGetFramework.AnyFramework; } return GetLatestVersionAsync( packageId, framework, resolutionContext, new List<SourceRepository> { primarySourceRepository }, log, token); } public static async Task<NuGetVersion> GetLatestVersionAsync( string packageId, NuGetProject project, ResolutionContext resolutionContext, IEnumerable<SourceRepository> sources, Common.ILogger log, CancellationToken token) { var tasks = new List<Task<NuGetVersion>>(); NuGetFramework framework; if (!project.TryGetMetadata<NuGetFramework>(NuGetProjectMetadataKeys.TargetFramework, out framework)) { // Default to the any framework if the project does not specify a framework. framework = NuGetFramework.AnyFramework; } return await GetLatestVersionAsync(packageId, framework, resolutionContext, sources, log, token); } public static async Task<NuGetVersion> GetLatestVersionAsync( string packageId, NuGetFramework framework, ResolutionContext resolutionContext, IEnumerable<SourceRepository> sources, Common.ILogger log, CancellationToken token) { var tasks = new List<Task<NuGetVersion>>(); foreach (var source in sources) { tasks.Add(Task.Run(async () => await GetLatestVersionCoreAsync(packageId, framework, resolutionContext, source, log, token))); } var versions = await Task.WhenAll(tasks); return versions.Where(v => v != null).Max(); } private static async Task<NuGetVersion> GetLatestVersionCoreAsync( string packageId, NuGetFramework framework, ResolutionContext resolutionContext, SourceRepository source, Common.ILogger log, CancellationToken token) { var dependencyInfoResource = await source.GetResourceAsync<DependencyInfoResource>(); // Resolve the package for the project framework and cache the results in the // resolution context for the gather to use during the next step. // Using the metadata resource will result in multiple calls to the same url during an install. var packages = await dependencyInfoResource.ResolvePackages(packageId, framework, log, token); Debug.Assert(resolutionContext.GatherCache != null); // Cache the results, even if the package was not found. resolutionContext.GatherCache.AddAllPackagesForId( source.PackageSource, packageId, framework, packages.AsList()); // Find the latest version var latestVersion = packages.Where(package => (package.Listed || resolutionContext.IncludeUnlisted) && (resolutionContext.IncludePrerelease || !package.Version.IsPrerelease)) .OrderByDescending(package => package.Version, VersionComparer.Default) .Select(package => package.Version) .FirstOrDefault(); return latestVersion; } private IEnumerable<SourceRepository> GetEffectiveSources(IEnumerable<SourceRepository> primarySources, IEnumerable<SourceRepository> secondarySources) { // Always have to add the packages folder as the primary repository so that // dependency info for an installed package that is unlisted from the server is still available :( var effectiveSources = new List<SourceRepository>(primarySources); effectiveSources.Add(PackagesFolderSourceRepository); effectiveSources.AddRange(secondarySources); return new HashSet<SourceRepository>(effectiveSources, new SourceRepositoryComparer()); } public static void SetDirectInstall(PackageIdentity directInstall, INuGetProjectContext nuGetProjectContext) { if (directInstall != null && nuGetProjectContext != null && nuGetProjectContext.ExecutionContext != null) { var ideExecutionContext = nuGetProjectContext.ExecutionContext as IDEExecutionContext; if (ideExecutionContext != null) { ideExecutionContext.IDEDirectInstall = directInstall; } } } public static void ClearDirectInstall(INuGetProjectContext nuGetProjectContext) { if (nuGetProjectContext != null && nuGetProjectContext.ExecutionContext != null) { var ideExecutionContext = nuGetProjectContext.ExecutionContext as IDEExecutionContext; if (ideExecutionContext != null) { ideExecutionContext.IDEDirectInstall = null; } } } } }
48.167442
206
0.59954
[ "Apache-2.0" ]
OctopusDeploy/NuGet.Client
src/NuGet.Core/NuGet.PackageManagement/NuGetPackageManager.cs
124,274
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using Photon.Realtime; using Photon.Pun; using TMPro; using UnityEngine.SceneManagement; using UnityEngine.UI; public class PhotonManager : MonoBehaviourPunCallbacks { public static PhotonManager instance { get; private set; } public RoomOptions roomOptions = new RoomOptions(); public TMP_InputField red; public TMP_InputField green; public TMP_InputField blue; public GameObject panel; public string username; public int MAX_PLAYERS = 4; public float RED, GREEN, BLUE; public string winnerName; public bool matchDone = false; public int rounds; public List<int> players = new List<int>(); public bool allJoined = false; string gameVersion = "1"; string gameLevel = "Lobby"; void Awake() { if (instance) { Destroy(gameObject); } else { instance = this; gameObject.AddComponent<PhotonView>(); gameObject.GetPhotonView().ViewID = 999; DontDestroyOnLoad(this); } //SceneManager.sceneLoaded += OnSceneLoaded; PhotonNetwork.AutomaticallySyncScene = true; roomOptions.MaxPlayers = (byte)MAX_PLAYERS; } void Start() { Connect(); } /// <summary> /// Connects user to master server /// </summary> public void Connect() { if (!PhotonNetwork.IsConnected) { PhotonNetwork.ConnectUsingSettings(); PhotonNetwork.GameVersion = gameVersion; MainMenu.instance.connectedText.SetActive(true); MainMenu.instance.hasBeenConnected = true; } else { MainMenu.instance.connectedText.SetActive(true); MainMenu.instance.hasBeenConnected = true; } } public void CreateRoom() { Debug.Log("[PhotonManager][CreateRoom][Trying to create room]"); PhotonNetwork.NickName = MainMenu.instance.inputField.text; PhotonNetwork.CreateRoom("Test Room", roomOptions); } public void JoinRandomRoom() { Debug.Log("[PhotonManager][JoinRandomRoom][Trying to join random room]"); PhotonNetwork.NickName = MainMenu.instance.inputField.text; PhotonNetwork.JoinRandomRoom(); } public void JoinChatroom() { Debug.Log("[PhotonManager][JoinChatroom][Trying to join random room]"); PhotonNetwork.NickName = MainMenu.instance.inputField.text; PhotonNetwork.JoinRandomRoom(); } public void ChangeColor() { float redVal, greenVal, blueVal; if (!string.IsNullOrEmpty(red.ToString())) { float.TryParse(red.text.ToString(), out float resultRed); redVal = resultRed; RED = redVal; red.text = ""; } else { redVal = 0; RED = 0; } if (!string.IsNullOrEmpty(green.ToString())) { float.TryParse(green.text.ToString(), out float resultGreen); greenVal = resultGreen; GREEN = greenVal; green.text = ""; } else { greenVal = 0; GREEN = 0; } if (!string.IsNullOrEmpty(blue.ToString())) { float.TryParse(blue.text.ToString(), out float resultBlue); blueVal = resultBlue; BLUE = blueVal; blue.text = ""; } else { blueVal = 0; BLUE = 0; } panel.GetComponent<Image>().color = new Color32((byte)redVal, (byte)greenVal, (byte)blueVal, (byte)255); } #region Photon Callbacks public override void OnConnectedToMaster() { Debug.Log("[PhotonManager][Connected to Master]"); } public override void OnCreatedRoom() { Debug.Log("[PhotonManager][OnCreatedRoom]"); } public override void OnJoinedRoom() { Debug.Log("[PhotonManager][OnJoinedRoom]"); if (PhotonNetwork.IsMasterClient) { PhotonNetwork.LoadLevel(gameLevel); } } public override void OnDisconnected(DisconnectCause cause) { Debug.Log("[PhotonManager][OnDisconnected] " + cause); } public override void OnCreateRoomFailed(short returnCode, string message) { Debug.Log("[PhotonManager][OnCreateRoomFailed] " + message); JoinRandomRoom(); } public override void OnJoinRandomFailed(short returnCode, string message) { Debug.Log("[PhotonManager][OnJoinRandomFailed] " + message); CreateRoom(); } public override void OnLeftRoom() { Cursor.lockState = CursorLockMode.None; Cursor.visible = true; SceneManager.LoadScene("MainMenu"); } void OnSceneLoaded(Scene scene, LoadSceneMode mode) { if (instance != this) { //PhotonNetwork.Destroy(gameObject); } } #endregion #region RPC's [PunRPC] void LobbyChatRPC(string _username, string _chat) { Lobby.instance.field.text += _username + ": " + _chat + "\n"; } [PunRPC] void UpdateLobbyTimer(float t) { foreach (Lobby l in FindObjectsOfType<Lobby>()) { l.timer.text = Mathf.Round(t).ToString(); } } #endregion }
20.468468
106
0.705546
[ "MIT" ]
Gabe-B/AGGP225_GabeBlack_Final
AGGP225_GabeBlack_FinalProj/Assets/Scripts/PhotonManager.cs
4,544
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 codecommit-2015-04-13.normal.json service model. */ using System; using Amazon.Runtime; using Amazon.Util.Internal; namespace Amazon.CodeCommit { /// <summary> /// Configuration for accessing Amazon CodeCommit service /// </summary> public partial class AmazonCodeCommitConfig : ClientConfig { private static readonly string UserAgentString = InternalSDKUtils.BuildUserAgentString("3.3.0.0"); private string _userAgent = UserAgentString; /// <summary> /// Default constructor /// </summary> public AmazonCodeCommitConfig() { this.AuthenticationServiceName = "codecommit"; } /// <summary> /// The constant used to lookup in the region hash the endpoint. /// </summary> public override string RegionEndpointServiceName { get { return "codecommit"; } } /// <summary> /// Gets the ServiceVersion property. /// </summary> public override string ServiceVersion { get { return "2015-04-13"; } } /// <summary> /// Gets the value of UserAgent property. /// </summary> public override string UserAgent { get { return _userAgent; } } } }
26.2625
108
0.589243
[ "Apache-2.0" ]
brainmurphy/aws-sdk-net
sdk/src/Services/CodeCommit/Generated/AmazonCodeCommitConfig.cs
2,101
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information. using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Testing; using Test.Utilities; using Xunit; using VerifyCS = Test.Utilities.CSharpCodeFixVerifier< Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.TypeNamesShouldNotMatchNamespacesAnalyzer, Microsoft.CodeQuality.CSharp.Analyzers.ApiDesignGuidelines.CSharpTypeNamesShouldNotMatchNamespacesFixer>; using VerifyVB = Test.Utilities.VisualBasicCodeFixVerifier< Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.TypeNamesShouldNotMatchNamespacesAnalyzer, Microsoft.CodeQuality.VisualBasic.Analyzers.ApiDesignGuidelines.BasicTypeNamesShouldNotMatchNamespacesFixer>; namespace Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.UnitTests { public class TypeNamesShouldNotMatchNamespacesTests { private static DiagnosticResult CSharpDefaultResultAt(int line, int column, string typeName, string namespaceName) #pragma warning disable RS0030 // Do not used banned APIs => VerifyCS.Diagnostic(TypeNamesShouldNotMatchNamespacesAnalyzer.DefaultRule) .WithLocation(line, column) #pragma warning restore RS0030 // Do not used banned APIs .WithArguments(typeName, namespaceName); private static DiagnosticResult CSharpSystemResultAt(int line, int column, string typeName, string namespaceName) #pragma warning disable RS0030 // Do not used banned APIs => VerifyCS.Diagnostic(TypeNamesShouldNotMatchNamespacesAnalyzer.SystemRule) .WithLocation(line, column) #pragma warning restore RS0030 // Do not used banned APIs .WithArguments(typeName, namespaceName); private static DiagnosticResult BasicDefaultResultAt(int line, int column, string typeName, string namespaceName) #pragma warning disable RS0030 // Do not used banned APIs => VerifyVB.Diagnostic(TypeNamesShouldNotMatchNamespacesAnalyzer.DefaultRule) .WithLocation(line, column) #pragma warning restore RS0030 // Do not used banned APIs .WithArguments(typeName, namespaceName); private static DiagnosticResult BasicSystemResultAt(int line, int column, string typeName, string namespaceName) #pragma warning disable RS0030 // Do not used banned APIs => VerifyVB.Diagnostic(TypeNamesShouldNotMatchNamespacesAnalyzer.SystemRule) .WithLocation(line, column) #pragma warning restore RS0030 // Do not used banned APIs .WithArguments(typeName, namespaceName); [Fact] public async Task CA1724CSharpValidName() { await VerifyCS.VerifyAnalyzerAsync(@" public class C { }"); } [Fact] public async Task CA1724CSharpInvalidNameMatchingFormsNamespaceInSystemRule() { await VerifyCS.VerifyAnalyzerAsync(@" public class Forms { }", CSharpSystemResultAt(2, 14, "Forms", "System.Windows.Forms")); } [Fact, WorkItem(1432, "https://github.com/dotnet/roslyn-analyzers/issues/1432")] public async Task CA1724CSharpInvalidNameMatchingFormsNamespaceInSystemRule_Internal_NoDiagnostic() { await VerifyCS.VerifyAnalyzerAsync(@" internal class Forms { } public class Outer { private class Forms { } } internal class Outer2 { public class Forms { } } "); } [Fact] public async Task CA1724CSharpInvalidNameMatchingSdkNamespaceInDefaultRule() { await new VerifyCS.Test { TestState = { Sources = { @" public class Sdk { } ", }, AdditionalReferences = { MetadataReference.CreateFromFile(typeof(Xunit.Sdk.AllException).Assembly.Location) } }, ExpectedDiagnostics = { CSharpDefaultResultAt(2, 14, "Sdk", "Xunit.Sdk"), } }.RunAsync(); } [Fact, WorkItem(1673, "https://github.com/dotnet/roslyn-analyzers/issues/1673")] public async Task CA1724CSharp_NoDiagnostic_NamespaceWithNoTypes() { await VerifyCS.VerifyAnalyzerAsync(@" namespace A.B { } namespace D { public class A {} }"); } [Fact, WorkItem(1673, "https://github.com/dotnet/roslyn-analyzers/issues/1673")] public async Task CA1724CSharp_NoDiagnostic_NamespaceWithNoExternallyVisibleTypes() { await VerifyCS.VerifyAnalyzerAsync(@" namespace A { internal class C { } } namespace D { public class A {} }"); } [Fact, WorkItem(1673, "https://github.com/dotnet/roslyn-analyzers/issues/1673")] public async Task CA1724CSharp_NoDiagnostic_NamespaceWithNoExternallyVisibleTypes_02() { await VerifyCS.VerifyAnalyzerAsync(@" namespace A { namespace B { internal class C { } } } namespace D { public class A {} }"); } [Fact, WorkItem(1673, "https://github.com/dotnet/roslyn-analyzers/issues/1673")] public async Task CA1724CSharp_NoDiagnostic_ClashingTypeIsNotExternallyVisible() { await VerifyCS.VerifyAnalyzerAsync(@" namespace A { namespace B { public class C { } } } namespace D { internal class A {} }"); } [Fact, WorkItem(1673, "https://github.com/dotnet/roslyn-analyzers/issues/1673")] public async Task CA1724CSharp_Diagnostic_NamespaceWithExternallyVisibleTypeMember() { await VerifyCS.VerifyAnalyzerAsync(@" namespace A { public class C { } } namespace D { public class A {} }", // Test0.cs(9,18): warning CA1724: The type name A conflicts in whole or in part with the namespace name 'A'. Change either name to eliminate the conflict. CSharpDefaultResultAt(9, 18, "A", "A")); } [Fact, WorkItem(1673, "https://github.com/dotnet/roslyn-analyzers/issues/1673")] public async Task CA1724CSharp_Diagnostic_NamespaceWithExternallyVisibleTypeMember_02() { await VerifyCS.VerifyAnalyzerAsync(@" namespace B { namespace A { public class C { } } } namespace D { public class A {} }", // Test0.cs(12,18): warning CA1724: The type name A conflicts in whole or in part with the namespace name 'B.A'. Change either name to eliminate the conflict. CSharpDefaultResultAt(12, 18, "A", "B.A")); } [Fact, WorkItem(1673, "https://github.com/dotnet/roslyn-analyzers/issues/1673")] public async Task CA1724CSharp_Diagnostic_NamespaceWithExternallyVisibleTypeMember_InChildNamespace() { await VerifyCS.VerifyAnalyzerAsync(@" namespace A { namespace B { public class C { } } } namespace D { public class A {} }", // Test0.cs(12,18): warning CA1724: The type name A conflicts in whole or in part with the namespace name 'A'. Change either name to eliminate the conflict. CSharpDefaultResultAt(12, 18, "A", "A")); } [Fact, WorkItem(1673, "https://github.com/dotnet/roslyn-analyzers/issues/1673")] public async Task CA1724CSharp_Diagnostic_NamespaceWithExternallyVisibleTypeMember_InChildNamespace_02() { await VerifyCS.VerifyAnalyzerAsync(@" namespace A.B { public class C { } } namespace D { public class A {} }", // Test0.cs(9,18): warning CA1724: The type name A conflicts in whole or in part with the namespace name 'A'. Change either name to eliminate the conflict. CSharpDefaultResultAt(9, 18, "A", "A")); } [Fact] public async Task CA1724VisualBasicValidName() { await VerifyVB.VerifyAnalyzerAsync(@" Public Class C End Class"); } [Fact] public async Task CA1724VisualBasicInvalidNameMatchingFormsNamespaceInSystemRule() { await VerifyVB.VerifyAnalyzerAsync(@" Public Class Forms End Class", BasicSystemResultAt(2, 14, "Forms", "System.Windows.Forms")); } [Fact, WorkItem(1432, "https://github.com/dotnet/roslyn-analyzers/issues/1432")] public async Task CA1724VisualBasicInvalidNameMatchingFormsNamespaceInSystemRule_Internal_NoDiagnostic() { await VerifyVB.VerifyAnalyzerAsync(@" Friend Class Forms End Class Public Class Outer Private Class Forms End Class End Class Friend Class Outer2 Public Class Forms End Class End Class "); } [Fact] public async Task CA1724VisualBasicInvalidNameMatchingSdkNamespaceInDefaultRule() { await new VerifyVB.Test { TestState = { Sources = { @" Public Class Sdk End Class" }, AdditionalReferences = { MetadataReference.CreateFromFile(typeof(Xunit.Sdk.AllException).Assembly.Location) } }, ExpectedDiagnostics = { BasicDefaultResultAt(2, 14, "Sdk", "Xunit.Sdk"), } }.RunAsync(); } } }
30.273312
170
0.65077
[ "MIT" ]
AndreasVolkmann/roslyn-analyzers
src/NetAnalyzers/UnitTests/Microsoft.CodeQuality.Analyzers/ApiDesignGuidelines/TypeNamesShouldNotMatchNamespacesTests.cs
9,415
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("AerospikeTest")] [assembly: AssemblyDescription("Aerospike Client Tests")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Aerospike")] [assembly: AssemblyProduct("AerospikeTest")] [assembly: AssemblyCopyright("Copyright © 2012-2019")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("3d78e323-1ecd-4a0d-94a9-3e04fbc443db")] // 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("3.9.1")] [assembly: AssemblyFileVersion("3.9.1")]
38.583333
84
0.75522
[ "MIT" ]
Jac21/aerospike-client-csharp
Framework/AerospikeTest/Properties/AssemblyInfo.cs
1,390
C#
using LiveChartsCore.SkiaSharpView.WinForms; using System.Windows.Forms; using ViewModelsSamples.Axes.DateTimeScaled; namespace WinFormsSample.Axes.DateTimeScaled { public partial class View : UserControl { private readonly CartesianChart cartesianChart; public View() { InitializeComponent(); Size = new System.Drawing.Size(50, 50); var viewModel = new ViewModel(); cartesianChart = new CartesianChart { Series = viewModel.Series, XAxes = viewModel.XAxes, // out of livecharts properties... Location = new System.Drawing.Point(0, 0), Size = new System.Drawing.Size(50, 50), Anchor = AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top | AnchorStyles.Bottom }; Controls.Add(cartesianChart); } } }
28.30303
104
0.592077
[ "MIT" ]
Diademics-Pty-Ltd/LiveCharts2
samples/WinFormsSample/Axes/DateTimeScaled/View.cs
936
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.ElasticInference")] #if BCL35 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - Amazon Elastic Inference. Amazon Elastic Inference allows customers to attach Elastic Inference Accelerators to Amazon EC2 and Amazon ECS tasks, thus providing low-cost GPU-powered acceleration and reducing the cost of running deep learning inference. This release allows customers to add or remove tags for their Elastic Inference Accelerators.")] #elif BCL45 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (4.5) - Amazon Elastic Inference. Amazon Elastic Inference allows customers to attach Elastic Inference Accelerators to Amazon EC2 and Amazon ECS tasks, thus providing low-cost GPU-powered acceleration and reducing the cost of running deep learning inference. This release allows customers to add or remove tags for their Elastic Inference Accelerators.")] #elif PCL [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (PCL) - Amazon Elastic Inference. Amazon Elastic Inference allows customers to attach Elastic Inference Accelerators to Amazon EC2 and Amazon ECS tasks, thus providing low-cost GPU-powered acceleration and reducing the cost of running deep learning inference. This release allows customers to add or remove tags for their Elastic Inference Accelerators.")] #elif UNITY [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (Unity) - Amazon Elastic Inference. Amazon Elastic Inference allows customers to attach Elastic Inference Accelerators to Amazon EC2 and Amazon ECS tasks, thus providing low-cost GPU-powered acceleration and reducing the cost of running deep learning inference. This release allows customers to add or remove tags for their Elastic Inference Accelerators.")] #elif NETSTANDARD13 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (NetStandard 1.3)- Amazon Elastic Inference. Amazon Elastic Inference allows customers to attach Elastic Inference Accelerators to Amazon EC2 and Amazon ECS tasks, thus providing low-cost GPU-powered acceleration and reducing the cost of running deep learning inference. This release allows customers to add or remove tags for their Elastic Inference Accelerators.")] #elif NETSTANDARD20 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (NetStandard 2.0)- Amazon Elastic Inference. Amazon Elastic Inference allows customers to attach Elastic Inference Accelerators to Amazon EC2 and Amazon ECS tasks, thus providing low-cost GPU-powered acceleration and reducing the cost of running deep learning inference. This release allows customers to add or remove tags for their Elastic Inference Accelerators.")] #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 2009-2020 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.3.102.15")] #if WINDOWS_PHONE || UNITY [assembly: System.CLSCompliant(false)] # else [assembly: System.CLSCompliant(true)] #endif #if BCL [assembly: System.Security.AllowPartiallyTrustedCallers] #endif
72.677966
437
0.796875
[ "Apache-2.0" ]
NGL321/aws-sdk-net
sdk/src/Services/ElasticInference/Properties/AssemblyInfo.cs
4,288
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using System.Windows.Data; using System.Windows.Media.Imaging; namespace cs4rsa.Converters.DialogConverters { class Base64ImageConverter: IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { if (!(value is string s)) return null; BitmapImage bi = new BitmapImage(); Regex regex = new Regex(@"^[\w/\:.-]+;base64,"); s = regex.Replace(s, string.Empty); bi.BeginInit(); bi.StreamSource = new MemoryStream(System.Convert.FromBase64String(s)); bi.EndInit(); return bi; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } } }
29.666667
124
0.647004
[ "MIT" ]
toky0s/cs4rsa
cs4rsa/Converters/DialogConverters/Base64ImageConverter.cs
1,070
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace BAFactory.Fx.Security.Areas.Membership.Extensions { public static class FormsFieldsNames { /// <summary> /// Las propiedades de esta clase deben contener valores acordes a la la estructura /// de nombres de la propiedades de la clase FilterInformation antecedidas por el texto "FILTER_" /// </summary> public static class FilterForm { public static string UserId { get { return "FILTER_User_Id"; } private set { return; } } public static string UserName { get { return "FILTER_User_Name"; } private set { return; } } public static string AreaId { get { return "FILTER_Area_Id"; } private set { return; } } public static string Sort { get { return "FILTER_Sort"; } private set { return; } } } public static string Username { get { return "USERNAME"; } private set { return; } } public static string ActionId { get { return "IdAction"; } private set { return; } } public static string ModuleId { get { return "IdModule"; } private set { return; } } public static string AreaId { get { return "IdArea"; } private set { return; } } public static string UserId { get { return "IdUser"; } private set { return; } } } }
26.478873
106
0.467553
[ "Apache-2.0" ]
carlos-takeapps/bafactoryfx
Membership Managed Website/Membership Managed Website/Areas/Membership/Extensions/FormsFieldsNames.cs
1,882
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace _03.Nether_Realms { class Program { static void Main(string[] args) { var demons = Console.ReadLine() .Split(", ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries) .ToArray(); foreach (var demon in demons.OrderBy(n => n)) { var health = 0; var damage = 0.0; var regexLetters = new Regex(@"[^\d\*\/\+\.\-]"); MatchCollection letters = regexLetters.Matches(demon); foreach (Match letter in letters) { health += char.Parse(letter.Value); } var regexDigits = new Regex(@"([\-|\+])*(\d+\.)*\d+"); MatchCollection digits = regexDigits.Matches(demon); foreach (Match digit in digits) { damage += double.Parse(digit.Value); } var regexSymbols = new Regex(@"[\*|\/]"); MatchCollection symbols = regexSymbols.Matches(demon); foreach (Match symbol in symbols) { if (symbol.Value == "*") { damage *= 2; } else if (symbol.Value == "/") { damage /= 2; } } Console.WriteLine("{0} - {1} health, {2:F2} damage ", demon, health, damage); } } } }
30.625
93
0.441983
[ "MIT" ]
AneliaDoychinova/Programming-Fundamentals
13. Exam Preparation/Exam Preparation 2/03. Nether Realms/03. Nether Realms.cs
1,717
C#
using System.Threading.Tasks; using AElf.OS.Network.Application; using AElf.OS.Network.Infrastructure; using Shouldly; using Xunit; namespace AElf.OS.Network { public class PeerInvalidTransactionProviderTests: NetworkInfrastructureTestBase { private readonly IPeerInvalidTransactionProvider _peerInvalidTransactionProvider; public PeerInvalidTransactionProviderTests() { _peerInvalidTransactionProvider = GetRequiredService<IPeerInvalidTransactionProvider>(); } [Fact] public void MarkInvalidTransaction_Test() { var host = "127.0.0.1"; bool markResult; for (var i = 0; i < 5; i++) { markResult =_peerInvalidTransactionProvider.TryMarkInvalidTransaction(host); markResult.ShouldBeTrue(); } markResult =_peerInvalidTransactionProvider.TryMarkInvalidTransaction(host); markResult.ShouldBeFalse(); markResult =_peerInvalidTransactionProvider.TryMarkInvalidTransaction("192.168.1.1"); markResult.ShouldBeTrue(); _peerInvalidTransactionProvider.TryRemoveInvalidRecord(host); markResult =_peerInvalidTransactionProvider.TryMarkInvalidTransaction(host); markResult.ShouldBeTrue(); } [Fact] public async Task MarkInvalidTransaction_Timeout_Test() { var host = "127.0.0.1"; bool markResult; for (var i = 0; i < 5; i++) { markResult =_peerInvalidTransactionProvider.TryMarkInvalidTransaction(host); markResult.ShouldBeTrue(); } markResult =_peerInvalidTransactionProvider.TryMarkInvalidTransaction(host); markResult.ShouldBeFalse(); markResult =_peerInvalidTransactionProvider.TryMarkInvalidTransaction("192.168.1.1"); markResult.ShouldBeTrue(); await Task.Delay(1500); markResult =_peerInvalidTransactionProvider.TryMarkInvalidTransaction(host); markResult.ShouldBeTrue(); } } }
35.015625
100
0.622936
[ "MIT" ]
ezaruba/AElf
test/AElf.OS.Core.Tests/Network/Infrastructure/PeerInvalidTransactionProviderTests.cs
2,241
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("OperationBetweenNumbers")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("HP Inc.")] [assembly: AssemblyProduct("OperationBetweenNumbers")] [assembly: AssemblyCopyright("Copyright © HP Inc. 2019")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("fe630d34-39f8-42a6-881e-7a821ba835be")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.594595
84
0.751401
[ "MIT" ]
Martin-Stamenkov/Csharp-SoftUni
Programmig Basics/Nested Conditional Statements/OperationBetweenNumbers/Properties/AssemblyInfo.cs
1,431
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 imagebuilder-2019-12-02.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.Imagebuilder.Model { /// <summary> /// Container for the parameters to the CreateImagePipeline operation. /// Creates a new image pipeline. Image pipelines enable you to automate the creation /// and distribution of images. /// </summary> public partial class CreateImagePipelineRequest : AmazonImagebuilderRequest { private string _clientToken; private string _description; private string _distributionConfigurationArn; private bool? _enhancedImageMetadataEnabled; private string _imageRecipeArn; private ImageTestsConfiguration _imageTestsConfiguration; private string _infrastructureConfigurationArn; private string _name; private Schedule _schedule; private PipelineStatus _status; private Dictionary<string, string> _tags = new Dictionary<string, string>(); /// <summary> /// Gets and sets the property ClientToken. /// <para> /// The idempotency token used to make this request idempotent. /// </para> /// </summary> [AWSProperty(Min=1, Max=36)] public string ClientToken { get { return this._clientToken; } set { this._clientToken = value; } } // Check to see if ClientToken property is set internal bool IsSetClientToken() { return this._clientToken != null; } /// <summary> /// Gets and sets the property Description. /// <para> /// The description of the image pipeline. /// </para> /// </summary> [AWSProperty(Min=1, Max=1024)] public string Description { get { return this._description; } set { this._description = value; } } // Check to see if Description property is set internal bool IsSetDescription() { return this._description != null; } /// <summary> /// Gets and sets the property DistributionConfigurationArn. /// <para> /// The Amazon Resource Name (ARN) of the distribution configuration that will be used /// to configure and distribute images created by this image pipeline. /// </para> /// </summary> public string DistributionConfigurationArn { get { return this._distributionConfigurationArn; } set { this._distributionConfigurationArn = value; } } // Check to see if DistributionConfigurationArn property is set internal bool IsSetDistributionConfigurationArn() { return this._distributionConfigurationArn != null; } /// <summary> /// Gets and sets the property EnhancedImageMetadataEnabled. /// <para> /// Collects additional information about the image being created, including the operating /// system (OS) version and package list. This information is used to enhance the overall /// experience of using EC2 Image Builder. Enabled by default. /// </para> /// </summary> public bool EnhancedImageMetadataEnabled { get { return this._enhancedImageMetadataEnabled.GetValueOrDefault(); } set { this._enhancedImageMetadataEnabled = value; } } // Check to see if EnhancedImageMetadataEnabled property is set internal bool IsSetEnhancedImageMetadataEnabled() { return this._enhancedImageMetadataEnabled.HasValue; } /// <summary> /// Gets and sets the property ImageRecipeArn. /// <para> /// The Amazon Resource Name (ARN) of the image recipe that will be used to configure /// images created by this image pipeline. /// </para> /// </summary> [AWSProperty(Required=true)] public string ImageRecipeArn { get { return this._imageRecipeArn; } set { this._imageRecipeArn = value; } } // Check to see if ImageRecipeArn property is set internal bool IsSetImageRecipeArn() { return this._imageRecipeArn != null; } /// <summary> /// Gets and sets the property ImageTestsConfiguration. /// <para> /// The image test configuration of the image pipeline. /// </para> /// </summary> public ImageTestsConfiguration ImageTestsConfiguration { get { return this._imageTestsConfiguration; } set { this._imageTestsConfiguration = value; } } // Check to see if ImageTestsConfiguration property is set internal bool IsSetImageTestsConfiguration() { return this._imageTestsConfiguration != null; } /// <summary> /// Gets and sets the property InfrastructureConfigurationArn. /// <para> /// The Amazon Resource Name (ARN) of the infrastructure configuration that will be used /// to build images created by this image pipeline. /// </para> /// </summary> [AWSProperty(Required=true)] public string InfrastructureConfigurationArn { get { return this._infrastructureConfigurationArn; } set { this._infrastructureConfigurationArn = value; } } // Check to see if InfrastructureConfigurationArn property is set internal bool IsSetInfrastructureConfigurationArn() { return this._infrastructureConfigurationArn != null; } /// <summary> /// Gets and sets the property Name. /// <para> /// The name of the image pipeline. /// </para> /// </summary> [AWSProperty(Required=true)] 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 Schedule. /// <para> /// The schedule of the image pipeline. /// </para> /// </summary> public Schedule Schedule { get { return this._schedule; } set { this._schedule = value; } } // Check to see if Schedule property is set internal bool IsSetSchedule() { return this._schedule != null; } /// <summary> /// Gets and sets the property Status. /// <para> /// The status of the image pipeline. /// </para> /// </summary> public PipelineStatus Status { get { return this._status; } set { this._status = value; } } // Check to see if Status property is set internal bool IsSetStatus() { return this._status != null; } /// <summary> /// Gets and sets the property Tags. /// <para> /// The tags of the image pipeline. /// </para> /// </summary> [AWSProperty(Min=1, Max=50)] public Dictionary<string, string> Tags { get { return this._tags; } set { this._tags = value; } } // Check to see if Tags property is set internal bool IsSetTags() { return this._tags != null && this._tags.Count > 0; } } }
32.752896
110
0.586585
[ "Apache-2.0" ]
NGL321/aws-sdk-net
sdk/src/Services/Imagebuilder/Generated/Model/CreateImagePipelineRequest.cs
8,483
C#
namespace Spritesheet { using System.Linq; public class AnimationDefinition { public AnimationDefinition(string name, Frame[] frames) { this.Name = name; } public string Name { get; } } }
12.9375
57
0.68599
[ "MIT" ]
aloisdeniel/Spritesheet
Sources/Spritesheet/AnimationDefinition.cs
209
C#
/* // <copyright> // dotNetRDF is free and open source software licensed under the MIT License // ------------------------------------------------------------------------- // // Copyright (c) 2009-2020 dotNetRDF Project (http://dotnetrdf.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is furnished // to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // </copyright> */ using VDS.RDF; namespace VDS.RDF.Query.Spin.Constraints { /** * A SimplePropertyPath of the form SP->O. * * @author Holger Knublauch */ internal class ObjectPropertyPath : SimplePropertyPath { public ObjectPropertyPath(INode subject, INode predicate) : base(subject, predicate) { } } }
37.043478
84
0.68838
[ "MIT" ]
blackwork/dotnetrdf
Libraries/dotNetRDF.Query.Spin/Constraints/ObjectPropertyPath.cs
1,704
C#
using System; using MikhailKhalizev.Processor.x86.BinToCSharp; namespace MikhailKhalizev.Max.Program { public partial class RawProgram { [MethodInfo("0x18_dd10-f569078c")] public void Method_0018_dd10() { ii(0x18_dd10, 2); mov(di, ss); /* mov di, ss */ ii(0x18_dd12, 4); lar(edi, di); /* lar edi, di */ ii(0x18_dd16, 5); bt(edi, 0x16); /* bt edi, 0x16 */ ii(0x18_dd1b, 1); pop(di); /* pop di */ ii(0x18_dd1c, 5); push(memd[ds, 0xc18]); /* push dword [0xc18] */ ii(0x18_dd21, 4); push(memw[ds, 0xc1c]); /* push word [0xc1c] */ ii(0x18_dd25, 5); mov(memd[ds, 0xc18], esp); /* mov [0xc18], esp */ ii(0x18_dd2a, 2); if(jb(0x18_dd32, 6)) goto l_0x18_dd32; /* jb 0xdd32 */ ii(0x18_dd2c, 6); mov(memw[ds, 0xc1a], 0); /* mov word [0xc1a], 0x0 */ l_0x18_dd32: ii(0x18_dd32, 4); mov(memw[ds, 0xc1c], ss); /* mov [0xc1c], ss */ ii(0x18_dd36, 6); sub(memw[ds, 0x996], 0x180); /* sub word [0x996], 0x180 */ ii(0x18_dd3c, 1); push(ds); /* push ds */ ii(0x18_dd3d, 1); pop(ss); /* pop ss */ ii(0x18_dd3e, 6); movzx(esp, memw[ds, 0x996]); /* movzx esp, word [0x996] */ ii(0x18_dd44, 3); sub(sp, 0x10); /* sub sp, 0x10 */ ii(0x18_dd47, 2); jmp_abs(di); /* jmp di */ } } }
57
101
0.415393
[ "Apache-2.0" ]
mikhail-khalizev/max
source/MikhailKhalizev.Max/source/Program/Auto/z-0018-dd10.cs
1,767
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("FSL.CyclomaticComplexity")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("FSL.CyclomaticComplexity")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("124e7c73-4102-481e-ac12-9054ebd7898c")] // 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 Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.222222
84
0.75436
[ "MIT" ]
fabiosilvalima/FSL.CyclomaticComplexity
FSL.CyclomaticComplexity/Properties/AssemblyInfo.cs
1,379
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. namespace Microsoft.Azure.PowerShell.Cmdlets.Functions.Support { /// <summary> /// Used by the Application Insights system to determine what kind of flow this component was created by. This is to be set /// to 'Bluefield' when creating/updating a component via the REST API. /// </summary> public partial struct FlowType : System.IEquatable<FlowType> { public static Microsoft.Azure.PowerShell.Cmdlets.Functions.Support.FlowType Bluefield = @"Bluefield"; /// <summary>the value for an instance of the <see cref="FlowType" /> Enum.</summary> private string _value { get; set; } /// <summary>Conversion from arbitrary object to FlowType</summary> /// <param name="value">the value to convert to an instance of <see cref="FlowType" />.</param> internal static object CreateFrom(object value) { return new FlowType(System.Convert.ToString(value)); } /// <summary>Compares values of enum type FlowType</summary> /// <param name="e">the value to compare against this instance.</param> /// <returns><c>true</c> if the two instances are equal to the same value</returns> public bool Equals(Microsoft.Azure.PowerShell.Cmdlets.Functions.Support.FlowType e) { return _value.Equals(e._value); } /// <summary>Compares values of enum type FlowType (override for Object)</summary> /// <param name="obj">the value to compare against this instance.</param> /// <returns><c>true</c> if the two instances are equal to the same value</returns> public override bool Equals(object obj) { return obj is FlowType && Equals((FlowType)obj); } /// <summary>Creates an instance of the <see cref="FlowType" Enum class./></summary> /// <param name="underlyingValue">the value to create an instance for.</param> private FlowType(string underlyingValue) { this._value = underlyingValue; } /// <summary>Returns hashCode for enum FlowType</summary> /// <returns>The hashCode of the value</returns> public override int GetHashCode() { return this._value.GetHashCode(); } /// <summary>Returns string representation for FlowType</summary> /// <returns>A string for this value.</returns> public override string ToString() { return this._value; } /// <summary>Implicit operator to convert string to FlowType</summary> /// <param name="value">the value to convert to an instance of <see cref="FlowType" />.</param> public static implicit operator FlowType(string value) { return new FlowType(value); } /// <summary>Implicit operator to convert FlowType to string</summary> /// <param name="e">the value to convert to an instance of <see cref="FlowType" />.</param> public static implicit operator string(Microsoft.Azure.PowerShell.Cmdlets.Functions.Support.FlowType e) { return e._value; } /// <summary>Overriding != operator for enum FlowType</summary> /// <param name="e1">the value to compare against <see cref="e2" /></param> /// <param name="e2">the value to compare against <see cref="e1" /></param> /// <returns><c>true</c> if the two instances are not equal to the same value</returns> public static bool operator !=(Microsoft.Azure.PowerShell.Cmdlets.Functions.Support.FlowType e1, Microsoft.Azure.PowerShell.Cmdlets.Functions.Support.FlowType e2) { return !e2.Equals(e1); } /// <summary>Overriding == operator for enum FlowType</summary> /// <param name="e1">the value to compare against <see cref="e2" /></param> /// <param name="e2">the value to compare against <see cref="e1" /></param> /// <returns><c>true</c> if the two instances are equal to the same value</returns> public static bool operator ==(Microsoft.Azure.PowerShell.Cmdlets.Functions.Support.FlowType e1, Microsoft.Azure.PowerShell.Cmdlets.Functions.Support.FlowType e2) { return e2.Equals(e1); } } }
47.262626
171
0.629408
[ "MIT" ]
3quanfeng/azure-powershell
src/Functions/generated/api/Support/FlowType.cs
4,581
C#
namespace Symbolica.Implementation.System; public interface IFile { long LastAccessTime { get; } long LastModifiedTime { get; } long Size { get; } int Read(byte[] bytes, long offset, int count); }
19.636364
51
0.680556
[ "MIT" ]
Symbolica/Symbolica
src/Implementation/System/IFile.cs
218
C#
using Kros.Utils; using System; namespace Kros.Data.Schema { /// <summary> /// Schema of a column of an index. /// </summary> public class IndexColumnSchema { #region Constructors /// <summary> /// Creates an instance of an index column with <paramref name="name"/>. Column sort <see cref="Order"/> is /// <see cref="SortOrder.Ascending"/>. /// </summary> /// <param name="name">Index column name.</param> /// <exception cref="ArgumentNullException">Value of <paramref name="name"/> is <see langword="null"/>.</exception> /// <exception cref="ArgumentException">Value of <paramref name="name"/> is empty string, or string containing only /// whitespace characters.</exception> public IndexColumnSchema(string name) : this(name, SortOrder.Ascending) { } /// <summary> /// Creates an instance of an index column with <paramref name="name"/> and sort <paramref name="order"/>. /// </summary> /// <param name="name">Index column name.</param> /// <param name="order">Index column sort order.</param> /// <exception cref="ArgumentNullException">Value of <paramref name="name"/> is <see langword="null"/>.</exception> /// <exception cref="ArgumentException">Value of <paramref name="name"/> is empty string, or string containing only /// whitespace characters.</exception> public IndexColumnSchema(string name, SortOrder order) { Name = Check.NotNullOrWhiteSpace(name, nameof(name)); Order = order; } #endregion #region Common /// <summary> /// Column name. /// </summary> public string Name { get; } /// <summary> /// Sort order of the column. /// </summary> public SortOrder Order { get; set; } = SortOrder.Ascending; /// <summary> /// Index, to which column belongs. /// </summary> public IndexSchema Index { get; internal set; } #endregion } }
34.129032
123
0.579395
[ "MIT" ]
Abd-Elrazek/Kros.Libs
Kros.Utils/src/Kros.Utils/Data/Schema/IndexColumnSchema.cs
2,118
C#
using System; using System.Linq; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using FluentMigrator; namespace SoftwareManager.DbMigrations.Migrations { [Migration(4, TransactionBehavior.Default, "Create table ApplicationApplicationManager")] public class CreateApplicationApplicationManagerTable : Migration { private string _tableName = "ApplicationApplicationManager"; public override void Up() { Create.Table(_tableName).InSchema("dbo") .WithColumn($"{_tableName}Id").AsInt32().PrimaryKey().Identity() .WithColumn("ApplicationId").AsInt32().NotNullable() .WithColumn("ApplicationManagerId").AsInt32().NotNullable() .WithColumn("CreateDate").AsDateTime().NotNullable().WithDefaultValue(SystemMethods.CurrentUTCDateTime) .WithColumn("CreateById").AsInt32().NotNullable() .WithColumn("ModifyDate").AsDateTime().Nullable() .WithColumn("ModifyById").AsInt32().Nullable() .WithColumn("RowVersion").AsCustom("rowversion").NotNullable(); this.CreateForeignKeyWithIndex(_tableName, "CreateById", "ApplicationManager", "ApplicationManagerId"); this.CreateForeignKeyWithIndex(_tableName, "ModifyById", "ApplicationManager", "ApplicationManagerId"); this.CreateForeignKeyWithIndex(_tableName, "ApplicationId", "Application", "ApplicationId", true); this.CreateForeignKeyWithIndex(_tableName, "ApplicationManagerId", "ApplicationManager", "ApplicationManagerId"); } public override void Down() { Delete.Table(_tableName); } } }
43.325
125
0.679746
[ "MIT" ]
t0ms3n/SoftwareManager
SoftwareManager.DbMigrations/Migrations/004_CreateApplicationApplicationManagerTable.cs
1,733
C#
namespace Decorator.Components { using System; using System.Linq; public class ReverseBehavior : IModifyBehavior { public string Apply(string input) { var charArray = input .Reverse() .ToArray(); return new string(charArray); } } }
19.647059
50
0.532934
[ "MIT" ]
IanEscober/DesignPattern
src/Decorator/Components/ReverseBehavior.cs
336
C#
using Newtonsoft.Json; using Newtonsoft.Json.Serialization; namespace Pekka.ClashRoyaleApi.Client.Models.ClanModels { [JsonObject(NamingStrategyType = typeof(CamelCaseNamingStrategy))] public class ClanLocation { public int Id { get; set; } public string Name { get; set; } public bool IsCountry { get; set; } } }
23.8
70
0.686275
[ "MIT" ]
Blind-Striker/clash-royale-client-dotnet
src/Pekka.ClashRoyaleApi.Client/Models/ClanModels/ClanLocation.cs
359
C#
using UnityEngine; using System.Collections; using UnityEditor; [CanEditMultipleObjects] [CustomEditor(typeof(LoadLevelAction))] public class LoadLevelActionInspector : InspectorBase { private string explanation = "Use this script to restart the level, or load another one (load another Unity scene)."; private string sceneWarning = "WARNING: Make sure the scene is enabled in the Build Settings scenes list."; private string sceneInfo = "WARNING; To add a new level, save a Unity scene and then go to File > Build Settings... and add the scene to the list."; public override void OnInspectorGUI() { GUILayout.Space(10); EditorGUILayout.HelpBox(explanation, MessageType.Info); GUILayout.Space(10); bool displayWarning = false; if(EditorBuildSettings.scenes.Length > 0) { int sceneId = 0; string sceneNameProperty = serializedObject.FindProperty("levelName").stringValue; //get available scene names and clean the names string[] sceneNames = new string[EditorBuildSettings.scenes.Length + 1]; sceneNames[0] = "RELOAD LEVEL"; int i = 1; foreach(EditorBuildSettingsScene s in EditorBuildSettings.scenes) { int lastSlash = s.path.LastIndexOf("/"); string shortPath = s.path.Substring(lastSlash+1, s.path.Length-7-lastSlash); sceneNames[i] = shortPath; if(shortPath == sceneNameProperty) { sceneId = i; if(!s.enabled) { displayWarning = true; } } i++; } //Display the selector sceneId = EditorGUILayout.Popup("Scene to load", sceneId, sceneNames); if(displayWarning) { EditorGUILayout.HelpBox(sceneWarning, MessageType.Warning); } if(sceneId == 0) { serializedObject.FindProperty("levelName").stringValue = LoadLevelAction.SAME_SCENE; //this means same scene } else { serializedObject.FindProperty("levelName").stringValue = sceneNames[sceneId]; } } else { EditorGUILayout.Popup("Scene to load", 0, new string[]{"No scenes available!"}); EditorGUILayout.HelpBox(sceneInfo, MessageType.Warning); } if (GUI.changed) { serializedObject.ApplyModifiedProperties(); } } }
28.935065
150
0.682226
[ "MIT" ]
etcadinfinitum/games
playground/Assets/_INTERNAL_/Scripts/Editor/Conditions/Actions/LoadLevelActionInspector.cs
2,230
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System.Collections.Generic; namespace Azure.Search.Documents.Models { /// <summary> A token filter that only keeps tokens with text contained in a specified list of words. This token filter is implemented using Apache Lucene. </summary> public partial class KeepTokenFilter : TokenFilter { /// <summary> Initializes a new instance of KeepTokenFilter. </summary> public KeepTokenFilter() { ODataType = "#Microsoft.Azure.Search.KeepTokenFilter"; } /// <summary> Initializes a new instance of KeepTokenFilter. </summary> /// <param name="keepWords"> The list of words to keep. </param> /// <param name="lowerCaseKeepWords"> A value indicating whether to lower case all words first. Default is false. </param> /// <param name="oDataType"> The model type. </param> /// <param name="name"> The name of the token filter. It must only contain letters, digits, spaces, dashes or underscores, can only start and end with alphanumeric characters, and is limited to 128 characters. </param> internal KeepTokenFilter(IList<string> keepWords, bool? lowerCaseKeepWords, string oDataType, string name) : base(oDataType, name) { KeepWords = keepWords; LowerCaseKeepWords = lowerCaseKeepWords; ODataType = "#Microsoft.Azure.Search.KeepTokenFilter"; } /// <summary> The list of words to keep. </summary> public IList<string> KeepWords { get; set; } = new List<string>(); /// <summary> A value indicating whether to lower case all words first. Default is false. </summary> public bool? LowerCaseKeepWords { get; set; } } }
47.230769
226
0.67481
[ "MIT" ]
dadihe/azure-sdk-for-net
sdk/search/Azure.Search.Documents/src/Generated/Models/KeepTokenFilter.cs
1,842
C#
/* Copyright (c) Citrix Systems, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, * with or without modification, are permitted provided * that the following conditions are met: * * * Redistributions of source code must retain the above * copyright notice, this list of conditions and the * following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the * following disclaimer in the documentation and/or other * materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Text; using System.Windows.Forms; using System.Windows.Forms.VisualStyles; using XenAdmin.Core; using XenAPI; namespace XenAdmin.Controls { public partial class CustomTreeView : FlickerFreeListBox { private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// SURGEON GENERAL'S WARNING: This collection contains the infamous 'secret node'. /// To iterate only through items that you have explicity added to the treeview, use /// the Items collection instead. /// </summary> public readonly List<CustomTreeNode> Nodes = new List<CustomTreeNode>(); private VisualStyleRenderer plusRenderer; private VisualStyleRenderer minusRenderer; private CustomTreeNode lastSelected; private bool _inUpdate = false; /// <summary> /// If you want to make this into a regular listbox, set this to a smaller value, like 5 or something /// </summary> private int _nodeIndent = 19; [Browsable(true)] public int NodeIndent { get { return _nodeIndent; } set { _nodeIndent = value; } } public CustomTreeNode SecretNode = new CustomTreeNode(); private bool _showCheckboxes = true; [Browsable(true)] public bool ShowCheckboxes { get { return _showCheckboxes; } set { _showCheckboxes = value; } } private bool _showDescription = true; [Browsable(true)] public bool ShowDescription { get { return _showDescription; } set { _showDescription = value; } } private bool _showImages = false; [Browsable(true)] public bool ShowImages { get { return _showImages; } set { _showImages = value; } } /// <summary> /// The font used in descriptions. /// </summary> private Font _descriptionFont = null; public override Font Font { get { return base.Font; } set { base.Font = value; if (_descriptionFont != null) _descriptionFont.Dispose(); _descriptionFont = new Font(value.FontFamily, value.Size - 1); RecalculateWidth(); } } private bool _showRootLines = true; [Browsable(true)] public bool ShowRootLines { get { return _showRootLines; } set { _showRootLines = value; } } private bool _rootAlwaysExpanded = false; [Browsable(true)] public bool RootAlwaysExpanded { get { return _rootAlwaysExpanded; } set { _rootAlwaysExpanded = value; } } public override int ItemHeight { get { return 17; } } public CustomTreeView() { InitializeComponent(); _descriptionFont = new Font(base.Font.FontFamily, base.Font.Size - 2); if (Application.RenderWithVisualStyles) { plusRenderer = new VisualStyleRenderer(VisualStyleElement.TreeView.Glyph.Closed); minusRenderer = new VisualStyleRenderer(VisualStyleElement.TreeView.Glyph.Opened); } } public new void BeginUpdate() { _inUpdate = true; base.BeginUpdate(); } public new void EndUpdate() { _inUpdate = false; base.EndUpdate(); RecalculateWidth(); Resort(); Refresh(); } public new void Invalidate() { RecalculateWidth(); base.Invalidate(); } protected override void OnDrawItem(DrawItemEventArgs e) { base.OnDrawItem(e); if(Enabled) { using (SolidBrush backBrush = new SolidBrush(BackColor)) { e.Graphics.FillRectangle(backBrush, e.Bounds); } } else { e.Graphics.FillRectangle(SystemBrushes.Control, e.Bounds); } if (e.Index == -1 || Items.Count <= e.Index) return; CustomTreeNode node = this.Items[e.Index] as CustomTreeNode; if (node == null) return; //int indent = (node.Level + 1) * NodeIndent; int indent = node.Level * NodeIndent + (ShowRootLines ? NodeIndent : 2); int TextLength = Drawing.MeasureText(node.ToString(), e.Font).Width + 2; int TextLeft = indent + (ShowCheckboxes && !node.HideCheckbox ? ItemHeight : 0) + (ShowImages ? ItemHeight : 0); //CA-59618: add top margin to the items except the first one when rendering with //visual styles because in this case there is already one pixel of margin. int topMargin = Application.RenderWithVisualStyles && e.Index == 0 ? 0 : 1; if (Enabled && node.Selectable) { Color nodeBackColor = node.Enabled ? e.BackColor : (e.BackColor == BackColor ? BackColor : SystemColors.ControlLight); using (SolidBrush backBrush = new SolidBrush(nodeBackColor)) { e.Graphics.FillRectangle(backBrush, new Rectangle(e.Bounds.Left + TextLeft + 1, e.Bounds.Top + topMargin, TextLength - 4, e.Bounds.Height)); } } //draw expander if (node.ChildNodes.Count > 0 && (ShowRootLines || node.Level > 0)) { if (!node.Expanded) { if(Application.RenderWithVisualStyles) plusRenderer.DrawBackground(e.Graphics, new Rectangle(e.Bounds.Left + indent - ItemHeight, e.Bounds.Top + 3 + topMargin, 9, 9)); else e.Graphics.DrawImage(Properties.Resources.tree_plus, new Rectangle(e.Bounds.Left + indent - ItemHeight, e.Bounds.Top + 3 + topMargin, 9, 9)); } else { if (Application.RenderWithVisualStyles) minusRenderer.DrawBackground(e.Graphics, new Rectangle(e.Bounds.Left + indent - ItemHeight, e.Bounds.Top + 3 + topMargin, 9, 9)); else e.Graphics.DrawImage(Properties.Resources.tree_minus, new Rectangle(e.Bounds.Left + indent - ItemHeight, e.Bounds.Top + 3 + topMargin, 9, 9)); } } //draw checkboxes if (ShowCheckboxes && !node.HideCheckbox) { var checkedState = CheckBoxState.UncheckedDisabled; if (node.State == CheckState.Checked) { if (node.Enabled && Enabled) checkedState = CheckBoxState.CheckedNormal; else if (node.CheckedIfdisabled) checkedState = CheckBoxState.CheckedDisabled; } else if (node.State == CheckState.Indeterminate) { checkedState = node.Enabled && Enabled ? CheckBoxState.MixedNormal : CheckBoxState.MixedDisabled; } else if (node.State == CheckState.Unchecked) { checkedState = node.Enabled && Enabled ? CheckBoxState.UncheckedNormal : CheckBoxState.UncheckedDisabled; } CheckBoxRenderer.DrawCheckBox(e.Graphics, new Point(e.Bounds.Left + indent, e.Bounds.Top + 1 + topMargin), checkedState); indent += ItemHeight; } //draw images if (ShowImages && node.Image != null) { var rectangle = new Rectangle(e.Bounds.Left + indent, e.Bounds.Top + topMargin, node.Image.Width, node.Image.Height); if (node.Enabled && Enabled) e.Graphics.DrawImage(node.Image, rectangle); else e.Graphics.DrawImage(node.Image, rectangle, 0, 0, node.Image.Width, node.Image.Height, GraphicsUnit.Pixel, Drawing.GreyScaleAttributes); indent += ItemHeight; } //draw item's main text Color textColor = node.Enabled && Enabled ? (node.Selectable ? e.ForeColor : ForeColor) : SystemColors.GrayText; Drawing.DrawText(e.Graphics, node.ToString(), e.Font, new Point(e.Bounds.Left + indent, e.Bounds.Top + topMargin), textColor); indent += TextLength; //draw item's description if (ShowDescription) { Drawing.DrawText(e.Graphics, node.Description, _descriptionFont, new Point(e.Bounds.Left + indent, e.Bounds.Top + 1 + topMargin), SystemColors.GrayText); } } public List<CustomTreeNode> CheckedItems() { List<CustomTreeNode> nodes = new List<CustomTreeNode>(); foreach (CustomTreeNode node in Nodes) if (node.Level >= 0 && node.State == CheckState.Checked && node.Enabled) nodes.Add(node); return nodes; } public List<CustomTreeNode> CheckableItems() { List<CustomTreeNode> nodes = new List<CustomTreeNode>(); foreach (CustomTreeNode node in Nodes) if (node.Level >= 0 && node.State != CheckState.Checked && node.Enabled) nodes.Add(node); return nodes; } public void AddNode(CustomTreeNode node) { if (Nodes.Count == 0) Nodes.Add(SecretNode); SecretNode.AddChild(node); Nodes.Add(node); if (!_inUpdate) { RecalculateWidth(); Resort(); Refresh(); } } public void RemoveNode(CustomTreeNode node) { Nodes.Remove(node); if (!_inUpdate) { RecalculateWidth(); Resort(); Refresh(); } } public void AddChildNode(CustomTreeNode parent, CustomTreeNode child) { parent.AddChild(child); Nodes.Add(child); if (!_inUpdate) { RecalculateWidth(); Resort(); Refresh(); } } public void ClearAllNodes() { Nodes.Clear(); if (!_inUpdate) { RecalculateWidth(); Resort(); Refresh(); } } public void Resort() { try { lastSelected = SelectedItem as CustomTreeNode; } catch (IndexOutOfRangeException) { // Accessing ListBox.SelectedItem sometimes throws an IndexOutOfRangeException (See CA-24396) log.Warn("IndexOutOfRangeException in ListBox.SelectedItem"); lastSelected = null; } Nodes.Sort(); Items.Clear(); foreach (CustomTreeNode node in Nodes) { if (node.Level != -1 && node.ParentNode.Expanded) Items.Add(node); } SelectedItem = lastSelected; // I've yet to come across the above assignement working. If we fail to restore the selection, select something so the user can see focus feedback // (the color of the selected item is the only indication as to whether it is focused or not) // Iterating through and using CustomTreeNode.equals is useless here as it compares based on index, which I think is why the above call almost never works if (SelectedItem == null && lastSelected != null && Items.Count > 0) { SelectedItem = Items[0]; } } // Adjusts the width of the control to that of the widest row private void RecalculateWidth() { int maxWidth = 0; foreach (CustomTreeNode node in this.Nodes) { int indent = (node.Level + 1) * NodeIndent; int checkbox = ShowCheckboxes && !node.HideCheckbox ? ItemHeight : 0; int image = ShowImages ? ItemHeight : 0; int text = Drawing.MeasureText(node.ToString(), this.Font).Width + 2; int desc = ShowDescription ? Drawing.MeasureText(node.Description, _descriptionFont).Width : 0; int itemWidth = indent + checkbox + image + text + desc + 10; maxWidth = Math.Max(itemWidth, maxWidth); } // Set horizontal extent and enable scrollbar if necessary this.HorizontalExtent = maxWidth; this.HorizontalScrollbar = this.HorizontalExtent > this.Width && Enabled; } /// <summary> /// Finds next/previous node in Items collection. /// </summary> /// <param name="currentNode">Node where the search for next/previous node will start.</param> /// <param name="searchForward">Determines direction of search (search for next or previous node).</param> /// <returns></returns> protected CustomTreeNode GetNextNode(CustomTreeNode currentNode, bool searchForward) { if (currentNode == null) return null; int index = Items.IndexOf(currentNode); if (searchForward) { index++; if (index >= Items.Count) index = -1; } else index--; if (index < 0) return null; return (CustomTreeNode)Items[index]; } /// <summary> /// Finds next/previous enabled node in Items collection. /// </summary> /// <param name="currentNode">Node where the search for next/previous enabled node will start.</param> /// <param name="searchForward">Determines direction of search (search for next or previous node).</param> /// <returns></returns> protected CustomTreeNode GetNextEnabledNode(CustomTreeNode currentNode, bool searchForward) { if (currentNode == null) return null; CustomTreeNode nextNode = GetNextNode(currentNode, searchForward); if (nextNode == null) return null; if (nextNode.Enabled) return nextNode; return GetNextEnabledNode(nextNode, searchForward); } protected override void OnMouseUp(MouseEventArgs e) { bool anythingChanged = false; bool orderChanged = false; Point loc = this.PointToClient(MousePosition); int index = this.IndexFromPoint(loc); if (index < 0 || index > Items.Count) return; CustomTreeNode node = this.Items[index] as CustomTreeNode; if (node == null) return; int indent = node.Level * NodeIndent + (ShowRootLines ? NodeIndent : 2); if (node.ChildNodes.Count > 0 && loc.X < indent - (ItemHeight - 9) && loc.X > indent - ItemHeight && (ShowRootLines || node.Level > 0)) { node.Expanded = !node.Expanded; node.PreferredExpanded = node.Expanded; anythingChanged = true; orderChanged = true; } else if (ShowCheckboxes && !node.HideCheckbox && node.Enabled && loc.X > indent && loc.X < indent + ItemHeight) { if (node.State == CheckState.Unchecked || node.State == CheckState.Indeterminate) node.State = CheckState.Checked; else node.State = CheckState.Unchecked; anythingChanged = true; } if (orderChanged) Resort(); if (anythingChanged) { if(ItemCheckChanged != null) ItemCheckChanged(node, new EventArgs()); Refresh(); } base.OnMouseUp(e); } public event EventHandler<EventArgs> ItemCheckChanged; public event EventHandler DoubleClickOnRow; protected override void OnMouseDoubleClick(MouseEventArgs e) { base.OnMouseDoubleClick(e); bool anythingChanged = false; Point loc = this.PointToClient(MousePosition); int index = this.IndexFromPoint(loc); if (index < 0 || index > Items.Count) return; CustomTreeNode node = this.Items[index] as CustomTreeNode; if (node == null) return; int indent = node.Level * NodeIndent + (ShowRootLines ? NodeIndent : 2); if (node.ChildNodes.Count > 0 && loc.X < indent - (ItemHeight - 9) && loc.X > indent - ItemHeight && (ShowRootLines || node.Level > 0)) { return; } else if (ShowCheckboxes && !node.HideCheckbox && loc.X > indent && loc.X < indent + ItemHeight) { return; } else if (node.ChildNodes.Count > 0 && (node.Level > 0 || !_rootAlwaysExpanded)) { node.Expanded = !node.Expanded; node.PreferredExpanded = node.Expanded; anythingChanged = true; } if (anythingChanged) { Resort(); Refresh(); } if (DoubleClickOnRow != null) DoubleClickOnRow(this, e); } protected override void OnKeyUp(KeyEventArgs e) { var node = SelectedItem as CustomTreeNode; switch (e.KeyCode) { case Keys.Space: { if (!ShowCheckboxes) break; if (node == null || node.HideCheckbox || !node.Enabled) break; //checked => uncheck it; unchecked or indeterminate => check it node.State = node.State == CheckState.Checked ? CheckState.Unchecked : CheckState.Checked; Refresh(); if (ItemCheckChanged != null) ItemCheckChanged(node, new EventArgs()); break; } } base.OnKeyUp(e); } protected override void OnKeyDown(KeyEventArgs e) { var node = SelectedItem as CustomTreeNode; switch (e.KeyCode) { case Keys.Right: { if (node != null && node.ChildNodes.Count > 0 && (node.Level > 0 || !_rootAlwaysExpanded) && !node.Expanded) { node.Expanded = true; Resort(); Refresh(); e.Handled = true; } break; } case Keys.Left: { if (node != null && node.ChildNodes.Count > 0 && (node.Level > 0 || !_rootAlwaysExpanded) && node.Expanded) { node.Expanded = false; Resort(); Refresh(); e.Handled = true; } break; } } base.OnKeyDown(e); } } }
37.570952
167
0.510909
[ "BSD-2-Clause" ]
CraigOrendi/xenadmin
XenAdmin/Controls/CustomTreeView.cs
22,507
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace DotNetCoreApplication.Entities { public class Employee { [Key] public int EmployeeId { get; set; } public string EmployeeName { get; set; } public string EmployeeCode { get; set; } public string ContactNo { get; set; } public string CompanyName { get; set; } public DateTime CreatedOn { get; set; } } }
21.24
48
0.659134
[ "MIT" ]
vijaykumarvicky/DotNetCoreApplication
DotNetCoreApplication/DotNetCoreApplication/Entities/Employee.cs
533
C#
// Copyright (c) 2021 .NET Foundation and Contributors. All rights reserved. // 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 full license information. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; #if NETFX_CORE using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; #else using System.Windows.Controls; #endif namespace ReactiveUI.Tests.Xaml { public class PropertyBindView : Control, IViewFor<PropertyBindViewModel> { public static readonly DependencyProperty ViewModelProperty = DependencyProperty.Register("ViewModel", typeof(PropertyBindViewModel), typeof(PropertyBindView), new PropertyMetadata(null)); public PropertyBindView() { SomeTextBox = new TextBox(); Property2 = new TextBox(); FakeControl = new PropertyBindFakeControl(); FakeItemsControl = new ListBox(); } public TextBox SomeTextBox { get; set; } public TextBox Property2 { get; set; } public PropertyBindFakeControl FakeControl { get; set; } public ListBox FakeItemsControl { get; set; } public PropertyBindViewModel? ViewModel { get => (PropertyBindViewModel)GetValue(ViewModelProperty); set => SetValue(ViewModelProperty, value); } object? IViewFor.ViewModel { get => ViewModel; set => ViewModel = (PropertyBindViewModel?)value; } } }
29.964286
138
0.675805
[ "MIT" ]
benchabot2/ReactiveUI
src/ReactiveUI.Tests/Platforms/windows-xaml/Mocks/PropertyBindView.cs
1,680
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.Collections.Generic; using System.Text; using System.Xml; using System.Xml.Linq; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.DocumentationComments { internal abstract class AbstractDocumentationCommentFormattingService : IDocumentationCommentFormattingService { private enum DocumentationCommentListType { None, Bullet, Number, Table, } private class FormatterState { private bool _anyNonWhitespaceSinceLastPara; private bool _pendingParagraphBreak; private bool _pendingLineBreak; private bool _pendingSingleSpace; private static readonly TaggedText s_spacePart = new TaggedText(TextTags.Space, " "); private static readonly TaggedText s_newlinePart = new TaggedText(TextTags.LineBreak, "\r\n"); internal readonly List<TaggedText> Builder = new List<TaggedText>(); /// <summary> /// Defines the containing lists for the current formatting state. The last item in the list is the /// innermost list. /// /// <list type="bullet"> /// <item> /// <term><c>type</c></term> /// <description>The type of list.</description> /// </item> /// <item> /// <term><c>index</c></term> /// <description>The index of the current item in the list.</description> /// </item> /// <item> /// <term><c>renderedItem</c></term> /// <description><see langword="true"/> if the label (a bullet or number) for the current list item has already been rendered; otherwise <see langword="false"/>.</description> /// </item> /// </list> /// </summary> private readonly List<(DocumentationCommentListType type, int index, bool renderedItem)> _listStack = new List<(DocumentationCommentListType type, int index, bool renderedItem)>(); /// <summary> /// The top item of the stack indicates the hyperlink to apply to text rendered at the current location. It /// consists of a navigation <c>target</c> (the destination to navigate to when clicked) and a <c>hint</c> /// (typically shown as a tooltip for the link). This stack is never empty; when no hyperlink applies to the /// current scope, the top item of the stack will be a default tuple instance. /// </summary> private readonly Stack<(string target, string hint)> _navigationTargetStack = new Stack<(string target, string hint)>(); /// <summary> /// Tracks the style for text. The top item of the stack is the current style to apply (the merged result of /// all containing styles). This stack is never empty; when no style applies to the current scope, the top /// item of the stack will be <see cref="TaggedTextStyle.None"/>. /// </summary> private readonly Stack<TaggedTextStyle> _styleStack = new Stack<TaggedTextStyle>(); public FormatterState() { _navigationTargetStack.Push(default); _styleStack.Push(TaggedTextStyle.None); } internal SemanticModel SemanticModel { get; set; } internal int Position { get; set; } public bool AtBeginning { get { return Builder.Count == 0; } } public SymbolDisplayFormat Format { get; internal set; } internal (string target, string hint) NavigationTarget => _navigationTargetStack.Peek(); internal TaggedTextStyle Style => _styleStack.Peek(); public void AppendSingleSpace() => _pendingSingleSpace = true; public void AppendString(string s) { EmitPendingChars(); Builder.Add(new TaggedText(TextTags.Text, s, Style, NavigationTarget.target, NavigationTarget.hint)); _anyNonWhitespaceSinceLastPara = true; } public void AppendParts(IEnumerable<TaggedText> parts) { EmitPendingChars(); Builder.AddRange(parts); _anyNonWhitespaceSinceLastPara = true; } public void PushList(DocumentationCommentListType listType) { _listStack.Add((listType, index: 0, renderedItem: false)); MarkBeginOrEndPara(); } /// <summary> /// Marks the start of an item in a list; called before each item. /// </summary> public void NextListItem() { if (_listStack.Count == 0) { return; } var (type, index, renderedItem) = _listStack[_listStack.Count - 1]; if (renderedItem) { // Mark the end of the previous list item Builder.Add(new TaggedText(TextTags.ContainerEnd, string.Empty)); } // The next list item has an incremented index, and has not yet been rendered to Builder. _listStack[_listStack.Count - 1] = (type, index + 1, renderedItem: false); MarkLineBreak(); } public void PopList() { if (_listStack.Count == 0) { return; } if (_listStack[_listStack.Count - 1].renderedItem) { Builder.Add(new TaggedText(TextTags.ContainerEnd, string.Empty)); } _listStack.RemoveAt(_listStack.Count - 1); MarkBeginOrEndPara(); } public void PushNavigationTarget(string target, string hint) => _navigationTargetStack.Push((target, hint)); public void PopNavigationTarget() => _navigationTargetStack.Pop(); public void PushStyle(TaggedTextStyle style) => _styleStack.Push(_styleStack.Peek() | style); public void PopStyle() => _styleStack.Pop(); public void MarkBeginOrEndPara() { // If this is a <para> with nothing before it, then skip it. if (_anyNonWhitespaceSinceLastPara == false) { return; } _pendingParagraphBreak = true; // Reset flag. _anyNonWhitespaceSinceLastPara = false; } public void MarkLineBreak() { // If this is a <br> with nothing before it, then skip it. if (_anyNonWhitespaceSinceLastPara == false && !_pendingLineBreak) { return; } if (_pendingLineBreak || _pendingParagraphBreak) { // Multiple line breaks in sequence become a single paragraph break. _pendingParagraphBreak = true; _pendingLineBreak = false; } else { _pendingLineBreak = true; } // Reset flag. _anyNonWhitespaceSinceLastPara = false; } public string GetText() => Builder.GetFullText(); private void EmitPendingChars() { if (_pendingParagraphBreak) { Builder.Add(s_newlinePart); Builder.Add(s_newlinePart); } else if (_pendingLineBreak) { Builder.Add(s_newlinePart); } else if (_pendingSingleSpace) { Builder.Add(s_spacePart); } _pendingParagraphBreak = false; _pendingLineBreak = false; _pendingSingleSpace = false; for (var i = 0; i < _listStack.Count; i++) { if (_listStack[i].renderedItem) { continue; } switch (_listStack[i].type) { case DocumentationCommentListType.Bullet: Builder.Add(new TaggedText(TextTags.ContainerStart, "• ")); break; case DocumentationCommentListType.Number: Builder.Add(new TaggedText(TextTags.ContainerStart, $"{_listStack[i].index}. ")); break; case DocumentationCommentListType.Table: case DocumentationCommentListType.None: default: Builder.Add(new TaggedText(TextTags.ContainerStart, string.Empty)); break; } _listStack[i] = (_listStack[i].type, _listStack[i].index, renderedItem: true); } } } public string Format(string rawXmlText, Compilation compilation = null) { if (rawXmlText == null) { return null; } var state = new FormatterState(); // In case the XML is a fragment (that is, a series of elements without a parent) // wrap it up in a single tag. This makes parsing it much, much easier. var inputString = "<tag>" + rawXmlText + "</tag>"; var summaryElement = XElement.Parse(inputString, LoadOptions.PreserveWhitespace); AppendTextFromNode(state, summaryElement, compilation); return state.GetText(); } public IEnumerable<TaggedText> Format(string rawXmlText, SemanticModel semanticModel, int position, SymbolDisplayFormat format = null) { if (rawXmlText == null) { return null; } var state = new FormatterState() { SemanticModel = semanticModel, Position = position, Format = format }; // In case the XML is a fragment (that is, a series of elements without a parent) // wrap it up in a single tag. This makes parsing it much, much easier. var inputString = "<tag>" + rawXmlText + "</tag>"; var summaryElement = XElement.Parse(inputString, LoadOptions.PreserveWhitespace); AppendTextFromNode(state, summaryElement, state.SemanticModel.Compilation); return state.Builder; } private static void AppendTextFromNode(FormatterState state, XNode node, Compilation compilation) { if (node.NodeType == XmlNodeType.Text) { AppendTextFromTextNode(state, (XText)node); } if (node.NodeType != XmlNodeType.Element) { return; } var element = (XElement)node; var name = element.Name.LocalName; var needPopStyle = false; (string target, string hint)? navigationTarget = null; if (name == DocumentationCommentXmlNames.SeeElementName || name == DocumentationCommentXmlNames.SeeAlsoElementName || name == "a") { if (element.IsEmpty || element.FirstNode == null) { foreach (var attribute in element.Attributes()) { AppendTextFromAttribute(state, element, attribute, attributeNameToParse: DocumentationCommentXmlNames.CrefAttributeName, SymbolDisplayPartKind.Text); } return; } else { navigationTarget = GetNavigationTarget(element, state.SemanticModel, state.Position, state.Format); if (navigationTarget is object) { state.PushNavigationTarget(navigationTarget.Value.target, navigationTarget.Value.hint); } } } else if (name == DocumentationCommentXmlNames.ParameterReferenceElementName || name == DocumentationCommentXmlNames.TypeParameterReferenceElementName) { var kind = name == DocumentationCommentXmlNames.ParameterReferenceElementName ? SymbolDisplayPartKind.ParameterName : SymbolDisplayPartKind.TypeParameterName; foreach (var attribute in element.Attributes()) { AppendTextFromAttribute(state, element, attribute, attributeNameToParse: DocumentationCommentXmlNames.NameAttributeName, kind); } return; } else if (name == DocumentationCommentXmlNames.CElementName || name == DocumentationCommentXmlNames.CodeElementName || name == "tt") { needPopStyle = true; state.PushStyle(TaggedTextStyle.Code); } else if (name == "em" || name == "i") { needPopStyle = true; state.PushStyle(TaggedTextStyle.Emphasis); } else if (name == "strong" || name == "b" || name == DocumentationCommentXmlNames.TermElementName) { needPopStyle = true; state.PushStyle(TaggedTextStyle.Strong); } else if (name == "u") { needPopStyle = true; state.PushStyle(TaggedTextStyle.Underline); } if (name == DocumentationCommentXmlNames.ListElementName) { var rawListType = element.Attribute(DocumentationCommentXmlNames.TypeAttributeName)?.Value; var listType = rawListType switch { "table" => DocumentationCommentListType.Table, "number" => DocumentationCommentListType.Number, "bullet" => DocumentationCommentListType.Bullet, _ => DocumentationCommentListType.None, }; state.PushList(listType); } else if (name == DocumentationCommentXmlNames.ItemElementName) { state.NextListItem(); } if (name == DocumentationCommentXmlNames.ParaElementName || name == DocumentationCommentXmlNames.CodeElementName) { state.MarkBeginOrEndPara(); } else if (name == "br") { state.MarkLineBreak(); } foreach (var childNode in element.Nodes()) { AppendTextFromNode(state, childNode, compilation); } if (name == DocumentationCommentXmlNames.ParaElementName || name == DocumentationCommentXmlNames.CodeElementName) { state.MarkBeginOrEndPara(); } if (name == DocumentationCommentXmlNames.ListElementName) { state.PopList(); } if (needPopStyle) { state.PopStyle(); } if (navigationTarget is object) { state.PopNavigationTarget(); } if (name == DocumentationCommentXmlNames.TermElementName) { state.AppendSingleSpace(); state.AppendString("–"); } } private static (string target, string hint)? GetNavigationTarget(XElement element, SemanticModel semanticModel, int position, SymbolDisplayFormat format) { var crefAttribute = element.Attribute(DocumentationCommentXmlNames.CrefAttributeName); if (crefAttribute is object) { if (semanticModel is object) { var symbol = DocumentationCommentId.GetFirstSymbolForDeclarationId(crefAttribute.Value, semanticModel.Compilation); if (symbol is object) { return (target: SymbolKey.CreateString(symbol), hint: symbol.ToMinimalDisplayString(semanticModel, position, format ?? SymbolDisplayFormat.MinimallyQualifiedFormat)); } } } var hrefAttribute = element.Attribute(DocumentationCommentXmlNames.HrefAttributeName); if (hrefAttribute is object) { return (target: hrefAttribute.Value, hint: hrefAttribute.Value); } return null; } private static void AppendTextFromAttribute(FormatterState state, XElement element, XAttribute attribute, string attributeNameToParse, SymbolDisplayPartKind kind) { var attributeName = attribute.Name.LocalName; if (attributeNameToParse == attributeName) { state.AppendParts( CrefToSymbolDisplayParts(attribute.Value, state.Position, state.SemanticModel, state.Format, kind).ToTaggedText(state.Style)); } else { var displayKind = attributeName == DocumentationCommentXmlNames.LangwordAttributeName ? TextTags.Keyword : TextTags.Text; var text = attribute.Value; var style = state.Style; var navigationTarget = attributeName == DocumentationCommentXmlNames.HrefAttributeName ? attribute.Value : null; var navigationHint = navigationTarget; state.AppendParts(SpecializedCollections.SingletonEnumerable(new TaggedText(displayKind, text, style, navigationTarget, navigationHint))); } } internal static IEnumerable<SymbolDisplayPart> CrefToSymbolDisplayParts( string crefValue, int position, SemanticModel semanticModel, SymbolDisplayFormat format = null, SymbolDisplayPartKind kind = SymbolDisplayPartKind.Text) { // first try to parse the symbol if (semanticModel != null) { var symbol = DocumentationCommentId.GetFirstSymbolForDeclarationId(crefValue, semanticModel.Compilation); if (symbol != null) { format ??= SymbolDisplayFormat.MinimallyQualifiedFormat; if (symbol.IsConstructor()) { format = format.WithMemberOptions(SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeExplicitInterface); } return symbol.ToMinimalDisplayParts(semanticModel, position, format); } } // if any of that fails fall back to just displaying the raw text return SpecializedCollections.SingletonEnumerable( new SymbolDisplayPart(kind, symbol: null, text: TrimCrefPrefix(crefValue))); } private static string TrimCrefPrefix(string value) { if (value.Length >= 2 && value[1] == ':') { value = value.Substring(startIndex: 2); } return value; } private static void AppendTextFromTextNode(FormatterState state, XText element) { var rawText = element.Value; var builder = new StringBuilder(rawText.Length); // Normalize the whitespace. var pendingWhitespace = false; var hadAnyNonWhitespace = false; for (var i = 0; i < rawText.Length; i++) { if (char.IsWhiteSpace(rawText[i])) { // Whitespace. If it occurs at the beginning of the text we don't append it // at all; otherwise, we reduce it to a single space. if (!state.AtBeginning || hadAnyNonWhitespace) { pendingWhitespace = true; } } else { // Some other character... if (pendingWhitespace) { if (builder.Length == 0) { state.AppendSingleSpace(); } else { builder.Append(' '); } pendingWhitespace = false; } builder.Append(rawText[i]); hadAnyNonWhitespace = true; } } if (builder.Length > 0) { state.AppendString(builder.ToString()); } if (pendingWhitespace) { state.AppendSingleSpace(); } } } }
38.292254
192
0.528322
[ "MIT" ]
BertanAygun/roslyn
src/Features/Core/Portable/DocumentationComments/AbstractDocumentationCommentFormattingService.cs
21,756
C#
using Exadel.CrazyPrice.Common.Extentions; using Exadel.CrazyPrice.Common.Models.Promocode; using System; using System.Collections.Generic; using FluentAssertions; using Xunit; namespace Exadel.CrazyPrice.Tests.Common.Models.Promocode { public class UserPromocodesTests { [Fact] public void UserPromocodesTest() { var userPromocodes = new UserPromocodes() { UserId = Guid.Parse("675f0949-fd50-4738-92e2-9523ecc031d1"), Promocodes = new List<CrazyPrice.Common.Models.Promocode.Promocode>() { new() { Id = Guid.Parse("dc666524-36a3-43ef-998c-7f250793d9bc"), CreateDate = DateTime.UtcNow, EndDate = DateTime.UtcNow, Deleted = false, PromocodeValue = StringExtentions.NewPromocodeValue() } } }; userPromocodes.UserId.Should().NotBeEmpty(); userPromocodes.Promocodes.Should().NotBeNull(); } } }
32.666667
86
0.532313
[ "BSD-3-Clause" ]
ssivazhalezau/exadel_discounts_be
src/Exadel.CrazyPrice/Exadel.CrazyPrice.Tests/Common/Models/Promocode/UserPromocodesTests.cs
1,178
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 sagemaker-2017-07-24.normal.json service model. */ using System; using System.IO; using System.Text; using Microsoft.VisualStudio.TestTools.UnitTesting; using Amazon.SageMaker; using Amazon.SageMaker.Model; using Amazon.SageMaker.Model.Internal.MarshallTransformations; using Amazon.Runtime.Internal.Transform; using ServiceClientGenerator; using AWSSDK_DotNet35.UnitTests.TestTools; namespace AWSSDK_DotNet35.UnitTests.Marshalling { [TestClass] public class SageMakerMarshallingTests { static readonly ServiceModel service_model = Utils.LoadServiceModel("sagemaker"); [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("SageMaker")] public void AddTagsMarshallTest() { var request = InstantiateClassGenerator.Execute<AddTagsRequest>(); var marshaller = new AddTagsRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<AddTagsRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("AddTags").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = AddTagsResponseUnmarshaller.Instance.Unmarshall(context) as AddTagsResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("SageMaker")] public void CreateEndpointMarshallTest() { var request = InstantiateClassGenerator.Execute<CreateEndpointRequest>(); var marshaller = new CreateEndpointRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<CreateEndpointRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("CreateEndpoint").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = CreateEndpointResponseUnmarshaller.Instance.Unmarshall(context) as CreateEndpointResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("SageMaker")] public void CreateEndpointConfigMarshallTest() { var request = InstantiateClassGenerator.Execute<CreateEndpointConfigRequest>(); var marshaller = new CreateEndpointConfigRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<CreateEndpointConfigRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("CreateEndpointConfig").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = CreateEndpointConfigResponseUnmarshaller.Instance.Unmarshall(context) as CreateEndpointConfigResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("SageMaker")] public void CreateModelMarshallTest() { var request = InstantiateClassGenerator.Execute<CreateModelRequest>(); var marshaller = new CreateModelRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<CreateModelRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("CreateModel").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = CreateModelResponseUnmarshaller.Instance.Unmarshall(context) as CreateModelResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("SageMaker")] public void CreateNotebookInstanceMarshallTest() { var request = InstantiateClassGenerator.Execute<CreateNotebookInstanceRequest>(); var marshaller = new CreateNotebookInstanceRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<CreateNotebookInstanceRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("CreateNotebookInstance").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = CreateNotebookInstanceResponseUnmarshaller.Instance.Unmarshall(context) as CreateNotebookInstanceResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("SageMaker")] public void CreatePresignedNotebookInstanceUrlMarshallTest() { var request = InstantiateClassGenerator.Execute<CreatePresignedNotebookInstanceUrlRequest>(); var marshaller = new CreatePresignedNotebookInstanceUrlRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<CreatePresignedNotebookInstanceUrlRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("CreatePresignedNotebookInstanceUrl").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = CreatePresignedNotebookInstanceUrlResponseUnmarshaller.Instance.Unmarshall(context) as CreatePresignedNotebookInstanceUrlResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("SageMaker")] public void CreateTrainingJobMarshallTest() { var request = InstantiateClassGenerator.Execute<CreateTrainingJobRequest>(); var marshaller = new CreateTrainingJobRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<CreateTrainingJobRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("CreateTrainingJob").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = CreateTrainingJobResponseUnmarshaller.Instance.Unmarshall(context) as CreateTrainingJobResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("SageMaker")] public void DeleteEndpointMarshallTest() { var request = InstantiateClassGenerator.Execute<DeleteEndpointRequest>(); var marshaller = new DeleteEndpointRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<DeleteEndpointRequest>(request,jsonRequest); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("SageMaker")] public void DeleteEndpointConfigMarshallTest() { var request = InstantiateClassGenerator.Execute<DeleteEndpointConfigRequest>(); var marshaller = new DeleteEndpointConfigRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<DeleteEndpointConfigRequest>(request,jsonRequest); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("SageMaker")] public void DeleteModelMarshallTest() { var request = InstantiateClassGenerator.Execute<DeleteModelRequest>(); var marshaller = new DeleteModelRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<DeleteModelRequest>(request,jsonRequest); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("SageMaker")] public void DeleteNotebookInstanceMarshallTest() { var request = InstantiateClassGenerator.Execute<DeleteNotebookInstanceRequest>(); var marshaller = new DeleteNotebookInstanceRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<DeleteNotebookInstanceRequest>(request,jsonRequest); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("SageMaker")] public void DeleteTagsMarshallTest() { var request = InstantiateClassGenerator.Execute<DeleteTagsRequest>(); var marshaller = new DeleteTagsRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<DeleteTagsRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("DeleteTags").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = DeleteTagsResponseUnmarshaller.Instance.Unmarshall(context) as DeleteTagsResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("SageMaker")] public void DescribeEndpointMarshallTest() { var request = InstantiateClassGenerator.Execute<DescribeEndpointRequest>(); var marshaller = new DescribeEndpointRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<DescribeEndpointRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("DescribeEndpoint").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = DescribeEndpointResponseUnmarshaller.Instance.Unmarshall(context) as DescribeEndpointResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("SageMaker")] public void DescribeEndpointConfigMarshallTest() { var request = InstantiateClassGenerator.Execute<DescribeEndpointConfigRequest>(); var marshaller = new DescribeEndpointConfigRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<DescribeEndpointConfigRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("DescribeEndpointConfig").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = DescribeEndpointConfigResponseUnmarshaller.Instance.Unmarshall(context) as DescribeEndpointConfigResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("SageMaker")] public void DescribeModelMarshallTest() { var request = InstantiateClassGenerator.Execute<DescribeModelRequest>(); var marshaller = new DescribeModelRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<DescribeModelRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("DescribeModel").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = DescribeModelResponseUnmarshaller.Instance.Unmarshall(context) as DescribeModelResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("SageMaker")] public void DescribeNotebookInstanceMarshallTest() { var request = InstantiateClassGenerator.Execute<DescribeNotebookInstanceRequest>(); var marshaller = new DescribeNotebookInstanceRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<DescribeNotebookInstanceRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("DescribeNotebookInstance").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = DescribeNotebookInstanceResponseUnmarshaller.Instance.Unmarshall(context) as DescribeNotebookInstanceResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("SageMaker")] public void DescribeTrainingJobMarshallTest() { var request = InstantiateClassGenerator.Execute<DescribeTrainingJobRequest>(); var marshaller = new DescribeTrainingJobRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<DescribeTrainingJobRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("DescribeTrainingJob").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = DescribeTrainingJobResponseUnmarshaller.Instance.Unmarshall(context) as DescribeTrainingJobResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("SageMaker")] public void ListEndpointConfigsMarshallTest() { var request = InstantiateClassGenerator.Execute<ListEndpointConfigsRequest>(); var marshaller = new ListEndpointConfigsRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<ListEndpointConfigsRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("ListEndpointConfigs").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = ListEndpointConfigsResponseUnmarshaller.Instance.Unmarshall(context) as ListEndpointConfigsResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("SageMaker")] public void ListEndpointsMarshallTest() { var request = InstantiateClassGenerator.Execute<ListEndpointsRequest>(); var marshaller = new ListEndpointsRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<ListEndpointsRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("ListEndpoints").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = ListEndpointsResponseUnmarshaller.Instance.Unmarshall(context) as ListEndpointsResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("SageMaker")] public void ListModelsMarshallTest() { var request = InstantiateClassGenerator.Execute<ListModelsRequest>(); var marshaller = new ListModelsRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<ListModelsRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("ListModels").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = ListModelsResponseUnmarshaller.Instance.Unmarshall(context) as ListModelsResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("SageMaker")] public void ListNotebookInstancesMarshallTest() { var request = InstantiateClassGenerator.Execute<ListNotebookInstancesRequest>(); var marshaller = new ListNotebookInstancesRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<ListNotebookInstancesRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("ListNotebookInstances").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = ListNotebookInstancesResponseUnmarshaller.Instance.Unmarshall(context) as ListNotebookInstancesResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("SageMaker")] public void ListTagsMarshallTest() { var request = InstantiateClassGenerator.Execute<ListTagsRequest>(); var marshaller = new ListTagsRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<ListTagsRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("ListTags").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = ListTagsResponseUnmarshaller.Instance.Unmarshall(context) as ListTagsResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("SageMaker")] public void ListTrainingJobsMarshallTest() { var request = InstantiateClassGenerator.Execute<ListTrainingJobsRequest>(); var marshaller = new ListTrainingJobsRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<ListTrainingJobsRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("ListTrainingJobs").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = ListTrainingJobsResponseUnmarshaller.Instance.Unmarshall(context) as ListTrainingJobsResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("SageMaker")] public void StartNotebookInstanceMarshallTest() { var request = InstantiateClassGenerator.Execute<StartNotebookInstanceRequest>(); var marshaller = new StartNotebookInstanceRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<StartNotebookInstanceRequest>(request,jsonRequest); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("SageMaker")] public void StopNotebookInstanceMarshallTest() { var request = InstantiateClassGenerator.Execute<StopNotebookInstanceRequest>(); var marshaller = new StopNotebookInstanceRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<StopNotebookInstanceRequest>(request,jsonRequest); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("SageMaker")] public void StopTrainingJobMarshallTest() { var request = InstantiateClassGenerator.Execute<StopTrainingJobRequest>(); var marshaller = new StopTrainingJobRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<StopTrainingJobRequest>(request,jsonRequest); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("SageMaker")] public void UpdateEndpointMarshallTest() { var request = InstantiateClassGenerator.Execute<UpdateEndpointRequest>(); var marshaller = new UpdateEndpointRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<UpdateEndpointRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("UpdateEndpoint").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = UpdateEndpointResponseUnmarshaller.Instance.Unmarshall(context) as UpdateEndpointResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("SageMaker")] public void UpdateEndpointWeightsAndCapacitiesMarshallTest() { var request = InstantiateClassGenerator.Execute<UpdateEndpointWeightsAndCapacitiesRequest>(); var marshaller = new UpdateEndpointWeightsAndCapacitiesRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<UpdateEndpointWeightsAndCapacitiesRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("UpdateEndpointWeightsAndCapacities").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = UpdateEndpointWeightsAndCapacitiesResponseUnmarshaller.Instance.Unmarshall(context) as UpdateEndpointWeightsAndCapacitiesResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("SageMaker")] public void UpdateNotebookInstanceMarshallTest() { var request = InstantiateClassGenerator.Execute<UpdateNotebookInstanceRequest>(); var marshaller = new UpdateNotebookInstanceRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<UpdateNotebookInstanceRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("UpdateNotebookInstance").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = UpdateNotebookInstanceResponseUnmarshaller.Instance.Unmarshall(context) as UpdateNotebookInstanceResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } } }
48.438131
165
0.64385
[ "Apache-2.0" ]
Murcho/aws-sdk-net
sdk/test/UnitTests/Generated/Marshalling/SageMakerMarshallingTests.cs
38,363
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("BazaDateMarinari")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("BazaDateMarinari")] [assembly: AssemblyCopyright("Copyright © 2019")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("ce0c51cd-0a29-493b-9b8c-ff4b9988a954")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.837838
84
0.749286
[ "MIT" ]
adrianB3/mtp_lab
other_things/BazaDateMarinari/BazaDateMarinari/Properties/AssemblyInfo.cs
1,403
C#
using System; using System.Runtime.InteropServices; namespace com.openrest.v1_1 { [ComVisible(true)] [InterfaceType(ComInterfaceType.InterfaceIsDual)] public interface IVariations { int GetCount(); IVariation Get(int i); } }
19.714286
54
0.652174
[ "Apache-2.0" ]
wix-incubator/openrest4net
openrest4com/com/openrest/v1_1/IVariations.cs
278
C#
#region License /* * Copyright 2009- Marko Lahma * * 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 namespace Quartz.Impl.AdoJobStore { /// <summary> /// This is a driver delegate for the PostgreSQL ADO.NET driver. /// </summary> /// <author>Marko Lahma</author> public class PostgreSQLDelegate : StdAdoDelegate { /// <summary> /// Gets the select next trigger to acquire SQL clause. /// MySQL version with LIMIT support. /// </summary> /// <returns></returns> protected override string GetSelectNextTriggerToAcquireSql(int maxCount) { return SqlSelectNextTriggerToAcquire + " LIMIT " + maxCount; } protected override string GetSelectNextMisfiredTriggersInStateToAcquireSql(int count) { if (count != -1) { return SqlSelectHasMisfiredTriggersInState + " LIMIT " + count; } return base.GetSelectNextMisfiredTriggersInStateToAcquireSql(count); } } }
31.979592
93
0.658583
[ "Apache-2.0" ]
1508553303/quartznet
src/Quartz/Impl/AdoJobStore/PostgreSQLDelegate.cs
1,569
C#
using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using DgcReader.BlacklistProviders.Italy; namespace DgcReader.BlacklistProviders.Italy.Migrations { [DbContext(typeof(ItalianDrlBlacklistDbContext))] partial class ItalianDrlBlacklistDbContextModelSnapshot : ModelSnapshot { protected override void BuildModel(ModelBuilder modelBuilder) { modelBuilder .HasAnnotation("ProductVersion", "1.1.6"); modelBuilder.Entity("DgcReader.BlacklistProviders.Italy.Entities.BlacklistEntry", b => { b.Property<string>("HashedUCVI") .ValueGeneratedOnAdd() .HasMaxLength(44); b.HasKey("HashedUCVI"); b.ToTable("DgcReader_ItalianDrl_Blacklist"); }); modelBuilder.Entity("DgcReader.BlacklistProviders.Italy.Entities.SyncStatus", b => { b.Property<int>("Id"); b.Property<int>("CurrentVersion"); b.Property<string>("CurrentVersionId") .HasMaxLength(24); b.Property<DateTime>("LastCheck"); b.Property<int>("LastChunkSaved"); b.Property<int>("TargetChunkSize"); b.Property<int>("TargetChunksCount"); b.Property<int>("TargetTotalNumberUCVI"); b.Property<int>("TargetVersion"); b.Property<string>("TargetVersionId") .HasMaxLength(24); b.HasKey("Id"); b.ToTable("DgcReader_ItalianDrl_SyncStatus"); }); } } }
31.616667
98
0.562467
[ "Apache-2.0" ]
DevTrevi/DgcReader
BlacklistProviders/DgcReader.BlacklistProviders.Italy/Migrations/ItalianDrlBlacklistDbContextModelSnapshot.cs
1,899
C#
using Xunit; using System.Collections.Generic; using System; using Papabytes.Cronofy.NetCore; namespace Papabytes.Cronofy.NetCore.Test.CronofyAccountClientTests { public class GetFreeBusy : Base { const string BasicResponseBody = @"{ ""pages"": { ""current"": 1, ""total"": 1 }, ""free_busy"": [ { ""calendar_id"": ""cal_U9uuErStTG@EAAAB_IsAsykA2DBTWqQTf-f0kJw"", ""start"": ""2014-09-06"", ""end"": ""2014-09-08"", ""free_busy_status"": ""busy"" } ] }"; private static readonly List<FreeBusy> BasicResponseCollection = new List<FreeBusy> { new FreeBusy { CalendarId = "cal_U9uuErStTG@EAAAB_IsAsykA2DBTWqQTf-f0kJw", Start = new EventTime(new Date(2014, 9, 6), "Etc/UTC"), End = new EventTime(new Date(2014, 9, 8), "Etc/UTC"), FreeBusyStatus = FreeBusyStatus.Busy, } }; [Fact] public void CanGetFreeBusy() { Http.Stub( HttpGet .Url("https://api.cronofy.com/v1/free_busy?tzid=Etc%2FUTC&localized_times=true") .RequestHeader("Authorization", "Bearer " + AccessToken) .ResponseCode(200) .ResponseBody(BasicResponseBody) ); var events = Client.GetFreeBusy(); Assert.Equal(BasicResponseCollection, events); } [Fact] public void CanGetPagedFreeBusy() { Http.Stub( HttpGet .Url("https://api.cronofy.com/v1/free_busy?tzid=Etc%2FUTC&localized_times=true") .RequestHeader("Authorization", "Bearer " + AccessToken) .ResponseCode(200) .ResponseBody( @"{ ""pages"": { ""current"": 1, ""total"": 2, ""next_page"": ""https://api.cronofy.com/v1/free_busy/pages/08a07b034306679e"" }, ""free_busy"": [ { ""calendar_id"": ""cal_U9uuErStTG@EAAAB_IsAsykA2DBTWqQTf-f0kJw"", ""start"": ""2014-09-06"", ""end"": ""2014-09-08"", ""free_busy_status"": ""busy"" } ] }") ); Http.Stub( HttpGet .Url("https://api.cronofy.com/v1/free_busy/pages/08a07b034306679e") .RequestHeader("Authorization", "Bearer " + AccessToken) .ResponseCode(200) .ResponseBody( @"{ ""pages"": { ""current"": 2, ""total"": 2 }, ""free_busy"": [ { ""calendar_id"": ""cal_U9uuErStTG@EAAAB_IsAsykA2DBTWqQTf-f0kJw"", ""start"": ""2014-12-06"", ""end"": ""2014-12-08"", ""free_busy_status"": ""tentative"" } ] }") ); var events = Client.GetFreeBusy(); Assert.Equal( new List<FreeBusy> { new FreeBusy { CalendarId = "cal_U9uuErStTG@EAAAB_IsAsykA2DBTWqQTf-f0kJw", Start = new EventTime(new Date(2014, 9, 6), "Etc/UTC"), End = new EventTime(new Date(2014, 9, 8), "Etc/UTC"), FreeBusyStatus = FreeBusyStatus.Busy, }, new FreeBusy { CalendarId = "cal_U9uuErStTG@EAAAB_IsAsykA2DBTWqQTf-f0kJw", Start = new EventTime(new Date(2014, 12, 6), "Etc/UTC"), End = new EventTime(new Date(2014, 12, 8), "Etc/UTC"), FreeBusyStatus = FreeBusyStatus.Tentative, }, }, events); } [Fact] public void CanGetFreeBusyWithinDates() { AssertParameter( "from=2015-10-20&to=2015-10-30", b => b.From(2015, 10, 20).To(2015, 10, 30)); } [Fact] public void CanGetFreeBusyIncludingManagedEvents() { AssertParameter("include_managed=true", b => b.IncludeManaged(true)); } [Fact] public void CanGetFreeBusyWithinMultipleCalendars() { var calendarIds = new List<string> { "cal_U9uuErStTG@EAAAB_IsAsykA2DBTWqQTf-f0kJw", "cal_U@y23bStTFV7AAAB_iWTeH8WOCDOIW@us5gRzww", }; var expectedKeyValue = Encode("calendar_ids[]", calendarIds[0]) + "&" + Encode("calendar_ids[]", calendarIds[1]); AssertParameter( expectedKeyValue, b => b.CalendarIds(calendarIds)); AssertParameter( expectedKeyValue, b => b.CalendarIds(calendarIds.ToArray())); } private void AssertParameter(string keyValue, Action<GetFreeBusyRequestBuilder> builderAction) { Http.Stub( HttpGet .Url("https://api.cronofy.com/v1/free_busy?tzid=Etc%2FUTC&localized_times=true&" + keyValue) .RequestHeader("Authorization", "Bearer " + AccessToken) .ResponseCode(200) .ResponseBody(BasicResponseBody) ); var builder = new GetFreeBusyRequestBuilder(); builderAction.Invoke(builder); var events = Client.GetFreeBusy(builder); Assert.Equal(BasicResponseCollection, events); } private static string Encode(string value) { return UrlBuilder.EncodeParameter(value); } private static string Encode(string key, string value) { return Encode(key) + "=" + Encode(value); } } }
31.01087
108
0.513845
[ "MIT" ]
Toky0/cronofy-csharp
test/Papabytes.Cronofy.NetCore.Test/CronofyAccountClientTests/GetFreeBusy.cs
5,706
C#
using Igtampe.BasicRender; using System; namespace Igtampe.BasicWindows { /// <summary>Creates a window that can "Tick". A tick subroutine is called every 250 ms.</summary> public class TickableWindow:Window { /// <summary>Creates an Animated, Shadowed, and centered tickable window with a centered header with the default colors (Gray Main BG, dark blue header, White Header Text)</summary> /// <param name="Title"></param> /// <param name="Length"></param> /// <param name="Height"></param> public TickableWindow(String Title,int Length,int Height) : base(true,true,ConsoleColor.Gray,ConsoleColor.DarkBlue,ConsoleColor.White,HeaderPosition.CENTER,Title,Length,Height,-1,-1) { } /// <summary>Creates an Animated, Shadowed, and Centered tickable window with a centered header with the specified colors.</summary> /// <param name="MainBG"></param> /// <param name="HeaderBG"></param> /// <param name="HeaderFG"></param> /// <param name="Title"></param> /// <param name="Length"></param> /// <param name="Height"></param> public TickableWindow(ConsoleColor MainBG,ConsoleColor HeaderBG,ConsoleColor HeaderFG,String Title,int Length,int Height) : base(true,true,MainBG,HeaderBG,HeaderFG,HeaderPosition.CENTER,Title,Length,Height,-1,-1) { } /// <summary>Creates a centered tickable window with a centered header with the default colors (Gray Main BG, dark blue header, White Header Text)</summary> /// <param name="Animated"></param> /// <param name="Shadowed"></param> /// <param name="Title"></param> /// <param name="Length"></param> /// <param name="Height"></param> public TickableWindow(Boolean Animated,Boolean Shadowed,String Title,int Length,int Height) : base(Animated,Shadowed,ConsoleColor.Gray,ConsoleColor.DarkBlue,ConsoleColor.White,HeaderPosition.CENTER,Title,Length,Height,-1,-1) { } /// <summary>Creates a centered tickable window with a centered header</summary> /// <param name="Animated"></param> /// <param name="Shadowed"></param> /// <param name="MainBG"></param> /// <param name="HeaderBG"></param> /// <param name="HeaderFG"></param> /// <param name="Title"></param> /// <param name="Length"></param> /// <param name="Height"></param> public TickableWindow(Boolean Animated,Boolean Shadowed,ConsoleColor MainBG,ConsoleColor HeaderBG,ConsoleColor HeaderFG,String Title,int Length,int Height) : base(Animated,Shadowed,MainBG,HeaderBG,HeaderFG,HeaderPosition.CENTER,Title,Length,Height,-1,-1) { } /// <summary>Creates a Tickable Window centered on the screen</summary> /// <param name="Animated"></param> /// <param name="Shadowed"></param> /// <param name="MainBG"></param> /// <param name="HeaderBG"></param> /// <param name="HeaderFG"></param> /// <param name="HeadPos"></param> /// <param name="Title"></param> /// <param name="Length"></param> /// <param name="Height"></param> public TickableWindow(Boolean Animated,Boolean Shadowed,ConsoleColor MainBG,ConsoleColor HeaderBG,ConsoleColor HeaderFG,HeaderPosition HeadPos,String Title,int Length,int Height) : base(Animated,Shadowed,MainBG,HeaderBG,HeaderFG,HeadPos,Title,Length,Height,-1,-1) { } /// <summary> /// Creates a Tickable Window. You get basically full control of everything with base constructor. /// </summary> /// <param name="Animated"></param> /// <param name="Shadowed"></param> /// <param name="MainBG"></param> /// <param name="HeaderBG"></param> /// <param name="HeaderFG"></param> /// <param name="HeadPos"></param> /// <param name="Title"></param> /// <param name="Length"></param> /// <param name="Height"></param> /// <param name="LeftPos"></param> /// <param name="TopPos"></param> public TickableWindow(Boolean Animated,Boolean Shadowed,ConsoleColor MainBG,ConsoleColor HeaderBG,ConsoleColor HeaderFG,HeaderPosition HeadPos,String Title,int Length,int Height,int LeftPos,int TopPos):base(Animated,Shadowed,MainBG,HeaderBG,HeaderFG,HeadPos,Title,Length,Height,LeftPos,TopPos) {} /// <summary>Executes this tickable window</summary> public override void Execute() { DrawWindow(Animated); //OnKeyPress returns true if we should continue execution. while(true) { //If there's a key to read, read it, otherwise, do not. if (Console.KeyAvailable && !OnKeyPress(Console.ReadKey(true))) { Close(); return; } if (!Tick()) { Close(); return; } RenderUtils.Sleep(250); } } /// <summary> /// Subroutine that runs every 250ms while the window is waiting for user input. /// At Base, it ticks every tickable element. /// </summary> /// <returns>True if execution should continue</returns> protected virtual bool Tick() { //tick each element. foreach(WindowElement element in AllElements) { //Look at us making some nice code and using the question mark cosa TickableWindowElement TickableElement = element as TickableWindowElement; bool? cont = TickableElement?.Tick(); if(cont ==false) { return false; } } return true; } } }
50.628319
304
0.615627
[ "CC0-1.0" ]
igtampe/BasicRender
Igtampe.BasicWindows/TickableWindow.cs
5,723
C#
/* Copyright (c) Citrix Systems, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, * with or without modification, are permitted provided * that the following conditions are met: * * * Redistributions of source code must retain the above * copyright notice, this list of conditions and the * following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the * following disclaimer in the documentation and/or other * materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ using System.Collections.Generic; using System.Linq; using XenAdmin.Core; using XenAdmin.Dialogs; using XenAPI; namespace XenAdmin.Commands { class MigrateVirtualDiskCommand : Command { /// <summary> /// Initializes a new instance of this Command. The parameter-less constructor is required in the derived /// class if it is to be attached to a ToolStrip menu item or button. It should not be used in any other scenario. /// </summary> public MigrateVirtualDiskCommand() { } public MigrateVirtualDiskCommand(IMainWindow mainWindow, IEnumerable<SelectedItem> selection) : base(mainWindow, selection) { } public override string ContextMenuText { get { return GetSelection().Count > 1 ? Messages.MAINWINDOW_MOVE_OBJECTS : Messages.MOVE_VDI_CONTEXT_MENU; } } protected override void RunCore(SelectedItemCollection selection) { List<VDI> vdis = selection.AsXenObjects<VDI>(); bool featureForbidden = vdis.TrueForAll(vdi => Helpers.FeatureForbidden(vdi.Connection, Host.RestrictCrossPoolMigrate)); if (featureForbidden) { UpsellDialog.ShowUpsellDialog(Messages.UPSELL_BLURB_MIGRATE_VDI, Parent); } else { new MigrateVirtualDiskDialog(selection.FirstAsXenObject.Connection, vdis).Show(Program.MainWindow); } } protected override bool CanRunCore(SelectedItemCollection selection) { return selection.Count > 0 && selection.All(v => CanBeMigrated(v.XenObject as VDI)); } private bool CanBeMigrated(VDI vdi) { if (vdi == null || vdi.is_a_snapshot || vdi.Locked || vdi.IsHaType() || vdi.cbt_enabled) return false; if(vdi.Connection.ResolveAll(vdi.VBDs).Count == 0) return false; if (vdi.GetVMs().Any(vm => !vm.IsRunning()) && !Helpers.DundeeOrGreater(vdi.Connection)) return false; SR sr = vdi.Connection.Resolve(vdi.SR); if (sr == null || sr.HBALunPerVDI()) return false; if (!sr.SupportsStorageMigration()) return false; return true; } protected override string GetCantRunReasonCore(IXenObject item) { VDI vdi = item as VDI; if (vdi == null) return base.GetCantRunReasonCore(item); if (vdi.is_a_snapshot) return Messages.CANNOT_MOVE_VDI_IS_SNAPSHOT; if (vdi.Locked) return Messages.CANNOT_MOVE_VDI_IN_USE; if (vdi.IsHaType()) return Messages.CANNOT_MOVE_HA_VD; if (vdi.cbt_enabled) return Messages.CANNOT_MOVE_CBT_ENABLED_VDI; if (vdi.IsMetadataForDR()) return Messages.CANNOT_MOVE_DR_VD; if (vdi.GetVMs().Any(vm => !vm.IsRunning()) && !Helpers.DundeeOrGreater(vdi.Connection)) return Messages.CANNOT_MIGRATE_VDI_NON_RUNNING_VM; SR sr = vdi.Connection.Resolve(vdi.SR); if (sr == null) return base.GetCantRunReasonCore(item); if (sr.HBALunPerVDI()) return Messages.UNSUPPORTED_SR_TYPE; if (!sr.SupportsStorageMigration()) return Messages.UNSUPPORTED_SR_TYPE; return base.GetCantRunReasonCore(item); } } }
39.423077
133
0.619707
[ "BSD-2-Clause" ]
CitrixChris/xenadmin
XenAdmin/Commands/MigrateVirtualDiskCommand.cs
5,127
C#
using System; using System.Net; using System.Collections.Generic; using BackpackTfApi.UserToken.Classifieds.Users.Models; namespace BackpackTfApi.UserToken.Classifieds.Utilities { public static class UsersDataHandler { /// <summary> /// Downloads the users' data JSON and converts it to a .NET type. /// </summary> /// <param name="uri"></param> /// <returns></returns> /// <exception cref="ArgumentNullException"></exception> /// <exception cref="WebException"></exception> /// <exception cref="NotSupportedException"></exception> public static UsersData FetchUserData(string uri) { using (var client = new WebClient()) return UsersData.FromJson(client.DownloadString(uri)); } /// <summary> /// Searches the users data and returns a user's inventory for a specified AppId. /// </summary> /// <param name="users"></param> /// <param name="userId"></param> /// <param name="appid"></param> /// <returns></returns> /// <exception cref="KeyNotFoundException"></exception> public static Inventory GetUserInventoryForApp(UsersData users, string userId, string appid) { if (!users.Users.ContainsKey(userId)) throw new KeyNotFoundException("Cannot find user with the specified SteamId64."); if (!users.Users[userId].Inventory.ContainsKey(appid)) throw new KeyNotFoundException("Cannot find an inventory for the specified AppId"); return users.Users[userId].Inventory[appid]; } } }
36.977778
100
0.61899
[ "MIT" ]
jackofdiamond5/BackpackTfApi
src/BackpackTfApi/UserToken/Classifieds/Utilities/UsersDataHandler.cs
1,666
C#
using ElmSharp; using Tizen.UIExtensions.ElmSharp; namespace Microsoft.Maui { public static class SwitchExtensions { public static void UpdateIsOn(this Check nativeCheck, ISwitch view) { nativeCheck.IsChecked = view.IsOn; } public static void UpdateTrackColor(this Check nativeCheck, ISwitch view) { if (view.ThumbColor != null) { nativeCheck.Color = view.TrackColor.ToNativeEFL(); } } public static void UpdateThumbColor(this Check nativeCheck, ISwitch view) { if (view.ThumbColor == null) { nativeCheck.DeleteOnColors(); } else { nativeCheck.SetOnColors(view.ThumbColor.ToNativeEFL()); } } } }
20.060606
75
0.703927
[ "MIT" ]
JoonghyunCho/TestBed
src/Core/src/Platform/Tizen/SwitchExtensions.cs
664
C#
using System; using System.Diagnostics; #if WINDOWS_UWP using Windows.ApplicationModel; #endif using Xamarin.Forms; using Xamarin.Forms.Xaml; [assembly: XamlCompilation(XamlCompilationOptions.Compile)] namespace ConferenceKiosk { public partial class App : Application { public App() { InitializeComponent(); MainPage = new NavigationPage(new MainPage()); } protected override async void OnStart() { #if WINDOWS_UWP await FullTrustProcessLauncher.LaunchFullTrustProcessForCurrentAppAsync("Setup"); #elif __MACOS__ var process = new ProcessStartInfo("scripts/setup.sh"); Process.Start(process); #endif Markdown.Init(); } protected override void OnSleep() { // Handle when your app sleeps } protected override void OnResume() { // Handle when your app resumes } } }
22.232558
93
0.632845
[ "MIT" ]
Bhaskers-Blu-Org2/ConferenceKiosk
ConferenceKiosk/ConferenceKiosk/App.xaml.cs
958
C#
using System.Windows.Forms; namespace JWLibrary.Winform.DataViewControls { public class DataGridViewDobleLineColumn : DataGridViewColumn { public DataGridViewDobleLineColumn() { this.CellTemplate = new DataGridViewDobleLineCell(); this.ReadOnly = true; } } }
22.928571
65
0.663551
[ "Unlicense" ]
GuyFawkesFromKorea/JWLibrary
JWLibrary.Winform/DataViewControls/DataGridViewDobleLineColumn.cs
323
C#
// This file is used by Code Analysis to maintain SuppressMessage // attributes that are applied to this project. // Project-level suppressions either have no target or are given // a specific target and scoped to a namespace, type, member, etc. using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "Needed when executing steps.")] [assembly: SuppressMessage("Globalization", "CA1303:Do not pass literals as localized parameters", Justification = "Temporary till the framework is completed.")] [assembly: SuppressMessage("Major Code Smell", "S3264:Events should be invoked", Justification = "Event is being invoked through an extension method.")]
40.105263
75
0.755906
[ "Apache-2.0" ]
JeevanJames/JustCompose
src/Core/GlobalSuppressions.cs
764
C#
using System; using System.Threading; using EventStore.ClientAPI; using EventStore.ClientAPI.Exceptions; using EventStore.Core.Tests.Helpers; using NUnit.Framework; namespace EventStore.Core.Tests.ClientAPI { [TestFixture, Category("ClientAPI"), Category("LongRunning")] public class deleting_existing_persistent_subscription_group_with_permissions : SpecificationWithMiniNode { private readonly PersistentSubscriptionSettings _settings = PersistentSubscriptionSettings.Create() .DoNotResolveLinkTos() .StartFromCurrent(); private readonly string _stream = Guid.NewGuid().ToString(); protected override void When() { _conn.CreatePersistentSubscriptionAsync(_stream, "groupname123", _settings, DefaultData.AdminCredentials).Wait(); } [Test] public void the_delete_of_group_succeeds() { Assert.DoesNotThrow(() => _conn.DeletePersistentSubscriptionAsync(_stream, "groupname123", DefaultData.AdminCredentials).Wait()); } } [TestFixture, Category("LongRunning")] public class deleting_existing_persistent_subscription_with_subscriber : SpecificationWithMiniNode { private readonly PersistentSubscriptionSettings _settings = PersistentSubscriptionSettings.Create() .DoNotResolveLinkTos() .StartFromCurrent(); private readonly string _stream = Guid.NewGuid().ToString(); private readonly ManualResetEvent _called = new ManualResetEvent(false); protected override void Given() { base.Given(); _conn.CreatePersistentSubscriptionAsync(_stream, "groupname123", _settings, DefaultData.AdminCredentials).Wait(); _conn.ConnectToPersistentSubscription(_stream, "groupname123", (s, e) => { }, (s, r, e) => _called.Set()); } protected override void When() { _conn.DeletePersistentSubscriptionAsync(_stream, "groupname123", DefaultData.AdminCredentials).Wait(); } [Test] public void the_subscription_is_dropped() { Assert.IsTrue(_called.WaitOne(TimeSpan.FromSeconds(5))); } } [TestFixture, Category("LongRunning")] public class deleting_persistent_subscription_group_that_doesnt_exist : SpecificationWithMiniNode { private readonly string _stream = Guid.NewGuid().ToString(); protected override void When() { } [Test] public void the_delete_fails_with_argument_exception() { try { _conn.DeletePersistentSubscriptionAsync(_stream, Guid.NewGuid().ToString(), DefaultData.AdminCredentials).Wait(); throw new Exception("expected exception"); } catch (Exception ex) { Assert.IsInstanceOf(typeof(AggregateException), ex); var inner = ex.InnerException; Assert.IsInstanceOf(typeof(InvalidOperationException), inner); } } } [TestFixture, Category("LongRunning")] public class deleting_persistent_subscription_group_without_permissions : SpecificationWithMiniNode { private readonly string _stream = Guid.NewGuid().ToString(); protected override void When() { } [Test] public void the_delete_fails_with_access_denied() { try { _conn.DeletePersistentSubscriptionAsync(_stream, Guid.NewGuid().ToString()).Wait(); throw new Exception("expected exception"); } catch (Exception ex) { Assert.IsInstanceOf(typeof(AggregateException), ex); var inner = ex.InnerException; Assert.IsInstanceOf(typeof(AccessDeniedException), inner); } } } //ALL /* [TestFixture, Category("LongRunning")] public class deleting_existing_persistent_subscription_group_on_all_with_permissions : SpecificationWithMiniNode { private readonly PersistentSubscriptionSettings _settings = PersistentSubscriptionSettingsBuilder.Create() .DoNotResolveLinkTos() .StartFromCurrent(); protected override void When() { _conn.CreatePersistentSubscriptionForAllAsync("groupname123", _settings, DefaultData.AdminCredentials).Wait(); } [Test] public void the_delete_of_group_succeeds() { var result = _conn.DeletePersistentSubscriptionForAllAsync("groupname123", DefaultData.AdminCredentials).Result; Assert.AreEqual(PersistentSubscriptionDeleteStatus.Success, result.Status); } } [TestFixture, Category("LongRunning")] public class deleting_persistent_subscription_group_on_all_that_doesnt_exist : SpecificationWithMiniNode { protected override void When() { } [Test] public void the_delete_fails_with_argument_exception() { try { _conn.DeletePersistentSubscriptionForAllAsync(Guid.NewGuid().ToString(), DefaultData.AdminCredentials).Wait(); throw new Exception("expected exception"); } catch (Exception ex) { Assert.IsInstanceOf(typeof(AggregateException), ex); var inner = ex.InnerException; Assert.IsInstanceOf(typeof(InvalidOperationException), inner); } } } [TestFixture, Category("LongRunning")] public class deleting_persistent_subscription_group_on_all_without_permissions : SpecificationWithMiniNode { protected override void When() { } [Test] public void the_delete_fails_with_access_denied() { try { _conn.DeletePersistentSubscriptionForAllAsync(Guid.NewGuid().ToString()).Wait(); throw new Exception("expected exception"); } catch (Exception ex) { Assert.IsInstanceOf(typeof(AggregateException), ex); var inner = ex.InnerException; Assert.IsInstanceOf(typeof(AccessDeniedException), inner); } } } */ }
35.814815
142
0.597725
[ "Apache-2.0" ]
shaan1337/EventStore
src/EventStore.Core.Tests/ClientAPI/deleting_persistent_subscription.cs
6,771
C#
/* * LUSID API * * # Introduction This page documents the [LUSID APIs](https://www.lusid.com/api/swagger), which allows authorised clients to query and update their data within the LUSID platform. SDKs to interact with the LUSID APIs are available in the following languages : * [C#](https://github.com/finbourne/lusid-sdk-csharp) * [Java](https://github.com/finbourne/lusid-sdk-java) * [JavaScript](https://github.com/finbourne/lusid-sdk-js) * [Python](https://github.com/finbourne/lusid-sdk-python) # Data Model The LUSID API has a relatively lightweight but extremely powerful data model. One of the goals of LUSID was not to enforce on clients a single rigid data model but rather to provide a flexible foundation onto which clients can map their own data models. The core entities in LUSID provide a minimal structure and set of relationships, and the data model can be extended using Properties. The LUSID data model is exposed through the LUSID APIs. The APIs provide access to both business objects and the meta data used to configure the systems behaviours. The key business entities are: - * **Portfolios** A portfolio is a container for transactions and holdings (a **Transaction Portfolio**) or constituents (a **Reference Portfolio**). * **Derived Portfolios**. Derived Portfolios allow Portfolios to be created based on other Portfolios, by overriding or adding specific items. * **Holdings** A Holding is a quantity of an Instrument or a balance of cash within a Portfolio. Holdings can only be adjusted via Transactions. * **Transactions** A Transaction is an economic event that occurs in a Portfolio, causing its holdings to change. * **Corporate Actions** A corporate action is a market event which occurs to an Instrument and thus applies to all portfolios which holding the instrument. Examples are stock splits or mergers. * **Constituents** A constituent is a record in a Reference Portfolio containing an Instrument and an associated weight. * **Instruments** An instrument represents a currency, tradable instrument or OTC contract that is attached to a transaction and a holding. * **Properties** All major entities allow additional user defined properties to be associated with them. For example, a Portfolio manager may be associated with a portfolio. Meta data includes: - * **Transaction Types** Transactions are booked with a specific transaction type. The types are client defined and are used to map the Transaction to a series of movements which update the portfolio holdings. * **Properties Types** Types of user defined properties used within the system. ## Scope All data in LUSID is segregated at the client level. Entities in LUSID are identifiable by a unique code. Every entity lives within a logical data partition known as a Scope. Scope is an identity namespace allowing two entities with the same unique code to co-exist within individual address spaces. For example, prices for equities from different vendors may be uploaded into different scopes such as `client/vendor1` and `client/vendor2`. A portfolio may then be valued using either of the price sources by referencing the appropriate scope. LUSID Clients cannot access scopes of other clients. ## Instruments LUSID has its own built-in instrument master which you can use to master your own instrument universe. Every instrument must be created with one or more unique market identifiers, such as [FIGI](https://openfigi.com/). For any non-listed instruments (eg OTCs), you can upload an instrument against a custom ID of your choosing. In addition, LUSID will allocate each instrument a unique 'LUSID instrument identifier'. The LUSID instrument identifier is what is used when uploading transactions, holdings, prices, etc. The API exposes an `instrument/lookup` endpoint which can be used to lookup these LUSID identifiers using their market identifiers. Cash can be referenced using the ISO currency code prefixed with \"`CCY_`\" e.g. `CCY_GBP` ## Instrument Data Instrument data can be uploaded to the system using the [Instrument Properties](#tag/InstrumentProperties) endpoint. | Field|Type|Description | | - --|- --|- -- | | Key|propertykey|The key of the property. This takes the format {domain}/{scope}/{code} e.g. 'Instrument/system/Name' or 'Transaction/strategy/quantsignal'. | | Value|string|The value of the property. | | EffectiveFrom|datetimeoffset|The effective datetime from which the property is valid. | | EffectiveUntil|datetimeoffset|The effective datetime until which the property is valid. If not supplied this will be valid indefinitely, potentially overwriting values with EffectiveFrom's in the future. | ## Transaction Portfolios Portfolios are the top-level entity containers within LUSID, containing transactions, corporate actions and holdings. The transactions build up the portfolio holdings on which valuations, analytics profit & loss and risk can be calculated. Properties can be associated with Portfolios to add in additional data. Portfolio properties can be changed over time, for example to allow a Portfolio Manager to be linked with a Portfolio. Additionally, portfolios can be securitised and held by other portfolios, allowing LUSID to perform \"drill-through\" into underlying fund holdings ### Derived Portfolios LUSID also allows for a portfolio to be composed of another portfolio via derived portfolios. A derived portfolio can contain its own transactions and also inherits any transactions from its parent portfolio. Any changes made to the parent portfolio are automatically reflected in derived portfolio. Derived portfolios in conjunction with scopes are a powerful construct. For example, to do pre-trade what-if analysis, a derived portfolio could be created a new namespace linked to the underlying live (parent) portfolio. Analysis can then be undertaken on the derived portfolio without affecting the live portfolio. ### Transactions A transaction represents an economic activity against a Portfolio. Transactions are processed according to a configuration. This will tell the LUSID engine how to interpret the transaction and correctly update the holdings. LUSID comes with a set of transaction types you can use out of the box, or you can configure your own set(s) of transactions. For more details see the [LUSID Getting Started Guide for transaction configuration.](https://support.lusid.com/configuring-transaction-types) | Field|Type|Description | | - --|- --|- -- | | TransactionId|string|The unique identifier for the transaction. | | Type|string|The type of the transaction e.g. 'Buy', 'Sell'. The transaction type should have been pre-configured via the System Configuration API endpoint. If it hasn't been pre-configured the transaction will still be updated or inserted however you will be unable to generate the resultant holdings for the portfolio that contains this transaction as LUSID does not know how to process it. | | InstrumentIdentifiers|map|A set of instrument identifiers to use to resolve the transaction to a unique instrument. | | TransactionDate|dateorcutlabel|The date of the transaction. | | SettlementDate|dateorcutlabel|The settlement date of the transaction. | | Units|decimal|The number of units transacted in the associated instrument. | | TransactionPrice|transactionprice|The price for each unit of the transacted instrument in the transaction currency. | | TotalConsideration|currencyandamount|The total value of the transaction in the settlement currency. | | ExchangeRate|decimal|The exchange rate between the transaction and settlement currency. For example if the transaction currency is in USD and the settlement currency is in GBP this this the USD/GBP rate. | | TransactionCurrency|currency|The transaction currency. | | Properties|map|Set of unique transaction properties and associated values to store with the transaction. Each property must be from the 'Transaction' domain. | | CounterpartyId|string|The identifier for the counterparty of the transaction. | | Source|string|The source of the transaction. This is used to look up the appropriate transaction group set in the transaction type configuration. | From these fields, the following values can be calculated * **Transaction value in Transaction currency**: TotalConsideration / ExchangeRate * **Transaction value in Portfolio currency**: Transaction value in Transaction currency * TradeToPortfolioRate #### Example Transactions ##### A Common Purchase Example Three example transactions are shown in the table below. They represent a purchase of USD denominated IBM shares within a Sterling denominated portfolio. * The first two transactions are for separate buy and fx trades * Buying 500 IBM shares for $71,480.00 * A spot foreign exchange conversion to fund the IBM purchase. (Buy $71,480.00 for &#163;54,846.60) * The third transaction is an alternate version of the above trades. Buying 500 IBM shares and settling directly in Sterling. | Column | Buy Trade | Fx Trade | Buy Trade with foreign Settlement | | - -- -- | - -- -- | - -- -- | - -- -- | | TransactionId | FBN00001 | FBN00002 | FBN00003 | | Type | Buy | FxBuy | Buy | | InstrumentIdentifiers | { \"figi\", \"BBG000BLNNH6\" } | { \"CCY\", \"CCY_USD\" } | { \"figi\", \"BBG000BLNNH6\" } | | TransactionDate | 2018-08-02 | 2018-08-02 | 2018-08-02 | | SettlementDate | 2018-08-06 | 2018-08-06 | 2018-08-06 | | Units | 500 | 71480 | 500 | | TransactionPrice | 142.96 | 1 | 142.96 | | TradeCurrency | USD | USD | USD | | ExchangeRate | 1 | 0.7673 | 0.7673 | | TotalConsideration.Amount | 71480.00 | 54846.60 | 54846.60 | | TotalConsideration.Currency | USD | GBP | GBP | | Trade/default/TradeToPortfolioRate&ast; | 0.7673 | 0.7673 | 0.7673 | [&ast; This is a property field] ##### A Forward FX Example LUSID has a flexible transaction modelling system, meaning there are a number of different ways of modelling forward fx trades. The default LUSID transaction types are FwdFxBuy and FwdFxSell. Using these transaction types, LUSID will generate two holdings for each Forward FX trade, one for each currency in the trade. An example Forward Fx trade to sell GBP for USD in a JPY-denominated portfolio is shown below: | Column | Forward 'Sell' Trade | Notes | | - -- -- | - -- -- | - -- - | | TransactionId | FBN00004 | | | Type | FwdFxSell | | | InstrumentIdentifiers | { \"Instrument/default/Currency\", \"GBP\" } | | | TransactionDate | 2018-08-02 | | | SettlementDate | 2019-02-06 | Six month forward | | Units | 10000.00 | Units of GBP | | TransactionPrice | 1 | | | TradeCurrency | GBP | Currency being sold | | ExchangeRate | 1.3142 | Agreed rate between GBP and USD | | TotalConsideration.Amount | 13142.00 | Amount in the settlement currency, USD | | TotalConsideration.Currency | USD | Settlement currency | | Trade/default/TradeToPortfolioRate | 142.88 | Rate between trade currency, GBP and portfolio base currency, JPY | Please note that exactly the same economic behaviour could be modelled using the FwdFxBuy Transaction Type with the amounts and rates reversed. ### Holdings A holding represents a position in an instrument or cash on a given date. | Field|Type|Description | | - --|- --|- -- | | InstrumentUid|string|The unqiue Lusid Instrument Id (LUID) of the instrument that the holding is in. | | SubHoldingKeys|map|The sub-holding properties which identify the holding. Each property will be from the 'Transaction' domain. These are configured when a transaction portfolio is created. | | Properties|map|The properties which have been requested to be decorated onto the holding. These will be from the 'Instrument' or 'Holding' domain. | | HoldingType|string|The type of the holding e.g. Position, Balance, CashCommitment, Receivable, ForwardFX etc. | | Units|decimal|The total number of units of the holding. | | SettledUnits|decimal|The total number of settled units of the holding. | | Cost|currencyandamount|The total cost of the holding in the transaction currency. | | CostPortfolioCcy|currencyandamount|The total cost of the holding in the portfolio currency. | | Transaction|transaction|The transaction associated with an unsettled holding. | ## Corporate Actions Corporate actions are represented within LUSID in terms of a set of instrument-specific 'transitions'. These transitions are used to specify the participants of the corporate action, and the effect that the corporate action will have on holdings in those participants. ### Corporate Action | Field|Type|Description | | - --|- --|- -- | | CorporateActionCode|code|The unique identifier of this corporate action | | Description|string| | | AnnouncementDate|datetimeoffset|The announcement date of the corporate action | | ExDate|datetimeoffset|The ex date of the corporate action | | RecordDate|datetimeoffset|The record date of the corporate action | | PaymentDate|datetimeoffset|The payment date of the corporate action | | Transitions|corporateactiontransition[]|The transitions that result from this corporate action | ### Transition | Field|Type|Description | | - --|- --|- -- | | InputTransition|corporateactiontransitioncomponent|Indicating the basis of the corporate action - which security and how many units | | OutputTransitions|corporateactiontransitioncomponent[]|What will be generated relative to the input transition | ### Example Corporate Action Transitions #### A Dividend Action Transition In this example, for each share of IBM, 0.20 units (or 20 pence) of GBP are generated. | Column | Input Transition | Output Transition | | - -- -- | - -- -- | - -- -- | | Instrument Identifiers | { \"figi\" : \"BBG000BLNNH6\" } | { \"ccy\" : \"CCY_GBP\" } | | Units Factor | 1 | 0.20 | | Cost Factor | 1 | 0 | #### A Split Action Transition In this example, for each share of IBM, we end up with 2 units (2 shares) of IBM, with total value unchanged. | Column | Input Transition | Output Transition | | - -- -- | - -- -- | - -- -- | | Instrument Identifiers | { \"figi\" : \"BBG000BLNNH6\" } | { \"figi\" : \"BBG000BLNNH6\" } | | Units Factor | 1 | 2 | | Cost Factor | 1 | 1 | #### A Spinoff Action Transition In this example, for each share of IBM, we end up with 1 unit (1 share) of IBM and 3 units (3 shares) of Celestica, with 85% of the value remaining on the IBM share, and 5% in each Celestica share (15% total). | Column | Input Transition | Output Transition 1 | Output Transition 2 | | - -- -- | - -- -- | - -- -- | - -- -- | | Instrument Identifiers | { \"figi\" : \"BBG000BLNNH6\" } | { \"figi\" : \"BBG000BLNNH6\" } | { \"figi\" : \"BBG000HBGRF3\" } | | Units Factor | 1 | 1 | 3 | | Cost Factor | 1 | 0.85 | 0.15 | ## Reference Portfolios Reference portfolios are portfolios that contain constituents with weights. They are designed to represent entities such as indices and benchmarks. ### Constituents | Field|Type|Description | | - --|- --|- -- | | InstrumentIdentifiers|map|Unique instrument identifiers | | InstrumentUid|string|LUSID's internal unique instrument identifier, resolved from the instrument identifiers | | Currency|decimal| | | Weight|decimal| | | FloatingWeight|decimal| | ## Portfolio Groups Portfolio groups allow the construction of a hierarchy from portfolios and groups. Portfolio operations on the group are executed on an aggregated set of portfolios in the hierarchy. For example: * Global Portfolios _(group)_ * APAC _(group)_ * Hong Kong _(portfolio)_ * Japan _(portfolio)_ * Europe _(group)_ * France _(portfolio)_ * Germany _(portfolio)_ * UK _(portfolio)_ In this example **Global Portfolios** is a group that consists of an aggregate of **Hong Kong**, **Japan**, **France**, **Germany** and **UK** portfolios. ## Properties Properties are key-value pairs that can be applied to any entity within a domain (where a domain is `trade`, `portfolio`, `security` etc). Properties must be defined before use with a `PropertyDefinition` and can then subsequently be added to entities. ## Schema A detailed description of the entities used by the API and parameters for endpoints which take a JSON document can be retrieved via the `schema` endpoint. ## Meta data The following headers are returned on all responses from LUSID | Name | Purpose | | - -- | - -- | | lusid-meta-duration | Duration of the request | | lusid-meta-success | Whether or not LUSID considered the request to be successful | | lusid-meta-requestId | The unique identifier for the request | | lusid-schema-url | Url of the schema for the data being returned | | lusid-property-schema-url | Url of the schema for any properties | # Error Codes | Code|Name|Description | | - --|- --|- -- | | <a name=\"-10\">-10</a>|Server Configuration Error| | | <a name=\"-1\">-1</a>|Unknown error|An unexpected error was encountered on our side. | | <a name=\"102\">102</a>|Version Not Found| | | <a name=\"103\">103</a>|Api Rate Limit Violation| | | <a name=\"104\">104</a>|Instrument Not Found| | | <a name=\"105\">105</a>|Property Not Found| | | <a name=\"106\">106</a>|Portfolio Recursion Depth| | | <a name=\"108\">108</a>|Group Not Found| | | <a name=\"109\">109</a>|Portfolio Not Found| | | <a name=\"110\">110</a>|Property Schema Not Found| | | <a name=\"111\">111</a>|Portfolio Ancestry Not Found| | | <a name=\"112\">112</a>|Portfolio With Id Already Exists| | | <a name=\"113\">113</a>|Orphaned Portfolio| | | <a name=\"119\">119</a>|Missing Base Claims| | | <a name=\"121\">121</a>|Property Not Defined| | | <a name=\"122\">122</a>|Cannot Delete System Property| | | <a name=\"123\">123</a>|Cannot Modify Immutable Property Field| | | <a name=\"124\">124</a>|Property Already Exists| | | <a name=\"125\">125</a>|Invalid Property Life Time| | | <a name=\"126\">126</a>|Property Constraint Style Excludes Properties| | | <a name=\"127\">127</a>|Cannot Modify Default Data Type| | | <a name=\"128\">128</a>|Group Already Exists| | | <a name=\"129\">129</a>|No Such Data Type| | | <a name=\"130\">130</a>|Undefined Value For Data Type| | | <a name=\"131\">131</a>|Unsupported Value Type Defined On Data Type| | | <a name=\"132\">132</a>|Validation Error| | | <a name=\"133\">133</a>|Loop Detected In Group Hierarchy| | | <a name=\"134\">134</a>|Undefined Acceptable Values| | | <a name=\"135\">135</a>|Sub Group Already Exists| | | <a name=\"138\">138</a>|Price Source Not Found| | | <a name=\"139\">139</a>|Analytic Store Not Found| | | <a name=\"141\">141</a>|Analytic Store Already Exists| | | <a name=\"143\">143</a>|Client Instrument Already Exists| | | <a name=\"144\">144</a>|Duplicate In Parameter Set| | | <a name=\"147\">147</a>|Results Not Found| | | <a name=\"148\">148</a>|Order Field Not In Result Set| | | <a name=\"149\">149</a>|Operation Failed| | | <a name=\"150\">150</a>|Elastic Search Error| | | <a name=\"151\">151</a>|Invalid Parameter Value| | | <a name=\"153\">153</a>|Command Processing Failure| | | <a name=\"154\">154</a>|Entity State Construction Failure| | | <a name=\"155\">155</a>|Entity Timeline Does Not Exist| | | <a name=\"156\">156</a>|Concurrency Conflict Failure| | | <a name=\"157\">157</a>|Invalid Request| | | <a name=\"158\">158</a>|Event Publish Unknown| | | <a name=\"159\">159</a>|Event Query Failure| | | <a name=\"160\">160</a>|Blob Did Not Exist| | | <a name=\"162\">162</a>|Sub System Request Failure| | | <a name=\"163\">163</a>|Sub System Configuration Failure| | | <a name=\"165\">165</a>|Failed To Delete| | | <a name=\"166\">166</a>|Upsert Client Instrument Failure| | | <a name=\"167\">167</a>|Illegal As At Interval| | | <a name=\"168\">168</a>|Illegal Bitemporal Query| | | <a name=\"169\">169</a>|Invalid Alternate Id| | | <a name=\"170\">170</a>|Cannot Add Source Portfolio Property Explicitly| | | <a name=\"171\">171</a>|Entity Already Exists In Group| | | <a name=\"173\">173</a>|Entity With Id Already Exists| | | <a name=\"174\">174</a>|Derived Portfolio Details Do Not Exist| | | <a name=\"176\">176</a>|Portfolio With Name Already Exists| | | <a name=\"177\">177</a>|Invalid Transactions| | | <a name=\"178\">178</a>|Reference Portfolio Not Found| | | <a name=\"179\">179</a>|Duplicate Id| | | <a name=\"180\">180</a>|Command Retrieval Failure| | | <a name=\"181\">181</a>|Data Filter Application Failure| | | <a name=\"182\">182</a>|Search Failed| | | <a name=\"183\">183</a>|Movements Engine Configuration Key Failure| | | <a name=\"184\">184</a>|Fx Rate Source Not Found| | | <a name=\"185\">185</a>|Accrual Source Not Found| | | <a name=\"186\">186</a>|Access Denied| | | <a name=\"187\">187</a>|Invalid Identity Token| | | <a name=\"188\">188</a>|Invalid Request Headers| | | <a name=\"189\">189</a>|Price Not Found| | | <a name=\"190\">190</a>|Invalid Sub Holding Keys Provided| | | <a name=\"191\">191</a>|Duplicate Sub Holding Keys Provided| | | <a name=\"192\">192</a>|Cut Definition Not Found| | | <a name=\"193\">193</a>|Cut Definition Invalid| | | <a name=\"194\">194</a>|Time Variant Property Deletion Date Unspecified| | | <a name=\"195\">195</a>|Perpetual Property Deletion Date Specified| | | <a name=\"196\">196</a>|Time Variant Property Upsert Date Unspecified| | | <a name=\"197\">197</a>|Perpetual Property Upsert Date Specified| | | <a name=\"200\">200</a>|Invalid Unit For Data Type| | | <a name=\"201\">201</a>|Invalid Type For Data Type| | | <a name=\"202\">202</a>|Invalid Value For Data Type| | | <a name=\"203\">203</a>|Unit Not Defined For Data Type| | | <a name=\"204\">204</a>|Units Not Supported On Data Type| | | <a name=\"205\">205</a>|Cannot Specify Units On Data Type| | | <a name=\"206\">206</a>|Unit Schema Inconsistent With Data Type| | | <a name=\"207\">207</a>|Unit Definition Not Specified| | | <a name=\"208\">208</a>|Duplicate Unit Definitions Specified| | | <a name=\"209\">209</a>|Invalid Units Definition| | | <a name=\"210\">210</a>|Invalid Instrument Identifier Unit| | | <a name=\"211\">211</a>|Holdings Adjustment Does Not Exist| | | <a name=\"212\">212</a>|Could Not Build Excel Url| | | <a name=\"213\">213</a>|Could Not Get Excel Version| | | <a name=\"214\">214</a>|Instrument By Code Not Found| | | <a name=\"215\">215</a>|Entity Schema Does Not Exist| | | <a name=\"216\">216</a>|Feature Not Supported On Portfolio Type| | | <a name=\"217\">217</a>|Quote Not Found| | | <a name=\"218\">218</a>|Invalid Quote Identifier| | | <a name=\"219\">219</a>|Invalid Metric For Data Type| | | <a name=\"220\">220</a>|Invalid Instrument Definition| | | <a name=\"221\">221</a>|Instrument Upsert Failure| | | <a name=\"222\">222</a>|Reference Portfolio Request Not Supported| | | <a name=\"223\">223</a>|Transaction Portfolio Request Not Supported| | | <a name=\"224\">224</a>|Invalid Property Value Assignment| | | <a name=\"230\">230</a>|Transaction Type Not Found| | | <a name=\"231\">231</a>|Transaction Type Duplication| | | <a name=\"232\">232</a>|Portfolio Does Not Exist At Given Date| | | <a name=\"233\">233</a>|Query Parser Failure| | | <a name=\"234\">234</a>|Duplicate Constituent| | | <a name=\"235\">235</a>|Unresolved Instrument Constituent| | | <a name=\"236\">236</a>|Unresolved Instrument In Transition| | | <a name=\"237\">237</a>|Missing Side Definitions| | | <a name=\"299\">299</a>|Invalid Recipe| | | <a name=\"300\">300</a>|Missing Recipe| | | <a name=\"301\">301</a>|Dependencies| | | <a name=\"304\">304</a>|Portfolio Preprocess Failure| | | <a name=\"310\">310</a>|Valuation Engine Failure| | | <a name=\"311\">311</a>|Task Factory Failure| | | <a name=\"312\">312</a>|Task Evaluation Failure| | | <a name=\"313\">313</a>|Task Generation Failure| | | <a name=\"314\">314</a>|Engine Configuration Failure| | | <a name=\"315\">315</a>|Model Specification Failure| | | <a name=\"320\">320</a>|Market Data Key Failure| | | <a name=\"321\">321</a>|Market Resolver Failure| | | <a name=\"322\">322</a>|Market Data Failure| | | <a name=\"330\">330</a>|Curve Failure| | | <a name=\"331\">331</a>|Volatility Surface Failure| | | <a name=\"332\">332</a>|Volatility Cube Failure| | | <a name=\"350\">350</a>|Instrument Failure| | | <a name=\"351\">351</a>|Cash Flows Failure| | | <a name=\"352\">352</a>|Reference Data Failure| | | <a name=\"360\">360</a>|Aggregation Failure| | | <a name=\"361\">361</a>|Aggregation Measure Failure| | | <a name=\"370\">370</a>|Result Retrieval Failure| | | <a name=\"371\">371</a>|Result Processing Failure| | | <a name=\"372\">372</a>|Vendor Result Processing Failure| | | <a name=\"373\">373</a>|Vendor Result Mapping Failure| | | <a name=\"374\">374</a>|Vendor Library Unauthorised| | | <a name=\"375\">375</a>|Vendor Connectivity Error| | | <a name=\"376\">376</a>|Vendor Interface Error| | | <a name=\"377\">377</a>|Vendor Pricing Failure| | | <a name=\"378\">378</a>|Vendor Translation Failure| | | <a name=\"379\">379</a>|Vendor Key Mapping Failure| | | <a name=\"380\">380</a>|Vendor Reflection Failure| | | <a name=\"390\">390</a>|Attempt To Upsert Duplicate Quotes| | | <a name=\"391\">391</a>|Corporate Action Source Does Not Exist| | | <a name=\"392\">392</a>|Corporate Action Source Already Exists| | | <a name=\"393\">393</a>|Instrument Identifier Already In Use| | | <a name=\"394\">394</a>|Properties Not Found| | | <a name=\"395\">395</a>|Batch Operation Aborted| | | <a name=\"400\">400</a>|Invalid Iso4217 Currency Code| | | <a name=\"401\">401</a>|Cannot Assign Instrument Identifier To Currency| | | <a name=\"402\">402</a>|Cannot Assign Currency Identifier To Non Currency| | | <a name=\"403\">403</a>|Currency Instrument Cannot Be Deleted| | | <a name=\"404\">404</a>|Currency Instrument Cannot Have Economic Definition| | | <a name=\"405\">405</a>|Currency Instrument Cannot Have Lookthrough Portfolio| | | <a name=\"406\">406</a>|Cannot Create Currency Instrument With Multiple Identifiers| | | <a name=\"407\">407</a>|Specified Currency Is Undefined| | | <a name=\"410\">410</a>|Index Does Not Exist| | | <a name=\"411\">411</a>|Sort Field Does Not Exist| | | <a name=\"413\">413</a>|Negative Pagination Parameters| | | <a name=\"414\">414</a>|Invalid Search Syntax| | | <a name=\"415\">415</a>|Filter Execution Timeout| | | <a name=\"420\">420</a>|Side Definition Inconsistent| | | <a name=\"450\">450</a>|Invalid Quote Access Metadata Rule| | | <a name=\"451\">451</a>|Access Metadata Not Found| | | <a name=\"452\">452</a>|Invalid Access Metadata Identifier| | | <a name=\"460\">460</a>|Standard Resource Not Found| | | <a name=\"461\">461</a>|Standard Resource Conflict| | | <a name=\"462\">462</a>|Calendar Not Found| | | <a name=\"463\">463</a>|Date In A Calendar Not Found| | | <a name=\"464\">464</a>|Invalid Date Source Data| | | <a name=\"465\">465</a>|Invalid Timezone| | | <a name=\"601\">601</a>|Person Identifier Already In Use| | | <a name=\"602\">602</a>|Person Not Found| | | <a name=\"603\">603</a>|Cannot Set Identifier| | | <a name=\"617\">617</a>|Invalid Recipe Specification In Request| | | <a name=\"618\">618</a>|Inline Recipe Deserialisation Failure| | | <a name=\"619\">619</a>|Identifier Types Not Set For Entity| | | <a name=\"620\">620</a>|Cannot Delete All Client Defined Identifiers| | | <a name=\"650\">650</a>|The Order requested was not found.| | | <a name=\"654\">654</a>|The Allocation requested was not found.| | | <a name=\"655\">655</a>|Cannot build the fx forward target with the given holdings.| | | <a name=\"656\">656</a>|Group does not contain expected entities.| | | <a name=\"667\">667</a>|Relation definition already exists| | | <a name=\"673\">673</a>|Missing entitlements for entities in Group| | | <a name=\"674\">674</a>|Next Best Action not found| | | <a name=\"676\">676</a>|Relation definition not defined| | | <a name=\"677\">677</a>|Invalid entity identifier for relation| | | <a name=\"681\">681</a>|Sorting by specified field not supported|One or more of the provided fields to order by were either invalid or not supported. | | <a name=\"682\">682</a>|Too many fields to sort by|The number of fields to sort the data by exceeds the number allowed by the endpoint | | <a name=\"684\">684</a>|Sequence Not Found| | | <a name=\"685\">685</a>|Sequence Already Exists| | | <a name=\"686\">686</a>|Non-cycling sequence has been exhausted| | | <a name=\"687\">687</a>|Legal Entity Identifier Already In Use| | | <a name=\"688\">688</a>|Legal Entity Not Found| | | <a name=\"689\">689</a>|The supplied pagination token is invalid| | | <a name=\"690\">690</a>|Property Type Is Not Supported| | | <a name=\"691\">691</a>|Multiple Tax-lots For Currency Type Is Not Supported| | | <a name=\"692\">692</a>|This endpoint does not support impersonation| | * * The version of the OpenAPI document: 0.11.2295 * Contact: info@finbourne.com * Generated by: https://github.com/openapitools/openapi-generator.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using OpenAPIDateConverter = Lusid.Sdk.Client.OpenAPIDateConverter; namespace Lusid.Sdk.Model { /// <summary> /// ExpandedGroup /// </summary> [DataContract] public partial class ExpandedGroup : IEquatable<ExpandedGroup> { /// <summary> /// Initializes a new instance of the <see cref="ExpandedGroup" /> class. /// </summary> [JsonConstructorAttribute] protected ExpandedGroup() { } /// <summary> /// Initializes a new instance of the <see cref="ExpandedGroup" /> class. /// </summary> /// <param name="href">The specific Uniform Resource Identifier (URI) for this resource at the requested effective and asAt datetime..</param> /// <param name="id">id (required).</param> /// <param name="displayName">The name of the portfolio group. (required).</param> /// <param name="description">The long form description of the portfolio group..</param> /// <param name="values">The collection of resource identifiers for the portfolios contained in the portfolio group..</param> /// <param name="subGroups">The collection of resource identifiers for the portfolio groups contained in the portfolio group as sub groups..</param> /// <param name="version">version.</param> /// <param name="links">links.</param> public ExpandedGroup(string href = default(string), ResourceId id = default(ResourceId), string displayName = default(string), string description = default(string), List<CompletePortfolio> values = default(List<CompletePortfolio>), List<ExpandedGroup> subGroups = default(List<ExpandedGroup>), Version version = default(Version), List<Link> links = default(List<Link>)) { this.Href = href; // to ensure "id" is required (not null) if (id == null) { throw new InvalidDataException("id is a required property for ExpandedGroup and cannot be null"); } else { this.Id = id; } // to ensure "displayName" is required (not null) if (displayName == null) { throw new InvalidDataException("displayName is a required property for ExpandedGroup and cannot be null"); } else { this.DisplayName = displayName; } this.Description = description; this.Values = values; this.SubGroups = subGroups; this.Links = links; this.Href = href; this.Description = description; this.Values = values; this.SubGroups = subGroups; this.Version = version; this.Links = links; } /// <summary> /// The specific Uniform Resource Identifier (URI) for this resource at the requested effective and asAt datetime. /// </summary> /// <value>The specific Uniform Resource Identifier (URI) for this resource at the requested effective and asAt datetime.</value> [DataMember(Name="href", EmitDefaultValue=true)] public string Href { get; set; } /// <summary> /// Gets or Sets Id /// </summary> [DataMember(Name="id", EmitDefaultValue=false)] public ResourceId Id { get; set; } /// <summary> /// The name of the portfolio group. /// </summary> /// <value>The name of the portfolio group.</value> [DataMember(Name="displayName", EmitDefaultValue=false)] public string DisplayName { get; set; } /// <summary> /// The long form description of the portfolio group. /// </summary> /// <value>The long form description of the portfolio group.</value> [DataMember(Name="description", EmitDefaultValue=true)] public string Description { get; set; } /// <summary> /// The collection of resource identifiers for the portfolios contained in the portfolio group. /// </summary> /// <value>The collection of resource identifiers for the portfolios contained in the portfolio group.</value> [DataMember(Name="values", EmitDefaultValue=true)] public List<CompletePortfolio> Values { get; set; } /// <summary> /// The collection of resource identifiers for the portfolio groups contained in the portfolio group as sub groups. /// </summary> /// <value>The collection of resource identifiers for the portfolio groups contained in the portfolio group as sub groups.</value> [DataMember(Name="subGroups", EmitDefaultValue=true)] public List<ExpandedGroup> SubGroups { get; set; } /// <summary> /// Gets or Sets Version /// </summary> [DataMember(Name="version", EmitDefaultValue=false)] public Version Version { get; set; } /// <summary> /// Gets or Sets Links /// </summary> [DataMember(Name="links", EmitDefaultValue=true)] public List<Link> Links { 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 ExpandedGroup {\n"); sb.Append(" Href: ").Append(Href).Append("\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" DisplayName: ").Append(DisplayName).Append("\n"); sb.Append(" Description: ").Append(Description).Append("\n"); sb.Append(" Values: ").Append(Values).Append("\n"); sb.Append(" SubGroups: ").Append(SubGroups).Append("\n"); sb.Append(" Version: ").Append(Version).Append("\n"); sb.Append(" Links: ").Append(Links).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public virtual string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as ExpandedGroup); } /// <summary> /// Returns true if ExpandedGroup instances are equal /// </summary> /// <param name="input">Instance of ExpandedGroup to be compared</param> /// <returns>Boolean</returns> public bool Equals(ExpandedGroup input) { if (input == null) return false; return ( this.Href == input.Href || (this.Href != null && this.Href.Equals(input.Href)) ) && ( this.Id == input.Id || (this.Id != null && this.Id.Equals(input.Id)) ) && ( this.DisplayName == input.DisplayName || (this.DisplayName != null && this.DisplayName.Equals(input.DisplayName)) ) && ( this.Description == input.Description || (this.Description != null && this.Description.Equals(input.Description)) ) && ( this.Values == input.Values || this.Values != null && input.Values != null && this.Values.SequenceEqual(input.Values) ) && ( this.SubGroups == input.SubGroups || this.SubGroups != null && input.SubGroups != null && this.SubGroups.SequenceEqual(input.SubGroups) ) && ( this.Version == input.Version || (this.Version != null && this.Version.Equals(input.Version)) ) && ( this.Links == input.Links || this.Links != null && input.Links != null && this.Links.SequenceEqual(input.Links) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.Href != null) hashCode = hashCode * 59 + this.Href.GetHashCode(); if (this.Id != null) hashCode = hashCode * 59 + this.Id.GetHashCode(); if (this.DisplayName != null) hashCode = hashCode * 59 + this.DisplayName.GetHashCode(); if (this.Description != null) hashCode = hashCode * 59 + this.Description.GetHashCode(); if (this.Values != null) hashCode = hashCode * 59 + this.Values.GetHashCode(); if (this.SubGroups != null) hashCode = hashCode * 59 + this.SubGroups.GetHashCode(); if (this.Version != null) hashCode = hashCode * 59 + this.Version.GetHashCode(); if (this.Links != null) hashCode = hashCode * 59 + this.Links.GetHashCode(); return hashCode; } } } }
150.386973
28,764
0.659372
[ "MIT" ]
sgiulians/lusid-sdk-csharp
sdk/Lusid.Sdk/Model/ExpandedGroup.cs
39,251
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; namespace FileBackupper.Db { class PathInfo { public int Id { get; set; } public Target Target { get; set; } [Index] public string Name { get; set; } public PathInfo Parent { get; set; } [ForeignKey("Parent")] public int? ParentId { get; set; } public ICollection<PathInfo> Children { get; set; } /// <summary> /// Itemがnullならディレクトリ /// </summary> public ItemInfo Item { get; set; } public long Creation { get; set; } public long LastWrite { get; set; } [Index] public DateTime RegisterDate { get; set; } [Index] public DateTime? RemoveDate { get; set; } [NotMapped] public string Path => ParentId + "\\" + Name; } }
22.452381
60
0.538706
[ "MIT" ]
ShTair/FileBackupper
FileBackupper/Db/PathInfo.cs
963
C#
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // Template Source: Templates\CSharp\Requests\EntityCollectionRequestBuilder.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; /// <summary> /// The type PostMultiValueExtendedPropertiesCollectionRequestBuilder. /// </summary> public partial class PostMultiValueExtendedPropertiesCollectionRequestBuilder : BaseRequestBuilder, IPostMultiValueExtendedPropertiesCollectionRequestBuilder { /// <summary> /// Constructs a new PostMultiValueExtendedPropertiesCollectionRequestBuilder. /// </summary> /// <param name="requestUrl">The URL for the built request.</param> /// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param> public PostMultiValueExtendedPropertiesCollectionRequestBuilder( string requestUrl, IBaseClient client) : base(requestUrl, client) { } /// <summary> /// Builds the request. /// </summary> /// <returns>The built request.</returns> public IPostMultiValueExtendedPropertiesCollectionRequest Request() { return this.Request(null); } /// <summary> /// Builds the request. /// </summary> /// <param name="options">The query and header options for the request.</param> /// <returns>The built request.</returns> public IPostMultiValueExtendedPropertiesCollectionRequest Request(IEnumerable<Option> options) { return new PostMultiValueExtendedPropertiesCollectionRequest(this.RequestUrl, this.Client, options); } /// <summary> /// Gets an <see cref="IMultiValueLegacyExtendedPropertyRequestBuilder"/> for the specified PostMultiValueLegacyExtendedProperty. /// </summary> /// <param name="id">The ID for the PostMultiValueLegacyExtendedProperty.</param> /// <returns>The <see cref="IMultiValueLegacyExtendedPropertyRequestBuilder"/>.</returns> public IMultiValueLegacyExtendedPropertyRequestBuilder this[string id] { get { return new MultiValueLegacyExtendedPropertyRequestBuilder(this.AppendSegmentToRequestUrl(id), this.Client); } } } }
41.846154
161
0.627574
[ "MIT" ]
AzureMentor/msgraph-sdk-dotnet
src/Microsoft.Graph/Requests/Generated/PostMultiValueExtendedPropertiesCollectionRequestBuilder.cs
2,720
C#
// ------------------------------------------------------------------------------ // <auto-generated> // Generated by Xsd2Code. Version 3.4.0.18239 Microsoft Reciprocal License (Ms-RL) // <NameSpace>Mim.V6301</NameSpace><Collection>Array</Collection><codeType>CSharp</codeType><EnableDataBinding>False</EnableDataBinding><EnableLazyLoading>False</EnableLazyLoading><TrackingChangesEnable>False</TrackingChangesEnable><GenTrackingClasses>False</GenTrackingClasses><HidePrivateFieldInIDE>False</HidePrivateFieldInIDE><EnableSummaryComment>True</EnableSummaryComment><VirtualProp>False</VirtualProp><IncludeSerializeMethod>True</IncludeSerializeMethod><UseBaseClass>False</UseBaseClass><GenBaseClass>False</GenBaseClass><GenerateCloneMethod>True</GenerateCloneMethod><GenerateDataContracts>False</GenerateDataContracts><CodeBaseTag>Net35</CodeBaseTag><SerializeMethodName>Serialize</SerializeMethodName><DeserializeMethodName>Deserialize</DeserializeMethodName><SaveToFileMethodName>SaveToFile</SaveToFileMethodName><LoadFromFileMethodName>LoadFromFile</LoadFromFileMethodName><GenerateXMLAttributes>True</GenerateXMLAttributes><OrderXMLAttrib>False</OrderXMLAttrib><EnableEncoding>False</EnableEncoding><AutomaticProperties>False</AutomaticProperties><GenerateShouldSerialize>False</GenerateShouldSerialize><DisableDebug>False</DisableDebug><PropNameSpecified>Default</PropNameSpecified><Encoder>UTF8</Encoder><CustomUsings></CustomUsings><ExcludeIncludedTypes>True</ExcludeIncludedTypes><EnableInitializeFields>False</EnableInitializeFields> // </auto-generated> // ------------------------------------------------------------------------------ namespace Mim.V6301 { using System; using System.Diagnostics; using System.Xml.Serialization; using System.Collections; using System.Xml.Schema; using System.ComponentModel; using System.IO; using System.Text; [System.CodeDom.Compiler.GeneratedCodeAttribute("Xsd2Code", "3.4.0.18239")] [System.SerializableAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.XmlTypeAttribute(TypeName="UKCT_MT142101UK01.OrganizationSDS", Namespace="urn:hl7-org:v3")] public partial class UKCT_MT142101UK01OrganizationSDS { private II idField; private string typeField; private string classCodeField; private string determinerCodeField; private string[] typeIDField; private string[] realmCodeField; private string nullFlavorField; private static System.Xml.Serialization.XmlSerializer serializer; public UKCT_MT142101UK01OrganizationSDS() { this.typeField = "Organization"; this.classCodeField = "ORG"; this.determinerCodeField = "INSTANCE"; } public II id { get { return this.idField; } set { this.idField = value; } } [System.Xml.Serialization.XmlAttributeAttribute(DataType="token")] public string type { get { return this.typeField; } set { this.typeField = value; } } [System.Xml.Serialization.XmlAttributeAttribute()] public string classCode { get { return this.classCodeField; } set { this.classCodeField = value; } } [System.Xml.Serialization.XmlAttributeAttribute()] public string determinerCode { get { return this.determinerCodeField; } set { this.determinerCodeField = value; } } [System.Xml.Serialization.XmlAttributeAttribute()] public string[] typeID { get { return this.typeIDField; } set { this.typeIDField = value; } } [System.Xml.Serialization.XmlAttributeAttribute(DataType="token")] public string[] realmCode { get { return this.realmCodeField; } set { this.realmCodeField = value; } } [System.Xml.Serialization.XmlAttributeAttribute(DataType="token")] public string nullFlavor { get { return this.nullFlavorField; } set { this.nullFlavorField = value; } } private static System.Xml.Serialization.XmlSerializer Serializer { get { if ((serializer == null)) { serializer = new System.Xml.Serialization.XmlSerializer(typeof(UKCT_MT142101UK01OrganizationSDS)); } return serializer; } } #region Serialize/Deserialize /// <summary> /// Serializes current UKCT_MT142101UK01OrganizationSDS object into an XML document /// </summary> /// <returns>string XML value</returns> public virtual string Serialize() { System.IO.StreamReader streamReader = null; System.IO.MemoryStream memoryStream = null; try { memoryStream = new System.IO.MemoryStream(); Serializer.Serialize(memoryStream, this); memoryStream.Seek(0, System.IO.SeekOrigin.Begin); streamReader = new System.IO.StreamReader(memoryStream); return streamReader.ReadToEnd(); } finally { if ((streamReader != null)) { streamReader.Dispose(); } if ((memoryStream != null)) { memoryStream.Dispose(); } } } /// <summary> /// Deserializes workflow markup into an UKCT_MT142101UK01OrganizationSDS object /// </summary> /// <param name="xml">string workflow markup to deserialize</param> /// <param name="obj">Output UKCT_MT142101UK01OrganizationSDS object</param> /// <param name="exception">output Exception value if deserialize failed</param> /// <returns>true if this XmlSerializer can deserialize the object; otherwise, false</returns> public static bool Deserialize(string xml, out UKCT_MT142101UK01OrganizationSDS obj, out System.Exception exception) { exception = null; obj = default(UKCT_MT142101UK01OrganizationSDS); try { obj = Deserialize(xml); return true; } catch (System.Exception ex) { exception = ex; return false; } } public static bool Deserialize(string xml, out UKCT_MT142101UK01OrganizationSDS obj) { System.Exception exception = null; return Deserialize(xml, out obj, out exception); } public static UKCT_MT142101UK01OrganizationSDS Deserialize(string xml) { System.IO.StringReader stringReader = null; try { stringReader = new System.IO.StringReader(xml); return ((UKCT_MT142101UK01OrganizationSDS)(Serializer.Deserialize(System.Xml.XmlReader.Create(stringReader)))); } finally { if ((stringReader != null)) { stringReader.Dispose(); } } } /// <summary> /// Serializes current UKCT_MT142101UK01OrganizationSDS object into file /// </summary> /// <param name="fileName">full path of outupt xml file</param> /// <param name="exception">output Exception value if failed</param> /// <returns>true if can serialize and save into file; otherwise, false</returns> public virtual bool SaveToFile(string fileName, out System.Exception exception) { exception = null; try { SaveToFile(fileName); return true; } catch (System.Exception e) { exception = e; return false; } } public virtual void SaveToFile(string fileName) { System.IO.StreamWriter streamWriter = null; try { string xmlString = Serialize(); System.IO.FileInfo xmlFile = new System.IO.FileInfo(fileName); streamWriter = xmlFile.CreateText(); streamWriter.WriteLine(xmlString); streamWriter.Close(); } finally { if ((streamWriter != null)) { streamWriter.Dispose(); } } } /// <summary> /// Deserializes xml markup from file into an UKCT_MT142101UK01OrganizationSDS object /// </summary> /// <param name="fileName">string xml file to load and deserialize</param> /// <param name="obj">Output UKCT_MT142101UK01OrganizationSDS object</param> /// <param name="exception">output Exception value if deserialize failed</param> /// <returns>true if this XmlSerializer can deserialize the object; otherwise, false</returns> public static bool LoadFromFile(string fileName, out UKCT_MT142101UK01OrganizationSDS obj, out System.Exception exception) { exception = null; obj = default(UKCT_MT142101UK01OrganizationSDS); try { obj = LoadFromFile(fileName); return true; } catch (System.Exception ex) { exception = ex; return false; } } public static bool LoadFromFile(string fileName, out UKCT_MT142101UK01OrganizationSDS obj) { System.Exception exception = null; return LoadFromFile(fileName, out obj, out exception); } public static UKCT_MT142101UK01OrganizationSDS LoadFromFile(string fileName) { System.IO.FileStream file = null; System.IO.StreamReader sr = null; try { file = new System.IO.FileStream(fileName, FileMode.Open, FileAccess.Read); sr = new System.IO.StreamReader(file); string xmlString = sr.ReadToEnd(); sr.Close(); file.Close(); return Deserialize(xmlString); } finally { if ((file != null)) { file.Dispose(); } if ((sr != null)) { sr.Dispose(); } } } #endregion #region Clone method /// <summary> /// Create a clone of this UKCT_MT142101UK01OrganizationSDS object /// </summary> public virtual UKCT_MT142101UK01OrganizationSDS Clone() { return ((UKCT_MT142101UK01OrganizationSDS)(this.MemberwiseClone())); } #endregion } }
40.748201
1,358
0.571593
[ "MIT" ]
Kusnaditjung/MimDms
src/Mim.V6301/Generated/UKCT_MT142101UK01OrganizationSDS.cs
11,328
C#
using System.ComponentModel.DataAnnotations; using Abp.Auditing; using Abp.Authorization.Users; namespace mcbc.Models.TokenAuth { public class AuthenticateModel { [Required] [StringLength(AbpUserBase.MaxEmailAddressLength)] public string UserNameOrEmailAddress { get; set; } [Required] [StringLength(AbpUserBase.MaxPlainPasswordLength)] [DisableAuditing] public string Password { get; set; } public bool RememberClient { get; set; } } }
24.619048
58
0.68472
[ "MIT" ]
jtechsharp/mcbc
src/mcbc.Web.Core/Models/TokenAuth/AuthenticateModel.cs
519
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Cmdlets { using static Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.Extensions; using System; /// <summary> /// Creates (or updates) a Azure Arc PrivateLinkScope. Note: You cannot specify a different value for InstrumentationKey nor /// AppId in the Put operation. /// </summary> /// <remarks> /// [OpenAPI] CreateOrUpdate=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HybridCompute/privateLinkScopes/{scopeName}" /// </remarks> [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzConnectedPrivateLinkScope_Create", SupportsShouldProcess = true)] [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Models.Api20210520.IHybridComputePrivateLinkScope))] [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Description(@"Creates (or updates) a Azure Arc PrivateLinkScope. Note: You cannot specify a different value for InstrumentationKey nor AppId in the Put operation.")] [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Generated] public partial class NewAzConnectedPrivateLinkScope_Create : global::System.Management.Automation.PSCmdlet, Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.IEventListener { /// <summary>A unique id generatd for the this cmdlet when it is instantiated.</summary> private string __correlationId = System.Guid.NewGuid().ToString(); /// <summary>A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet)</summary> private global::System.Management.Automation.InvocationInfo __invocationInfo; /// <summary>A unique id generatd for the this cmdlet when ProcessRecord() is called.</summary> private string __processRecordId; /// <summary> /// The <see cref="global::System.Threading.CancellationTokenSource" /> for this operation. /// </summary> private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); /// <summary>Wait for .NET debugger to attach</summary> [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.ParameterCategory.Runtime)] public global::System.Management.Automation.SwitchParameter Break { get; set; } /// <summary>The reference to the client API class.</summary> public Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.ConnectedMachine Client => Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Module.Instance.ClientAPI; /// <summary> /// The credentials, account, tenant, and subscription used for communication with Azure /// </summary> [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")] [global::System.Management.Automation.ValidateNotNull] [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.ParameterCategory.Azure)] public global::System.Management.Automation.PSObject DefaultProfile { get; set; } /// <summary>SendAsync Pipeline Steps to be appended to the front of the pipeline</summary> [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] [global::System.Management.Automation.ValidateNotNull] [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.ParameterCategory.Runtime)] public Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.SendAsyncStep[] HttpPipelineAppend { get; set; } /// <summary>SendAsync Pipeline Steps to be prepended to the front of the pipeline</summary> [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be prepended to the front of the pipeline")] [global::System.Management.Automation.ValidateNotNull] [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.ParameterCategory.Runtime)] public Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } /// <summary>Accessor for our copy of the InvocationInfo.</summary> public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } } /// <summary> /// <see cref="IEventListener" /> cancellation delegate. Stops the cmdlet when called. /// </summary> global::System.Action Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; /// <summary><see cref="IEventListener" /> cancellation token.</summary> global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.IEventListener.Token => _cancellationTokenSource.Token; /// <summary>Backing field for <see cref="Parameter" /> property.</summary> private Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Models.Api20210520.IHybridComputePrivateLinkScope _parameter; /// <summary>An Azure Arc PrivateLinkScope definition.</summary> [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "An Azure Arc PrivateLinkScope definition.", ValueFromPipeline = true)] [Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.Info( Required = true, ReadOnly = false, Description = @"An Azure Arc PrivateLinkScope definition.", SerializedName = @"parameters", PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Models.Api20210520.IHybridComputePrivateLinkScope) })] public Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Models.Api20210520.IHybridComputePrivateLinkScope Parameter { get => this._parameter; set => this._parameter = value; } /// <summary> /// The instance of the <see cref="Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.HttpPipeline" /> that the remote call will use. /// </summary> private Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.HttpPipeline Pipeline { get; set; } /// <summary>The URI for the proxy server to use</summary> [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "The URI for the proxy server to use")] [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.ParameterCategory.Runtime)] public global::System.Uri Proxy { get; set; } /// <summary>Credentials for a proxy server to use for the remote call</summary> [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Credentials for a proxy server to use for the remote call")] [global::System.Management.Automation.ValidateNotNull] [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.ParameterCategory.Runtime)] public global::System.Management.Automation.PSCredential ProxyCredential { get; set; } /// <summary>Use the default credentials for the proxy</summary> [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Use the default credentials for the proxy")] [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.ParameterCategory.Runtime)] public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } /// <summary>Backing field for <see cref="ResourceGroupName" /> property.</summary> private string _resourceGroupName; /// <summary>The name of the resource group. The name is case insensitive.</summary> [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the resource group. The name is case insensitive.")] [Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.Info( Required = true, ReadOnly = false, Description = @"The name of the resource group. The name is case insensitive.", SerializedName = @"resourceGroupName", PossibleTypes = new [] { typeof(string) })] [Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.CompleterInfo( Name = @"ResourceGroupName Completer", Description =@"Gets the list of ResourceGroupName's available for this subscription.", Script = @"Get-AzResourceGroup | Select-Object -ExpandProperty ResourceGroupName")] [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.ParameterCategory.Path)] public string ResourceGroupName { get => this._resourceGroupName; set => this._resourceGroupName = value; } /// <summary>Backing field for <see cref="ScopeName" /> property.</summary> private string _scopeName; /// <summary>The name of the Azure Arc PrivateLinkScope resource.</summary> [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the Azure Arc PrivateLinkScope resource.")] [Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.Info( Required = true, ReadOnly = false, Description = @"The name of the Azure Arc PrivateLinkScope resource.", SerializedName = @"scopeName", PossibleTypes = new [] { typeof(string) })] [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.ParameterCategory.Path)] public string ScopeName { get => this._scopeName; set => this._scopeName = value; } /// <summary>Backing field for <see cref="SubscriptionId" /> property.</summary> private string _subscriptionId; /// <summary>The ID of the target subscription.</summary> [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The ID of the target subscription.")] [Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.Info( Required = true, ReadOnly = false, Description = @"The ID of the target subscription.", SerializedName = @"subscriptionId", PossibleTypes = new [] { typeof(string) })] [Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.DefaultInfo( Name = @"", Description =@"", Script = @"(Get-AzContext).Subscription.Id")] [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.ParameterCategory.Path)] public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } /// <summary> /// <c>overrideOnCreated</c> will be called before the regular onCreated has been processed, allowing customization of what /// happens on that response. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="responseMessage">the raw response message as an global::System.Net.Http.HttpResponseMessage.</param> /// <param name="response">the body result as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Models.Api20210520.IHybridComputePrivateLinkScope" /// /> from the remote call</param> /// <param name="returnNow">/// Determines if the rest of the onCreated method should be processed, or if the method should /// return immediately (set to true to skip further processing )</param> partial void overrideOnCreated(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task<Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Models.Api20210520.IHybridComputePrivateLinkScope> response, ref global::System.Threading.Tasks.Task<bool> returnNow); /// <summary> /// <c>overrideOnDefault</c> will be called before the regular onDefault has been processed, allowing customization of what /// happens on that response. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="responseMessage">the raw response message as an global::System.Net.Http.HttpResponseMessage.</param> /// <param name="response">the body result as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Models.Api20.IErrorResponse" /// /> from the remote call</param> /// <param name="returnNow">/// Determines if the rest of the onDefault method should be processed, or if the method should /// return immediately (set to true to skip further processing )</param> partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task<Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Models.Api20.IErrorResponse> response, ref global::System.Threading.Tasks.Task<bool> returnNow); /// <summary> /// <c>overrideOnOk</c> will be called before the regular onOk has been processed, allowing customization of what happens /// on that response. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="responseMessage">the raw response message as an global::System.Net.Http.HttpResponseMessage.</param> /// <param name="response">the body result as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Models.Api20210520.IHybridComputePrivateLinkScope" /// /> from the remote call</param> /// <param name="returnNow">/// Determines if the rest of the onOk method should be processed, or if the method should return /// immediately (set to true to skip further processing )</param> partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task<Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Models.Api20210520.IHybridComputePrivateLinkScope> response, ref global::System.Threading.Tasks.Task<bool> returnNow); /// <summary> /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) /// </summary> protected override void BeginProcessing() { Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); if (Break) { Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.AttachDebugger.Break(); } ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } } /// <summary>Performs clean-up after the command execution</summary> protected override void EndProcessing() { ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } } /// <summary>Handles/Dispatches events during the call to the REST service.</summary> /// <param name="id">The message id</param> /// <param name="token">The message cancellation token. When this call is cancelled, this should be <c>true</c></param> /// <param name="messageData">Detailed message data for the message event.</param> /// <returns> /// A <see cref="global::System.Threading.Tasks.Task" /> that will be complete when handling of the message is completed. /// </returns> async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.IEventListener.Signal(string id, global::System.Threading.CancellationToken token, global::System.Func<Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.EventData> messageData) { using( NoSynchronizationContext ) { if (token.IsCancellationRequested) { return ; } switch ( id ) { case Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.Events.Verbose: { WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); return ; } case Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.Events.Warning: { WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); return ; } case Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.Events.Information: { var data = messageData(); WriteInformation(data.Message, new string[]{}); return ; } case Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.Events.Debug: { WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); return ; } case Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.Events.Error: { WriteError(new global::System.Management.Automation.ErrorRecord( new global::System.Exception(messageData().Message), string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null ) ); return ; } } await Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.EventData ), InvocationInformation, this.ParameterSetName, __correlationId, __processRecordId, null ); if (token.IsCancellationRequested) { return ; } WriteDebug($"{id}: {(messageData().Message ?? global::System.String.Empty)}"); } } /// <summary> /// Intializes a new instance of the <see cref="NewAzConnectedPrivateLinkScope_Create" /> cmdlet class. /// </summary> public NewAzConnectedPrivateLinkScope_Create() { } /// <summary>Performs execution of the command.</summary> protected override void ProcessRecord() { ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } __processRecordId = System.Guid.NewGuid().ToString(); try { // work if (ShouldProcess($"Call remote 'PrivateLinkScopesCreateOrUpdate' operation")) { using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.IEventListener)this).Token) ) { asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.IEventListener)this).Token); } } } catch (global::System.AggregateException aggregateException) { // unroll the inner exceptions to get the root cause foreach( var innerException in aggregateException.Flatten().InnerExceptions ) { ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } // Write exception out to error channel. WriteError( new global::System.Management.Automation.ErrorRecord(innerException,string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null) ); } } catch (global::System.Exception exception) when ((exception as System.Management.Automation.PipelineStoppedException)== null || (exception as System.Management.Automation.PipelineStoppedException).InnerException != null) { ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } // Write exception out to error channel. WriteError( new global::System.Management.Automation.ErrorRecord(exception,string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null) ); } finally { ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.Events.CmdletProcessRecordEnd).Wait(); } } /// <summary>Performs execution of the command, working asynchronously if required.</summary> /// <returns> /// A <see cref="global::System.Threading.Tasks.Task" /> that will be complete when handling of the method is completed. /// </returns> protected async global::System.Threading.Tasks.Task ProcessRecordAsync() { using( NoSynchronizationContext ) { await ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } await ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName); if (null != HttpPipelinePrepend) { Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); } if (null != HttpPipelineAppend) { Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); } // get the client instance try { await ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } await this.Client.PrivateLinkScopesCreateOrUpdate(ResourceGroupName, SubscriptionId, ScopeName, Parameter, onOk, onCreated, onDefault, this, Pipeline); await ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } } catch (Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.UndeclaredResponseException urexception) { WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { ResourceGroupName=ResourceGroupName,SubscriptionId=SubscriptionId,ScopeName=ScopeName,body=Parameter}) { ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } }); } finally { await ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.Events.CmdletProcessRecordAsyncEnd); } } } /// <summary>Interrupts currently running code within the command.</summary> protected override void StopProcessing() { ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.IEventListener)this).Cancel(); base.StopProcessing(); } /// <summary>a delegate that is called when the remote service returns 201 (Created).</summary> /// <param name="responseMessage">the raw response message as an global::System.Net.Http.HttpResponseMessage.</param> /// <param name="response">the body result as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Models.Api20210520.IHybridComputePrivateLinkScope" /// /> from the remote call</param> /// <returns> /// A <see cref="global::System.Threading.Tasks.Task" /> that will be complete when handling of the method is completed. /// </returns> private async global::System.Threading.Tasks.Task onCreated(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task<Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Models.Api20210520.IHybridComputePrivateLinkScope> response) { using( NoSynchronizationContext ) { var _returnNow = global::System.Threading.Tasks.Task<bool>.FromResult(false); overrideOnCreated(responseMessage, response, ref _returnNow); // if overrideOnCreated has returned true, then return right away. if ((null != _returnNow && await _returnNow)) { return ; } // onCreated - response for 201 / application/json // (await response) // should be Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Models.Api20210520.IHybridComputePrivateLinkScope WriteObject((await response)); } } /// <summary> /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). /// </summary> /// <param name="responseMessage">the raw response message as an global::System.Net.Http.HttpResponseMessage.</param> /// <param name="response">the body result as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Models.Api20.IErrorResponse" /// /> from the remote call</param> /// <returns> /// A <see cref="global::System.Threading.Tasks.Task" /> that will be complete when handling of the method is completed. /// </returns> private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task<Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Models.Api20.IErrorResponse> response) { using( NoSynchronizationContext ) { var _returnNow = global::System.Threading.Tasks.Task<bool>.FromResult(false); overrideOnDefault(responseMessage, response, ref _returnNow); // if overrideOnDefault has returned true, then return right away. if ((null != _returnNow && await _returnNow)) { return ; } // Error Response : default var code = (await response)?.Code; var message = (await response)?.Message; if ((null == code || null == message)) { // Unrecognized Response. Create an error record based on what we have. var ex = new Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.RestException<Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Models.Api20.IErrorResponse>(responseMessage, await response); WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { ResourceGroupName=ResourceGroupName, SubscriptionId=SubscriptionId, ScopeName=ScopeName, body=Parameter }) { ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } }); } else { WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { ResourceGroupName=ResourceGroupName, SubscriptionId=SubscriptionId, ScopeName=ScopeName, body=Parameter }) { ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } }); } } } /// <summary>a delegate that is called when the remote service returns 200 (OK).</summary> /// <param name="responseMessage">the raw response message as an global::System.Net.Http.HttpResponseMessage.</param> /// <param name="response">the body result as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Models.Api20210520.IHybridComputePrivateLinkScope" /// /> from the remote call</param> /// <returns> /// A <see cref="global::System.Threading.Tasks.Task" /> that will be complete when handling of the method is completed. /// </returns> private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task<Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Models.Api20210520.IHybridComputePrivateLinkScope> response) { using( NoSynchronizationContext ) { var _returnNow = global::System.Threading.Tasks.Task<bool>.FromResult(false); overrideOnOk(responseMessage, response, ref _returnNow); // if overrideOnOk has returned true, then return right away. if ((null != _returnNow && await _returnNow)) { return ; } // onOk - response for 200 / application/json // (await response) // should be Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Models.Api20210520.IHybridComputePrivateLinkScope WriteObject((await response)); } } } }
75.89011
495
0.68329
[ "MIT" ]
Agazoth/azure-powershell
src/ConnectedMachine/generated/cmdlets/NewAzConnectedPrivateLinkScope_Create.cs
34,076
C#