content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
// Copyright (c) 2021 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; using Newtonsoft.Json.Serialization; using System; using System.Collections.Generic; using System.Text.Json.Serialization; using Telegram.BotAPI.AvailableTypes; namespace Telegram.BotAPI.Games { /// <summary>This object represents a game. Use BotFather to create and edit games, their short names will act as unique identifiers.</summary> [JsonObject(MemberSerialization = MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))] public sealed class Game : IEquatable<Game> { /// <summary>Title of the game.</summary> [JsonPropertyName(PropertyNames.Title)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public string Title { get; set; } /// <summary>Description of the game.</summary> [JsonPropertyName(PropertyNames.Description)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public string Description { get; set; } /// <summary>Photo that will be displayed in the game message in chats.</summary> [JsonPropertyName(PropertyNames.Photo)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public PhotoSize[] Photo { get; set; } /// <summary>Optional. Brief description of the game or high scores included in the game message. Can be automatically edited to include current high scores for the game when the bot calls setGameScore, or manually edited using editMessageText. 0-4096 characters.</summary> [JsonPropertyName(PropertyNames.Text)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public string Text { get; set; } /// <summary>Optional. Special entities that appear in text, such as usernames, URLs, bot commands, etc.</summary> [JsonPropertyName(PropertyNames.TextEntities)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public MessageEntity[] TextEntities { get; set; } /// <summary>Optional. Animation that will be displayed in the game message in chats. Upload via BotFather.</summary> [JsonPropertyName(PropertyNames.Animation)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public Animation Animation { get; set; } #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member public override bool Equals(object obj) { return Equals(obj as Game); } public bool Equals(Game other) { return other != null && Title == other.Title && Description == other.Description && EqualityComparer<PhotoSize[]>.Default.Equals(Photo, other.Photo) && Text == other.Text && EqualityComparer<MessageEntity[]>.Default.Equals(TextEntities, other.TextEntities) && EqualityComparer<Animation>.Default.Equals(Animation, other.Animation); } public override int GetHashCode() { int hashCode = -817216167; hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(Title); hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(Description); hashCode = hashCode * -1521134295 + EqualityComparer<PhotoSize[]>.Default.GetHashCode(Photo); hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(Text); hashCode = hashCode * -1521134295 + EqualityComparer<MessageEntity[]>.Default.GetHashCode(TextEntities); hashCode = hashCode * -1521134295 + EqualityComparer<Animation>.Default.GetHashCode(Animation); return hashCode; } public static bool operator ==(Game left, Game right) { return EqualityComparer<Game>.Default.Equals(left, right); } public static bool operator !=(Game left, Game right) { return !(left == right); } #pragma warning restore CS1591 // Missing XML comment for publicly visible type or member } }
51.771084
281
0.681638
[ "MIT" ]
Eptagone/Telegram.BotAPI
src/Telegram.BotAPI/Games/Game.cs
4,297
C#
using System; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; using Moq; using NAsync; using NUnit.Framework; #pragma warning disable 162 namespace NAsyncTests { [TestFixture] [SuppressMessage("ReSharper", "InvokeAsExtensionMethod")] [SuppressMessage("ReSharper", "RedundantCast")] public class ThenTaskTest { #region Util public class Syncer { private int mCounter; public void Step(int step) { while (true) { int expectedPreviousStep = step - 1; int previousStep = Interlocked.CompareExchange(ref mCounter, step, expectedPreviousStep); if (expectedPreviousStep == previousStep) return; Thread.Sleep(10); } } } public class Ex1 : Exception { } public class Ex2 : Exception { } public interface IAfter { void NextAction(); void NextActionWithInput(int resultOfFirst); string NextFunction(); string NextFunctionWithInput(int resultOfFirst); void CatchExceptionHandler(Exception e); int CatchExceptionHandlerWithOutput(Exception e); } #endregion #region Then: Task then Task Action [Test] public void Task_Then_TaskAction__NullTask() { Task task = SimpleTaskFactory.Run(() => { /*do nothing*/}) .Then(() => (Task)null); try { task.Wait(); } catch (AggregateException e) { Assert.IsInstanceOf<ArgumentNullException>(e.InnerException); } } [Test] public void Task_Then_TaskAction__Normal() { var mock = new Mock<IAfter>(); Task task = SimpleTaskFactory.Run(() => { /*do nothing*/}) .Then(() => SimpleTaskFactory.Run(() => mock.Object.NextAction())); task.Wait(); mock.Verify(then => then.NextAction(), Times.Once); } [Test] public void Task_Then_TaskAction__ExceptionInFirst() { var mock = new Mock<IAfter>(); var thrownException = new Exception(); Task task = SimpleTaskFactory.Run(() => { throw thrownException; }) .Then(() => SimpleTaskFactory.Run(() => mock.Object.NextAction())); try { task.Wait(); Assert.Fail("task must bubble up the exception"); } catch (AggregateException e) { Assert.AreEqual(thrownException, e.InnerException); mock.Verify(then => then.NextAction(), Times.Never); Assert.Pass(); } } [Test] public void Task_Then_TaskAction__ExceptionInSecond() { var thrownException = new Exception(); Task task = SimpleTaskFactory.Run(() => { }) .Then(() => SimpleTaskFactory.Run(() => { throw thrownException; } )); try { task.Wait(); Assert.Fail("task must bubble up the exception"); } catch (AggregateException e) { Assert.AreEqual(thrownException, e.InnerException); Assert.Pass(); } } [Test] public void Task_Then_Action__Cancelled() { var source = new CancellationTokenSource(); CancellationToken token = source.Token; var syncer = new Syncer(); var mock = new Mock<IAfter>(); Task task = SimpleTaskFactory.Run(() => { syncer.Step(1); syncer.Step(4); token.ThrowIfCancellationRequested(); }, token) .Then(() => SimpleTaskFactory.Run(() => mock.Object.NextAction(), token), token); syncer.Step(2); source.Cancel(); syncer.Step(3); try { // ReSharper disable once MethodSupportsCancellation task.Wait(); Assert.Fail("task must bubble up the TaskCanceledException"); } catch (AggregateException e) { Assert.IsInstanceOf<TaskCanceledException>(e.InnerException); mock.Verify(then => then.NextAction(), Times.Never); Assert.Pass(); } } [Test] public void Task_Then_Action__SecondCancelled() { var source = new CancellationTokenSource(); CancellationToken token = source.Token; var syncer = new Syncer(); var mock = new Mock<IAfter>(); Task task = SimpleTaskFactory.Run(() => { // do nothing }, token) .Then(() => SimpleTaskFactory.Run(() => { syncer.Step(1); syncer.Step(4); token.ThrowIfCancellationRequested(); mock.Object.NextAction(); }, token), token); syncer.Step(2); source.Cancel(); syncer.Step(3); try { // ReSharper disable once MethodSupportsCancellation task.Wait(); Assert.Fail("task must bubble up the TaskCanceledException"); } catch (AggregateException e) { Assert.IsInstanceOf<OperationCanceledException>(e.InnerException); mock.Verify(then => then.NextAction(), Times.Never); Assert.Pass(); } } #endregion #region Then: Task then Task FuncT2 [Test] public void Task_Then_TaskFuncT2__NullTask() { Task task = SimpleTaskFactory.Run(() => { /*do nothing*/}) .Then(() => (Task<string>)null); try { task.Wait(); } catch (AggregateException e) { Assert.IsInstanceOf<ArgumentNullException>(e.InnerException); } } [Test] public void Task_Then_TaskFuncT2__Normal() { var mock = new Mock<IAfter>(); Task<string> task = SimpleTaskFactory.Run(() => { }) .Then(() => SimpleTaskFactory.Run(() => mock.Object.NextFunction())); task.Wait(); mock.Verify(then => then.NextFunction(), Times.Once); } [Test] public void Task_Then_TaskFuncT2__Normal_ResultBubbling() { Task<string> task = SimpleTaskFactory.Run(() => { }) .Then(() => SimpleTaskFactory.Run(() => "Coucou")); task.Wait(); Assert.AreEqual("Coucou", task.Result); } [Test] public void Task_Then_TaskFuncT2__ExceptionInFirst() { var mock = new Mock<IAfter>(); var thrownException = new Exception(); Task task = SimpleTaskFactory .Run(() => { throw thrownException; }) .Then( () => SimpleTaskFactory.Run(() => mock.Object.NextFunction())); try { task.Wait(); Assert.Fail("task must bubble up the exception"); } catch (AggregateException e) { Assert.AreEqual(thrownException, e.InnerException); mock.Verify(then => then.NextFunction(), Times.Never); Assert.Pass(); } } [Test] public void Task_Then_TaskFuncT2__ExceptionInSecond() { var thrownException = new Exception(); Task task = SimpleTaskFactory.Run(() => { }) .Then(() => SimpleTaskFactory.Run(() => { throw thrownException; return default(string); })); try { task.Wait(); Assert.Fail("task must bubble up the exception"); } catch (AggregateException e) { Assert.AreEqual(thrownException, e.InnerException); Assert.Pass(); } } [Test] public void Task_Then_TaskFuncT2__ExceptionInFatory() { var thrownException = new Exception(); Task task = SimpleTaskFactory.Run(() => { }) .Then(() => { throw thrownException; // factory fails return SimpleTaskFactory.Run(() => { throw thrownException; return default(string); }); }); try { task.Wait(); Assert.Fail("task must bubble up the exception"); } catch (AggregateException e) { Assert.AreEqual(thrownException, e.InnerException); Assert.Pass(); } } [Test] public void Task_Then_FuncT2__Cancelled() { var source = new CancellationTokenSource(); CancellationToken token = source.Token; var syncer = new Syncer(); var mock = new Mock<IAfter>(); Task task = SimpleTaskFactory.Run(() => { syncer.Step(1); syncer.Step(4); token.ThrowIfCancellationRequested(); }, token) .Then(() => SimpleTaskFactory.Run(() => mock.Object.NextFunction(), token), token); syncer.Step(2); source.Cancel(); syncer.Step(3); try { // ReSharper disable once MethodSupportsCancellation task.Wait(); Assert.Fail("task must bubble up the TaskCanceledException"); } catch (AggregateException e) { Assert.IsInstanceOf<TaskCanceledException>(e.InnerException); mock.Verify(then => then.NextFunction(), Times.Never); Assert.Pass(); } } [Test] public void Task_Then_FuncT2__SecondCancelled() { var source = new CancellationTokenSource(); CancellationToken token = source.Token; var syncer = new Syncer(); var mock = new Mock<IAfter>(); Task task = SimpleTaskFactory.Run(() => { // do nothing }, token) .Then(() => SimpleTaskFactory.Run(() => { syncer.Step(1); syncer.Step(4); token.ThrowIfCancellationRequested(); return mock.Object.NextFunction(); }, token), token); syncer.Step(2); source.Cancel(); syncer.Step(3); try { // ReSharper disable once MethodSupportsCancellation task.Wait(); Assert.Fail("task must bubble up the TaskCanceledException"); } catch (AggregateException e) { Assert.IsInstanceOf<OperationCanceledException>(e.InnerException); mock.Verify(then => then.NextFunction(), Times.Never); Assert.Pass(); } } #endregion #region Then: TaskT1 then Task ActionT1 [Test] public void TaskT1_Then_TaskActionT1__NullTask() { Task task = SimpleTaskFactory.Run(() => 12) .Then(result => (Task)null); try { task.Wait(); } catch (AggregateException e) { Assert.IsInstanceOf<ArgumentNullException>(e.InnerException); } } [Test] public void TaskT1_Then_TaskActionT1__Normal() { var mock = new Mock<IAfter>(); Task task = SimpleTaskFactory.Run(() => 12) .Then(result => SimpleTaskFactory.Run(() => mock.Object.NextActionWithInput(result))); task.Wait(); mock.Verify(then => then.NextActionWithInput(12), Times.Once); } [Test] public void TaskT1_Then_TaskActionT1__ExceptionInFirst() { var mock = new Mock<IAfter>(); var thrownException = new Exception(); Task task = SimpleTaskFactory .Run(() => { throw thrownException; return 12; }) .Then(result => SimpleTaskFactory.Run(() => mock.Object.NextActionWithInput(result))); try { task.Wait(); Assert.Fail("task must bubble up the exception"); } catch (AggregateException e) { Assert.AreEqual(thrownException, e.InnerException); mock.Verify(then => then.NextActionWithInput(It.IsAny<int>()), Times.Never); Assert.Pass(); } } [Test] public void TaskT1_Then_TaskActionT1__ExceptionInSecond() { var thrownException = new Exception(); Task task = SimpleTaskFactory .Run(() => 12 ) .Then(result => SimpleTaskFactory.Run(() => { throw thrownException; })); try { task.Wait(); Assert.Fail("task must bubble up the exception"); } catch (AggregateException e) { Assert.AreEqual(thrownException, e.InnerException); Assert.Pass(); } } [Test] public void TaskT1_Then_TaskActionT1__ExceptionInFatory() { var thrownException = new Exception(); Task task = SimpleTaskFactory.Run(() => 12) .Then(result => { throw thrownException; // factory fails return SimpleTaskFactory.Run(() => { throw thrownException; return default(string); }); }); try { task.Wait(); Assert.Fail("task must bubble up the exception"); } catch (AggregateException e) { Assert.AreEqual(thrownException, e.InnerException); Assert.Pass(); } } [Test] public void Task_Then_ActionT1__Cancelled() { var source = new CancellationTokenSource(); CancellationToken token = source.Token; var syncer = new Syncer(); var mock = new Mock<IAfter>(); Task task = SimpleTaskFactory.Run(() => { syncer.Step(1); syncer.Step(4); token.ThrowIfCancellationRequested(); return 10; }, token) .Then(result => SimpleTaskFactory.Run(() => mock.Object.NextActionWithInput(result), token), token); syncer.Step(2); source.Cancel(); syncer.Step(3); try { // ReSharper disable once MethodSupportsCancellation task.Wait(); Assert.Fail("task must bubble up the TaskCanceledException"); } catch (AggregateException e) { Assert.IsInstanceOf<TaskCanceledException>(e.InnerException); mock.Verify(then => then.NextActionWithInput(It.IsAny<int>()), Times.Never); Assert.Pass(); } } [Test] public void TaskT1_Then_ActionT1__SecondCancelled() { var source = new CancellationTokenSource(); CancellationToken token = source.Token; var syncer = new Syncer(); var mock = new Mock<IAfter>(); Task task = SimpleTaskFactory.Run(() => 12, token) .Then(result => SimpleTaskFactory.Run(() => { syncer.Step(1); syncer.Step(4); token.ThrowIfCancellationRequested(); mock.Object.NextActionWithInput(result); }, token), token); syncer.Step(2); source.Cancel(); syncer.Step(3); try { // ReSharper disable once MethodSupportsCancellation task.Wait(); Assert.Fail("task must bubble up the TaskCanceledException"); } catch (AggregateException e) { Assert.IsInstanceOf<OperationCanceledException>(e.InnerException); mock.Verify(then => then.NextFunction(), Times.Never); Assert.Pass(); } } #endregion #region Then: TaskT1 then Task FuncT1T2 [Test] public void TaskT1_Then_TaskFuncT1T2__NullTask() { Task task = SimpleTaskFactory.Run(() => 12) .Then(result => (Task<string>)null); try { task.Wait(); } catch (AggregateException e) { Assert.IsInstanceOf<ArgumentNullException>(e.InnerException); } } [Test] public void TaskT1_Then_TaskFuncT1T2__Normal() { var mock = new Mock<IAfter>(); Task task = SimpleTaskFactory.Run(() => 12 ) .Then(result => SimpleTaskFactory.Run(() => mock.Object.NextFunctionWithInput(result))); task.Wait(); mock.Verify(then => then.NextFunctionWithInput(12), Times.Once); } [Test] public void TaskT1_Then_TaskFuncT1T2__ExceptionInFirst() { var mock = new Mock<IAfter>(); var thrownException = new Exception(); Task task = SimpleTaskFactory .Run(() => { throw thrownException; return 12; }) .Then(result => SimpleTaskFactory.Run(() => mock.Object.NextFunctionWithInput(result))); try { task.Wait(); Assert.Fail("task must bubble up the exception"); } catch (AggregateException e) { Assert.AreEqual(thrownException, e.InnerException); mock.Verify(then => then.NextFunctionWithInput(It.IsAny<int>()), Times.Never); Assert.Pass(); } } [Test] public void TaskT1_Then_TaskFuncT1T2__ExceptionInSecond() { var thrownException = new Exception(); Task task = SimpleTaskFactory .Run(() => 12 ) .Then(result => SimpleTaskFactory.Run(() => { throw thrownException; return default(string); })); try { task.Wait(); Assert.Fail("task must bubble up the exception"); } catch (AggregateException e) { Assert.AreEqual(thrownException, e.InnerException); Assert.Pass(); } } [Test] public void Task_Then_FuncT1T2__Cancelled() { var source = new CancellationTokenSource(); CancellationToken token = source.Token; var syncer = new Syncer(); var mock = new Mock<IAfter>(); Task task = SimpleTaskFactory.Run(() => { syncer.Step(1); syncer.Step(4); token.ThrowIfCancellationRequested(); return 10; }, token) .Then(result => SimpleTaskFactory.Run(() => mock.Object.NextFunctionWithInput(result), token), token); syncer.Step(2); source.Cancel(); syncer.Step(3); try { // ReSharper disable once MethodSupportsCancellation task.Wait(); Assert.Fail("task must bubble up the TaskCanceledException"); } catch (AggregateException e) { Assert.IsInstanceOf<TaskCanceledException>(e.InnerException); mock.Verify(then => then.NextFunctionWithInput(It.IsAny<int>()), Times.Never); Assert.Pass(); } } [Test] public void TaskT1_Then_FuncT1T2__SecondCancelled() { var source = new CancellationTokenSource(); CancellationToken token = source.Token; var syncer = new Syncer(); var mock = new Mock<IAfter>(); Task task = SimpleTaskFactory.Run(() => 12, token) .Then(result => SimpleTaskFactory.Run(() => { syncer.Step(1); syncer.Step(4); token.ThrowIfCancellationRequested(); return mock.Object.NextFunctionWithInput(result); }, token), token); syncer.Step(2); source.Cancel(); syncer.Step(3); try { // ReSharper disable once MethodSupportsCancellation task.Wait(); Assert.Fail("task must bubble up the TaskCanceledException"); } catch (AggregateException e) { Assert.IsInstanceOf<OperationCanceledException>(e.InnerException); mock.Verify(then => then.NextFunctionWithInput(It.IsAny<int>()), Times.Never); Assert.Pass(); } } #endregion } }
30.155673
118
0.472789
[ "Apache-2.0" ]
jeromerg/NAsync
src/NAsyncTests/ThenTaskTest.cs
22,860
C#
namespace Elreg.Controls.ProgressColumns { public class DataGridViewVertProgressColumn : DataGridViewProgressColumn { public DataGridViewVertProgressColumn() { CellTemplate = new DataGridViewVertProgressCell(); } } }
23.166667
77
0.658273
[ "MIT" ]
Heinzman/DigiRcMan
VisualStudio/Sources/Controls/ProgressColumns/DataGridViewVertProgressColumn.cs
280
C#
using System; using System.ComponentModel.DataAnnotations.Schema; namespace Reface.NPI.DynamicProxy.AppOfSqlite.Entities { [Table("T_USER")] public class User { public string Id { get; set; } public string Name { get; set; } public string LoginName { get; set; } public string Password { get; set; } public static User New() { return new User() { Password = nameof(Password), Id = Guid.NewGuid().ToString(), LoginName = nameof(LoginName), Name = nameof(Name) }; } } }
24.730769
54
0.528771
[ "MIT" ]
ShimizuShiori/Reface.NPI.DynamicProxy
src/Reface.NPI.DynamicProxy.AppOfSqlite/Entities/User.cs
645
C#
using System; using Source.Components; using Source.Events; using UnityEngine; namespace Source.Controllers { public class BulletDestroyController : MonoBehaviour { private void Awake() { EventPool.OnBulletHit.AddListener(OnBulletHit); } private void OnBulletHit(BulletComponent arg0) { Destroy(arg0.gameObject); } } }
20.25
59
0.637037
[ "MIT" ]
DavidNightinga1e/Asteroids_1979
Assets/Source/Controllers/BulletDestroyController.cs
407
C#
// // Unit tests for AvoidUnnecessaryOverridesRule // // Authors: // N Lum <nol888@gmail.com // // Copyright (C) 2010 N Lum // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Security.Permissions; using Gendarme.Rules.Performance; using NUnit.Framework; using Test.Rules.Definitions; using Test.Rules.Fixtures; using Test.Rules.Helpers; namespace Tests.Rules.Performance { [TestFixture] public class AvoidUnnecessaryOverridesTest : MethodRuleTestFixture<AvoidUnnecessaryOverridesRule> { private class TestBaseClass { ~TestBaseClass () { Console.WriteLine ("the end"); } public string NonVirtualDoSomething (int i) { return i.ToString (); } public virtual string DoSomething (string s) { return s; } public virtual string DoSomething () { return ":D"; } public virtual void DoNothing () { } } abstract class AbstractTestClass : TestBaseClass { ~AbstractTestClass () { Console.WriteLine ("abstract"); } public abstract void DoSomething (int i); public override void DoNothing () { base.DoNothing (); } } private class TestClassGood : TestBaseClass { public override string DoSomething (string s) { return base.DoSomething (); } [STAThread] public override string DoSomething () { return base.DoSomething (); } [FileIOPermission (SecurityAction.Demand)] public override string ToString () { return base.ToString (); } public override bool Equals (object obj) { if (obj == null) return false; else return base.Equals (obj); } } private class TestClassAlsoGood : ApplicationException { public override bool Equals (object obj) { if (obj.GetType () != typeof (TestClassAlsoGood)) return false; return base.Equals (obj); } } private class TestClassBad : TestBaseClass { public override string ToString () { return base.ToString (); } public override string DoSomething (string s) { return base.DoSomething (s); } public override string DoSomething () { return base.DoSomething (); } } private class TestClassAlsoBad : ApplicationException { public override Exception GetBaseException () { return base.GetBaseException (); } } [Test] public void Good () { AssertRuleSuccess<TestClassGood> ("DoSomething", new Type [] { typeof (string) }); AssertRuleSuccess<TestClassGood> ("DoSomething", Type.EmptyTypes); AssertRuleSuccess<TestClassGood> ("Equals"); AssertRuleSuccess<TestClassGood> ("ToString"); AssertRuleSuccess<TestClassAlsoGood> ("Equals"); } [Test] public void Bad () { AssertRuleFailure<TestClassBad> ("ToString", 1); AssertRuleFailure<TestClassBad> ("DoSomething", new Type [] { typeof (string) }, 1); AssertRuleFailure<TestClassBad> ("DoSomething", Type.EmptyTypes, 1); AssertRuleFailure<TestClassAlsoBad> ("GetBaseException", 1); AssertRuleFailure<AbstractTestClass> ("DoNothing", 1); } [Test] public void DoesNotApply () { AssertRuleDoesNotApply<TestBaseClass> ("NonVirtualDoSomething"); AssertRuleDoesNotApply<TestClassGood> (".ctor"); AssertRuleDoesNotApply<TestClassBad> (".ctor"); AssertRuleDoesNotApply<AbstractTestClass> ("DoSomething"); } public class BaseClass { public virtual string DoSomething (int i) { return i.ToString(); } } public class GoodClass : BaseClass { public string Property { get; set; } public override string DoSomething (int i) { Property = base.DoSomething (i); return Property; } } [Test] public void Bug663492 () { AssertRuleSuccess<GoodClass> ("DoSomething"); } } }
24.341837
100
0.69629
[ "MIT" ]
JAD-SVK/Gendarme
rules/Gendarme.Rules.Performance/Test/AvoidUnnecessaryOverridesTest.cs
4,771
C#
#region License /* * All content copyright Terracotta, Inc., unless otherwise indicated. 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. * */ #endregion using System; namespace Quartz.Impl.Triggers { /// <summary> /// A concrete <see cref="ITrigger" /> that is used to fire a <see cref="IJobDetail" /> /// based upon repeating calendar time intervals. /// </summary> /// <remarks> /// The trigger will fire every N (see <see cref="RepeatInterval" />) units of calendar time /// (see <see cref="RepeatIntervalUnit" />) as specified in the trigger's definition. /// This trigger can achieve schedules that are not possible with <see cref="ISimpleTrigger" /> (e.g /// because months are not a fixed number of seconds) or <see cref="ICronTrigger" /> (e.g. because /// "every 5 months" is not an even divisor of 12). /// <para> /// If you use an interval unit of <see cref="IntervalUnit.Month" /> then care should be taken when setting /// a <see cref="StartTimeUtc" /> value that is on a day near the end of the month. For example, /// if you choose a start time that occurs on January 31st, and have a trigger with unit /// <see cref="IntervalUnit.Month" /> and interval 1, then the next fire time will be February 28th, /// and the next time after that will be March 28th - and essentially each subsequent firing will /// occur on the 28th of the month, even if a 31st day exists. If you want a trigger that always /// fires on the last day of the month - regardless of the number of days in the month, /// you should use <see cref="ICronTrigger" />. /// </para> /// </remarks> /// <see cref="ITrigger" /> /// <see cref="ICronTrigger" /> /// <see cref="ISimpleTrigger" /> /// <see cref="NthIncludedDayTrigger" /> /// <since>2.0</since> /// <author>James House</author> /// <author>Marko Lahma (.NET)</author> [Serializable] public class CalendarIntervalTriggerImpl : AbstractTrigger, ICalendarIntervalTrigger { private static readonly int YearToGiveupSchedulingAt = DateTime.Now.AddYears(100).Year; private DateTimeOffset startTime; private DateTimeOffset? endTime; private DateTimeOffset? nextFireTimeUtc; private DateTimeOffset? previousFireTimeUtc; private int repeatInterval; private IntervalUnit repeatIntervalUnit = IntervalUnit.Day; private TimeZoneInfo timeZone; private bool preserveHourOfDayAcrossDaylightSavings; // false is backward-compatible with behavior private bool skipDayIfHourDoesNotExist = false; private int timesTriggered; private bool complete = false; /// <summary> /// Create a <see cref="ICalendarIntervalTrigger" /> with no settings. /// </summary> public CalendarIntervalTriggerImpl() { } /// <summary> /// Create a <see cref="CalendarIntervalTriggerImpl" /> that will occur immediately, and /// repeat at the the given interval. /// </summary> /// <param name="name">Name for the trigger instance.</param> /// <param name="intervalUnit">The repeat interval unit (minutes, days, months, etc).</param> /// <param name="repeatInterval">The number of milliseconds to pause between the repeat firing.</param> public CalendarIntervalTriggerImpl(string name, IntervalUnit intervalUnit, int repeatInterval) : this(name, null, intervalUnit, repeatInterval) { } /// <summary> /// Create a <see cref="ICalendarIntervalTrigger" /> that will occur immediately, and /// repeat at the the given interval /// </summary> /// <param name="name">Name for the trigger instance.</param> /// <param name="group">Group for the trigger instance.</param> /// <param name="intervalUnit">The repeat interval unit (minutes, days, months, etc).</param> /// <param name="repeatInterval">The number of milliseconds to pause between the repeat firing.</param> public CalendarIntervalTriggerImpl(string name, string group, IntervalUnit intervalUnit, int repeatInterval) : this(name, group, SystemTime.UtcNow(), null, intervalUnit, repeatInterval) { } /// <summary> /// Create a <see cref="ICalendarIntervalTrigger" /> that will occur at the given time, /// and repeat at the the given interval until the given end time. /// </summary> /// <param name="name">Name for the trigger instance.</param> /// <param name="startTimeUtc">A <see cref="DateTimeOffset" /> set to the time for the <see cref="ITrigger" /> to fire.</param> /// <param name="endTimeUtc">A <see cref="DateTimeOffset" /> set to the time for the <see cref="ITrigger" /> to quit repeat firing.</param> /// <param name="intervalUnit">The repeat interval unit (minutes, days, months, etc).</param> /// <param name="repeatInterval">The number of milliseconds to pause between the repeat firing.</param> public CalendarIntervalTriggerImpl(string name, DateTimeOffset startTimeUtc, DateTimeOffset? endTimeUtc, IntervalUnit intervalUnit, int repeatInterval) : this(name, null, startTimeUtc, endTimeUtc, intervalUnit, repeatInterval) { } /// <summary> /// Create a <see cref="ICalendarIntervalTrigger" /> that will occur at the given time, /// and repeat at the the given interval until the given end time. /// </summary> /// <param name="name">Name for the trigger instance.</param> /// <param name="group">Group for the trigger instance.</param> /// <param name="startTimeUtc">A <see cref="DateTimeOffset" /> set to the time for the <see cref="ITrigger" /> to fire.</param> /// <param name="endTimeUtc">A <see cref="DateTimeOffset" /> set to the time for the <see cref="ITrigger" /> to quit repeat firing.</param> /// <param name="intervalUnit">The repeat interval unit (minutes, days, months, etc).</param> /// <param name="repeatInterval">The number of milliseconds to pause between the repeat firing.</param> public CalendarIntervalTriggerImpl(string name, string group, DateTimeOffset startTimeUtc, DateTimeOffset? endTimeUtc, IntervalUnit intervalUnit, int repeatInterval) : base(name, group) { StartTimeUtc = startTimeUtc; EndTimeUtc = endTimeUtc; RepeatIntervalUnit = (intervalUnit); RepeatInterval = (repeatInterval); } /// <summary> /// Create a <see cref="ICalendarIntervalTrigger" /> that will occur at the given time, /// and repeat at the the given interval until the given end time. /// </summary> /// <param name="name">Name for the trigger instance.</param> /// <param name="group">Group for the trigger instance.</param> /// <param name="jobName">Name of the associated job.</param> /// <param name="jobGroup">Group of the associated job.</param> /// <param name="startTimeUtc">A <see cref="DateTimeOffset" /> set to the time for the <see cref="ITrigger" /> to fire.</param> /// <param name="endTimeUtc">A <see cref="DateTimeOffset" /> set to the time for the <see cref="ITrigger" /> to quit repeat firing.</param> /// <param name="intervalUnit">The repeat interval unit (minutes, days, months, etc).</param> /// <param name="repeatInterval">The number of milliseconds to pause between the repeat firing.</param> public CalendarIntervalTriggerImpl(string name, string group, string jobName, string jobGroup, DateTimeOffset startTimeUtc, DateTimeOffset? endTimeUtc, IntervalUnit intervalUnit, int repeatInterval) : base(name, group, jobName, jobGroup) { StartTimeUtc = startTimeUtc; EndTimeUtc = endTimeUtc; RepeatIntervalUnit = intervalUnit; RepeatInterval = repeatInterval; } /// <summary> /// Get the time at which the <see cref="CalendarIntervalTriggerImpl" /> should occur. /// </summary> public override DateTimeOffset StartTimeUtc { get { if (startTime == DateTimeOffset.MinValue) { startTime = SystemTime.UtcNow(); } return startTime; } set { if (value == DateTimeOffset.MinValue) { throw new ArgumentException("Start time cannot be DateTimeOffset.MinValue"); } DateTimeOffset? eTime = EndTimeUtc; if (eTime != null && eTime < value) { throw new ArgumentException("End time cannot be before start time"); } startTime = value; } } /// <summary> /// Tells whether this Trigger instance can handle events /// in millisecond precision. /// </summary> public override bool HasMillisecondPrecision { get { return true; } } /// <summary> /// Get the time at which the <see cref="ICalendarIntervalTrigger" /> should quit /// repeating. /// </summary> public override DateTimeOffset? EndTimeUtc { get { return endTime; } set { DateTimeOffset sTime = StartTimeUtc; if (value != null && sTime > value) { throw new ArgumentException("End time cannot be before start time"); } endTime = value; } } /// <summary> /// Get or set the interval unit - the time unit on with the interval applies. /// </summary> public IntervalUnit RepeatIntervalUnit { get { return repeatIntervalUnit; } set { this.repeatIntervalUnit = value; } } /// <summary> /// Get the the time interval that will be added to the <see cref="ICalendarIntervalTrigger" />'s /// fire time (in the set repeat interval unit) in order to calculate the time of the /// next trigger repeat. /// </summary> public int RepeatInterval { get { return repeatInterval; } set { if (value < 0) { throw new ArgumentException("Repeat interval must be >= 1"); } repeatInterval = value; } } public TimeZoneInfo TimeZone { get { if (timeZone == null) { timeZone = TimeZoneInfo.Local; } return timeZone; } set { timeZone = value; } } ///<summary> /// If intervals are a day or greater, this property (set to true) will /// cause the firing of the trigger to always occur at the same time of day, /// (the time of day of the startTime) regardless of daylight saving time /// transitions. Default value is false. /// </summary> /// <remarks> /// <para> /// For example, without the property set, your trigger may have a start /// time of 9:00 am on March 1st, and a repeat interval of 2 days. But /// after the daylight saving transition occurs, the trigger may start /// firing at 8:00 am every other day. /// </para> /// <para> /// If however, the time of day does not exist on a given day to fire /// (e.g. 2:00 am in the United States on the days of daylight saving /// transition), the trigger will go ahead and fire one hour off on /// that day, and then resume the normal hour on other days. If /// you wish for the trigger to never fire at the "wrong" hour, then /// you should set the property skipDayIfHourDoesNotExist. /// </para> ///</remarks> /// <seealso cref="ICalendarIntervalTrigger.SkipDayIfHourDoesNotExist"/> /// <seealso cref="ICalendarIntervalTrigger.TimeZone"/> /// <seealso cref="TriggerBuilder.StartAt"/> public bool PreserveHourOfDayAcrossDaylightSavings { get { return preserveHourOfDayAcrossDaylightSavings; } set { preserveHourOfDayAcrossDaylightSavings = value; } } /// <summary> /// If intervals are a day or greater, and /// preserveHourOfDayAcrossDaylightSavings property is set to true, and the /// hour of the day does not exist on a given day for which the trigger /// would fire, the day will be skipped and the trigger advanced a second /// interval if this property is set to true. Defaults to false. /// </summary> /// <remarks> /// <b>CAUTION!</b> If you enable this property, and your hour of day happens /// to be that of daylight savings transition (e.g. 2:00 am in the United /// States) and the trigger's interval would have had the trigger fire on /// that day, then you may actually completely miss a firing on the day of /// transition if that hour of day does not exist on that day! In such a /// case the next fire time of the trigger will be computed as double (if /// the interval is 2 days, then a span of 4 days between firings will /// occur). /// </remarks> /// <seealso cref="ICalendarIntervalTrigger.PreserveHourOfDayAcrossDaylightSavings"/> public bool SkipDayIfHourDoesNotExist { get { return skipDayIfHourDoesNotExist; } set { skipDayIfHourDoesNotExist = value; } } /// <summary> /// Get the number of times the <see cref="ICalendarIntervalTrigger" /> has already fired. /// </summary> public int TimesTriggered { get { return timesTriggered; } set { this.timesTriggered = value; } } public TriggerBuilder GetTriggerBuilder() { throw new NotImplementedException(); } /// <summary> /// Validates the misfire instruction. /// </summary> /// <param name="misfireInstruction">The misfire instruction.</param> /// <returns></returns> protected override bool ValidateMisfireInstruction(int misfireInstruction) { if (misfireInstruction < Quartz.MisfireInstruction.IgnoreMisfirePolicy) { return false; } if (misfireInstruction > Quartz.MisfireInstruction.CalendarIntervalTrigger.DoNothing) { return false; } return true; } /// <summary> /// Updates the <see cref="ICalendarIntervalTrigger" />'s state based on the /// MisfireInstruction.XXX that was selected when the <see cref="ICalendarIntervalTrigger" /> /// was created. /// </summary> /// <remarks> /// If the misfire instruction is set to <see cref="MisfireInstruction.SmartPolicy" />, /// then the following scheme will be used: /// <ul> /// <li>The instruction will be interpreted as <see cref="MisfireInstruction.CalendarIntervalTrigger.FireOnceNow" /></li> /// </ul> /// </remarks> public override void UpdateAfterMisfire(ICalendar cal) { int instr = MisfireInstruction; if (instr == Quartz.MisfireInstruction.IgnoreMisfirePolicy) { return; } if (instr == Quartz.MisfireInstruction.SmartPolicy) { instr = Quartz.MisfireInstruction.CalendarIntervalTrigger.FireOnceNow; } if (instr == Quartz.MisfireInstruction.CalendarIntervalTrigger.DoNothing) { DateTimeOffset? newFireTime = GetFireTimeAfter(SystemTime.UtcNow()); while (newFireTime != null && cal != null && !cal.IsTimeIncluded(newFireTime.Value)) { newFireTime = GetFireTimeAfter(newFireTime); } SetNextFireTimeUtc(newFireTime); } else if (instr == Quartz.MisfireInstruction.CalendarIntervalTrigger.FireOnceNow) { // fire once now... SetNextFireTimeUtc(SystemTime.UtcNow()); // the new fire time afterward will magically preserve the original // time of day for firing for day/week/month interval triggers, // because of the way getFireTimeAfter() works - in its always restarting // computation from the start time. } } /// <summary> /// This method should not be used by the Quartz client. /// <para> /// Called when the <see cref="IScheduler" /> has decided to 'fire' /// the trigger (Execute the associated <see cref="IJob" />), in order to /// give the <see cref="ITrigger" /> a chance to update itself for its next /// triggering (if any). /// </para> /// </summary> /// <seealso cref="JobExecutionException" /> public override void Triggered(ICalendar calendar) { timesTriggered++; previousFireTimeUtc = nextFireTimeUtc; nextFireTimeUtc = GetFireTimeAfter(nextFireTimeUtc); while (nextFireTimeUtc != null && calendar != null && !calendar.IsTimeIncluded(nextFireTimeUtc.Value)) { nextFireTimeUtc = GetFireTimeAfter(nextFireTimeUtc); if (nextFireTimeUtc == null) { break; } //avoid infinite loop if (nextFireTimeUtc.Value.Year > YearToGiveupSchedulingAt) { nextFireTimeUtc = null; } } } /// <summary> /// This method should not be used by the Quartz client. /// <para> /// The implementation should update the <see cref="ITrigger" />'s state /// based on the given new version of the associated <see cref="ICalendar" /> /// (the state should be updated so that it's next fire time is appropriate /// given the Calendar's new settings). /// </para> /// </summary> /// <param name="calendar"> </param> /// <param name="misfireThreshold"></param> public override void UpdateWithNewCalendar(ICalendar calendar, TimeSpan misfireThreshold) { nextFireTimeUtc = GetFireTimeAfter(previousFireTimeUtc); if (nextFireTimeUtc == null || calendar == null) { return; } DateTimeOffset now = SystemTime.UtcNow(); while (nextFireTimeUtc != null && !calendar.IsTimeIncluded(nextFireTimeUtc.Value)) { nextFireTimeUtc = GetFireTimeAfter(nextFireTimeUtc); if (nextFireTimeUtc == null) { break; } //avoid infinite loop if (nextFireTimeUtc.Value.Year > YearToGiveupSchedulingAt) { nextFireTimeUtc = null; } if (nextFireTimeUtc != null && nextFireTimeUtc < now) { TimeSpan diff = now - nextFireTimeUtc.Value; if (diff >= misfireThreshold) { nextFireTimeUtc = GetFireTimeAfter(nextFireTimeUtc); } } } } /// <summary> /// This method should not be used by the Quartz client. /// </summary> /// <remarks> /// <para> /// Called by the scheduler at the time a <see cref="ITrigger" /> is first /// added to the scheduler, in order to have the <see cref="ITrigger" /> /// compute its first fire time, based on any associated calendar. /// </para> /// /// <para> /// After this method has been called, <see cref="ITrigger.GetNextFireTimeUtc" /> /// should return a valid answer. /// </para> /// </remarks> /// <returns> /// The first time at which the <see cref="ITrigger" /> will be fired /// by the scheduler, which is also the same value <see cref="ITrigger.GetNextFireTimeUtc" /> /// will return (until after the first firing of the <see cref="ITrigger" />). /// </returns> public override DateTimeOffset? ComputeFirstFireTimeUtc(ICalendar calendar) { nextFireTimeUtc = StartTimeUtc; while (nextFireTimeUtc != null && calendar != null && !calendar.IsTimeIncluded(nextFireTimeUtc.Value)) { nextFireTimeUtc = GetFireTimeAfter(nextFireTimeUtc); if (nextFireTimeUtc == null) { break; } //avoid infinite loop if (nextFireTimeUtc.Value.Year > YearToGiveupSchedulingAt) { return null; } } return nextFireTimeUtc; } /// <summary> /// Returns the next time at which the <see cref="ITrigger" /> is scheduled to fire. If /// the trigger will not fire again, <see langword="null" /> will be returned. Note that /// the time returned can possibly be in the past, if the time that was computed /// for the trigger to next fire has already arrived, but the scheduler has not yet /// been able to fire the trigger (which would likely be due to lack of resources /// e.g. threads). /// </summary> ///<remarks> /// The value returned is not guaranteed to be valid until after the <see cref="ITrigger" /> /// has been added to the scheduler. /// </remarks> /// <returns></returns> public override DateTimeOffset? GetNextFireTimeUtc() { return nextFireTimeUtc; } /// <summary> /// Returns the previous time at which the <see cref="ICalendarIntervalTrigger" /> fired. /// If the trigger has not yet fired, <see langword="null" /> will be returned. /// </summary> public override DateTimeOffset? GetPreviousFireTimeUtc() { return previousFireTimeUtc; } public override void SetNextFireTimeUtc(DateTimeOffset? value) { nextFireTimeUtc = value; } public override void SetPreviousFireTimeUtc(DateTimeOffset? previousFireTimeUtc) { this.previousFireTimeUtc = previousFireTimeUtc; } /// <summary> /// Returns the next time at which the <see cref="ICalendarIntervalTrigger" /> will fire, /// after the given time. If the trigger will not fire after the given time, /// <see langword="null" /> will be returned. /// </summary> public override DateTimeOffset? GetFireTimeAfter(DateTimeOffset? afterTime) { return GetFireTimeAfter(afterTime, false); } protected DateTimeOffset? GetFireTimeAfter(DateTimeOffset? afterTime, bool ignoreEndTime) { if (complete) { return null; } // increment afterTme by a second, so that we are // comparing against a time after it! if (afterTime == null) { afterTime = SystemTime.UtcNow().AddSeconds(1); } else { afterTime = afterTime.Value.AddSeconds(1); } DateTimeOffset startMillis = StartTimeUtc; DateTimeOffset afterMillis = afterTime.Value; DateTimeOffset endMillis = (EndTimeUtc == null) ? DateTimeOffset.MaxValue : EndTimeUtc.Value; if (!ignoreEndTime && (endMillis <= afterMillis)) { return null; } if (afterMillis < startMillis) { return startMillis; } long secondsAfterStart = (long) (afterMillis - startMillis).TotalSeconds; DateTimeOffset? time = null; long repeatLong = RepeatInterval; DateTimeOffset sTime = StartTimeUtc; if (timeZone != null) { sTime = TimeZoneInfo.ConvertTime(sTime, timeZone); } if (RepeatIntervalUnit == IntervalUnit.Second) { long jumpCount = secondsAfterStart/repeatLong; if (secondsAfterStart%repeatLong != 0) { jumpCount++; } time = sTime.AddSeconds(RepeatInterval*(int) jumpCount); } else if (RepeatIntervalUnit == IntervalUnit.Minute) { long jumpCount = secondsAfterStart/(repeatLong*60L); if (secondsAfterStart%(repeatLong*60L) != 0) { jumpCount++; } time = sTime.AddMinutes(RepeatInterval*(int) jumpCount); } else if (RepeatIntervalUnit == IntervalUnit.Hour) { long jumpCount = secondsAfterStart/(repeatLong*60L*60L); if (secondsAfterStart%(repeatLong*60L*60L) != 0) { jumpCount++; } time = sTime.AddHours(RepeatInterval*(int) jumpCount); } else { // intervals a day or greater ... int initialHourOfDay = sTime.Hour; if (RepeatIntervalUnit == IntervalUnit.Day) { // Because intervals greater than an hour have an non-fixed number // of seconds in them (due to daylight savings, variation number of // days in each month, leap year, etc. ) we can't jump forward an // exact number of seconds to calculate the fire time as we can // with the second, minute and hour intervals. But, rather // than slowly crawling our way there by iteratively adding the // increment to the start time until we reach the "after time", // we can first make a big leap most of the way there... long jumpCount = secondsAfterStart/(repeatLong*24L*60L*60L); // if we need to make a big jump, jump most of the way there, // but not all the way because in some cases we may over-shoot or under-shoot if (jumpCount > 20) { if (jumpCount < 50) { jumpCount = (long) (jumpCount*0.80); } else if (jumpCount < 500) { jumpCount = (long) (jumpCount*0.90); } else { jumpCount = (long) (jumpCount*0.95); } sTime = sTime.AddDays(RepeatInterval*jumpCount); } // now baby-step the rest of the way there... while (sTime < afterTime && sTime.Year < YearToGiveupSchedulingAt) { sTime = sTime.AddDays(RepeatInterval); } while (DaylightSavingHourShiftOccuredAndAdvanceNeeded(ref sTime, initialHourOfDay) && sTime.Year < YearToGiveupSchedulingAt) { sTime = sTime.AddDays(RepeatInterval); } time = sTime; } else if (RepeatIntervalUnit == IntervalUnit.Week) { // Because intervals greater than an hour have an non-fixed number // of seconds in them (due to daylight savings, variation number of // days in each month, leap year, etc. ) we can't jump forward an // exact number of seconds to calculate the fire time as we can // with the second, minute and hour intervals. But, rather // than slowly crawling our way there by iteratively adding the // increment to the start time until we reach the "after time", // we can first make a big leap most of the way there... long jumpCount = secondsAfterStart/(repeatLong*7L*24L*60L*60L); // if we need to make a big jump, jump most of the way there, // but not all the way because in some cases we may over-shoot or under-shoot if (jumpCount > 20) { if (jumpCount < 50) { jumpCount = (long) (jumpCount*0.80); } else if (jumpCount < 500) { jumpCount = (long) (jumpCount*0.90); } else { jumpCount = (long) (jumpCount*0.95); } sTime = sTime.AddDays((int) (RepeatInterval*jumpCount*7)); } while (sTime < afterTime && sTime.Year < YearToGiveupSchedulingAt) { sTime = sTime.AddDays(RepeatInterval*7); } while (DaylightSavingHourShiftOccuredAndAdvanceNeeded(ref sTime, initialHourOfDay) && sTime.Year < YearToGiveupSchedulingAt) { sTime = sTime.AddDays(RepeatInterval*7); } time = sTime; } else if (RepeatIntervalUnit == IntervalUnit.Month) { // because of the large variation in size of months, and // because months are already large blocks of time, we will // just advance via brute-force iteration. while (sTime < afterTime && sTime.Year < YearToGiveupSchedulingAt) { sTime = sTime.AddMonths(RepeatInterval); } while (DaylightSavingHourShiftOccuredAndAdvanceNeeded(ref sTime, initialHourOfDay) && sTime.Year < YearToGiveupSchedulingAt) { sTime = sTime.AddMonths(RepeatInterval); } time = sTime; } else if (RepeatIntervalUnit == IntervalUnit.Year) { while (sTime < afterTime && sTime.Year < YearToGiveupSchedulingAt) { sTime = sTime.AddYears(RepeatInterval); } while (DaylightSavingHourShiftOccuredAndAdvanceNeeded(ref sTime, initialHourOfDay) && sTime.Year < YearToGiveupSchedulingAt) { sTime = sTime.AddYears(RepeatInterval); } time = sTime; } } // case of interval of a day or greater if (!ignoreEndTime && endMillis <= time) { return null; } return time; } private bool DaylightSavingHourShiftOccuredAndAdvanceNeeded(ref DateTimeOffset newTime, int initialHourOfDay) { if (PreserveHourOfDayAcrossDaylightSavings && newTime.Hour != initialHourOfDay) { newTime = new DateTimeOffset(newTime.Year, newTime.Month, newTime.Day, initialHourOfDay, newTime.Minute, newTime.Second, newTime.Millisecond, newTime.Offset); if (newTime.Hour != initialHourOfDay) { return true; } } return false; } /// <summary> /// Returns the final time at which the <see cref="ICalendarIntervalTrigger" /> will /// fire, if there is no end time set, null will be returned. /// </summary> /// <value></value> /// <remarks>Note that the return time may be in the past.</remarks> public override DateTimeOffset? FinalFireTimeUtc { get { if (complete || EndTimeUtc == null) { return null; } // back up a second from end time DateTimeOffset? fTime = EndTimeUtc.Value.AddSeconds(-1); // find the next fire time after that fTime = GetFireTimeAfter(fTime, true); // the the trigger fires at the end time, that's it! if (fTime == EndTimeUtc) { return fTime; } // otherwise we have to back up one interval from the fire time after the end time DateTimeOffset lTime = fTime.Value; if (RepeatIntervalUnit == IntervalUnit.Second) { lTime = lTime.AddSeconds(-1*RepeatInterval); } else if (RepeatIntervalUnit == IntervalUnit.Minute) { lTime = lTime.AddMinutes(-1*RepeatInterval); } else if (RepeatIntervalUnit == IntervalUnit.Hour) { lTime = lTime.AddHours(-1*RepeatInterval); } else if (RepeatIntervalUnit == IntervalUnit.Day) { lTime = lTime.AddDays(-1*RepeatInterval); } else if (RepeatIntervalUnit == IntervalUnit.Week) { lTime = lTime.AddDays(-1*RepeatInterval*7); } else if (RepeatIntervalUnit == IntervalUnit.Month) { lTime = lTime.AddMonths(-1*RepeatInterval); } else if (RepeatIntervalUnit == IntervalUnit.Year) { lTime = lTime.AddYears(-1*RepeatInterval); } return lTime; } } /// <summary> /// Determines whether or not the <see cref="ICalendarIntervalTrigger" /> will occur /// again. /// </summary> /// <returns></returns> public override bool GetMayFireAgain() { return (GetNextFireTimeUtc() != null); } /// <summary> /// Validates whether the properties of the <see cref="IJobDetail" /> are /// valid for submission into a <see cref="IScheduler" />. /// </summary> public override void Validate() { base.Validate(); if (repeatIntervalUnit == IntervalUnit.Millisecond) { throw new SchedulerException("Invalid repeat IntervalUnit (must be Second, Minute, Hour, Day, Month, Week or Year)."); } if (repeatInterval < 1) { throw new SchedulerException("Repeat Interval cannot be zero."); } } /// <summary> /// Get a <see cref="IScheduleBuilder" /> that is configured to produce a /// schedule identical to this trigger's schedule. /// </summary> /// <remarks> /// </remarks> /// <seealso cref="GetTriggerBuilder()" /> public override IScheduleBuilder GetScheduleBuilder() { CalendarIntervalScheduleBuilder cb = CalendarIntervalScheduleBuilder.Create() .WithInterval(RepeatInterval, RepeatIntervalUnit); switch (MisfireInstruction) { case Quartz.MisfireInstruction.CalendarIntervalTrigger.DoNothing: cb.WithMisfireHandlingInstructionDoNothing(); break; case Quartz.MisfireInstruction.CalendarIntervalTrigger.FireOnceNow: cb.WithMisfireHandlingInstructionFireAndProceed(); break; } return cb; } public override bool HasAdditionalProperties { get { return false; } } } }
42.115427
174
0.544695
[ "Apache-2.0" ]
squanchYourCode/quartz.net-2.0.1
src/Quartz/Impl/Triggers/CalendarIntervalTriggerImpl.cs
37,946
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using MariosSpecialtyProducts.Models; using Microsoft.Extensions.Configuration; using Microsoft.EntityFrameworkCore; namespace MariosSpecialtyProducts { public class Startup { public IConfigurationRoot Configuration { get; set; } public Startup(IHostingEnvironment env) { var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("appsettings.json"); Configuration = builder.Build(); } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { // Add framework services. services.AddMvc(); services.AddEntityFrameworkMySql() .AddDbContext<MariosSpecialtyProductsContext>(options => options .UseMySql(Configuration["ConnectionStrings:DefaultConnection"])); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseBrowserLink(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); app.Run(async (context) => { await context.Response.WriteAsync("Hello World!"); }); } } }
33.225352
116
0.584994
[ "MIT" ]
kailinishihira/Mario-testing
MariosSpecialtyProducts/Startup.cs
2,361
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 frauddetector-2019-11-15.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.FraudDetector.Model { /// <summary> /// This is the response object from the CreateRule operation. /// </summary> public partial class CreateRuleResponse : AmazonWebServiceResponse { private Rule _rule; /// <summary> /// Gets and sets the property Rule. /// <para> /// The created rule. /// </para> /// </summary> public Rule Rule { get { return this._rule; } set { this._rule = value; } } // Check to see if Rule property is set internal bool IsSetRule() { return this._rule != null; } } }
27.719298
111
0.646835
[ "Apache-2.0" ]
DetlefGolze/aws-sdk-net
sdk/src/Services/FraudDetector/Generated/Model/CreateRuleResponse.cs
1,580
C#
using Go_Bootcamp_Q3.Data.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Go_Bootcamp_Q3.Core.IManagers { public interface IWeatherManager { Task<List<Weather>> Get(string parameter); } }
19.733333
50
0.753378
[ "MIT" ]
n-p-morales/Go-Bootcamp-Q3
Go-Bootcamp-Q3/Go-Bootcamp-Q3.Core/IManagers/IWeatherManager.cs
298
C#
using System.Collections.Generic; using System.IO; using Kentico.KInspector.Core; namespace Kentico.KInspector.Modules.Export { /// <summary> /// The interface to implement for adding an export format. /// Add DLL with implementation of this interface to the same folder as executing assembly to auto-load /// all of them. /// </summary> public interface IExportModule { /// <summary> /// Metadata of the module. /// </summary> /// <example> /// <code> /// public ExportModuleMetaData ModuleMetaData => new ExportModuleMetaData("Excel", "ExportXlsx", "xlsx", "application/xlsx"); /// </code> /// </example> ExportModuleMetaData ModuleMetaData { get; } /// <summary> /// Returns stream result of the export process. /// </summary> /// <param name="moduleNames">Modules to export.</param> /// <param name="instanceInfo">Instance for which to execute modules.</param> /// <returns></returns> Stream GetExportStream(IEnumerable<string> moduleNames, IInstanceInfo instanceInfo); } }
33.588235
134
0.624343
[ "MIT" ]
ChristopherBass/KInspector
KInspector.Modules/Export/IExportModule.cs
1,144
C#
using MediatR; using SFA.DAS.EmployerUsers.Domain; namespace SFA.DAS.EmployerUsers.Application.Commands.SuspendUser { public class SuspendUserCommand : IAsyncRequest { public User User { get; set; } } }
21.363636
65
0.689362
[ "MIT" ]
SkillsFundingAgency/das-employerusers
src/SFA.DAS.EmployerUsers.Application/Commands/SuspendUser/SuspendUserCommand.cs
237
C#
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Events; using UnityExtensions; /// <summary> /// Object that computes and manages inputs for the player's controls /// </summary> public class InputManager : MonoBehaviour { private Dictionary<KeyCode, bool> firstClickState; private Dictionary<KeyCode, UnityEvent<bool>> inputEvents, mouseEvents; public UnityEvent<Vector3> OnMouseMove, OnJoystick; public UnityEvent<bool> OnClickL, OnClickR, OnClickM, OnA, OnE, OnF, OnR, OnI, OnK, OnL, OnEscape; private void Start() { firstClickState = new Dictionary<KeyCode, bool> { { KeyCode.Mouse0, false }, { KeyCode.Mouse1, false }, { KeyCode.Mouse2, false }, { KeyCode.A, false }, { KeyCode.E, false }, { KeyCode.F, false }, { KeyCode.R, false }, { KeyCode.I, false }, { KeyCode.K, false }, { KeyCode.L, false }, { KeyCode.Escape, false }, }; mouseEvents = new Dictionary<KeyCode, UnityEvent<bool>> { { KeyCode.Mouse0, OnClickL}, { KeyCode.Mouse1, OnClickR}, { KeyCode.Mouse2, OnClickM}, }; inputEvents = new Dictionary<KeyCode, UnityEvent<bool>> { { KeyCode.A, OnA }, { KeyCode.E, OnE }, { KeyCode.F, OnF }, { KeyCode.R, OnR }, { KeyCode.I, OnI }, { KeyCode.K, OnK }, { KeyCode.L, OnL }, }; } private void Update() { DetectEscape(); } void FixedUpdate() { DetectMouseInputs(); DetectInputs(); } void DetectMouseInputs() { foreach (KeyValuePair<KeyCode, UnityEvent<bool>> keyPressed in mouseEvents) { if (Input.GetKey(keyPressed.Key)) { keyPressed.Value.Invoke(firstClickState[keyPressed.Key]); firstClickState[keyPressed.Key] = false; } else firstClickState[keyPressed.Key] = true; } OnMouseMove.Invoke(Input.mousePosition); } void DetectInputs() { int scrollDelta = MoInput.ScrollHasChanged(); Vector3 joystick = MoInput.GetZQSDDirection(); OnJoystick.Invoke(joystick); foreach (KeyValuePair<KeyCode, UnityEvent<bool>> keyPressed in inputEvents) { if (Input.GetKey(keyPressed.Key)) { keyPressed.Value.Invoke(firstClickState[keyPressed.Key]); firstClickState[keyPressed.Key] = false; } else firstClickState[keyPressed.Key] = true; } } void DetectEscape() { if (Input.GetKey(KeyCode.Escape)) { OnEscape.Invoke(firstClickState[KeyCode.Escape]); firstClickState[KeyCode.Escape] = false; } else firstClickState[KeyCode.Escape] = true; } }
27.509615
193
0.595596
[ "CC0-1.0" ]
Vanane/CyberBonk
Assets/Scripts/Managers/InputManager.cs
2,861
C#
using System; namespace CovarianceGenericDel { class Cat { public string Name { get; set; } public string Breed { get; protected set; } public Cat(string name = "Котик") { Name = name; Breed = "Порода не определена"; } public Cat GetCat() { return this; } public virtual void ShowInfo(){ Console.WriteLine($"{Name} : {Breed}"); } } class MaineCoon : Cat { public MaineCoon(string name = "Мейнкунчик") { Name = name; Breed = "Мейн Кун"; } public MaineCoon GetMaineCoon() { return this; } public override void ShowInfo() { Console.WriteLine($"{Name} : {Breed}"); } } class Program { private delegate T CovarianceGenericDel<out T>(); static void Main(string[] args) { Cat cat = new Cat("Маркиз"); MaineCoon mc = new MaineCoon("Чейз"); CovarianceGenericDel<MaineCoon> delMaineCoon = mc.GetMaineCoon; CovarianceGenericDel<Cat> delCat = delMaineCoon; Cat newCat = delCat(); newCat.ShowInfo(); Console.ReadKey(); } } }
23.716981
83
0.518695
[ "MIT" ]
Croniks/Algorithms-structures-and-patterns
CovarianceGenericDel/Program.cs
1,309
C#
// <auto-generated> // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/ads/googleads/v9/resources/ad_group_simulation.proto // </auto-generated> #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace Google.Ads.GoogleAds.V9.Resources { /// <summary>Holder for reflection information generated from google/ads/googleads/v9/resources/ad_group_simulation.proto</summary> public static partial class AdGroupSimulationReflection { #region Descriptor /// <summary>File descriptor for google/ads/googleads/v9/resources/ad_group_simulation.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static AdGroupSimulationReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "Cjtnb29nbGUvYWRzL2dvb2dsZWFkcy92OS9yZXNvdXJjZXMvYWRfZ3JvdXBf", "c2ltdWxhdGlvbi5wcm90bxIhZ29vZ2xlLmFkcy5nb29nbGVhZHMudjkucmVz", "b3VyY2VzGi9nb29nbGUvYWRzL2dvb2dsZWFkcy92OS9jb21tb24vc2ltdWxh", "dGlvbi5wcm90bxpCZ29vZ2xlL2Fkcy9nb29nbGVhZHMvdjkvZW51bXMvc2lt", "dWxhdGlvbl9tb2RpZmljYXRpb25fbWV0aG9kLnByb3RvGjNnb29nbGUvYWRz", "L2dvb2dsZWFkcy92OS9lbnVtcy9zaW11bGF0aW9uX3R5cGUucHJvdG8aH2dv", "b2dsZS9hcGkvZmllbGRfYmVoYXZpb3IucHJvdG8aGWdvb2dsZS9hcGkvcmVz", "b3VyY2UucHJvdG8aHGdvb2dsZS9hcGkvYW5ub3RhdGlvbnMucHJvdG8i7gcK", "EUFkR3JvdXBTaW11bGF0aW9uEkkKDXJlc291cmNlX25hbWUYASABKAlCMuBB", "A/pBLAoqZ29vZ2xlYWRzLmdvb2dsZWFwaXMuY29tL0FkR3JvdXBTaW11bGF0", "aW9uEh0KC2FkX2dyb3VwX2lkGAwgASgDQgPgQQNIAYgBARJTCgR0eXBlGAMg", "ASgOMkAuZ29vZ2xlLmFkcy5nb29nbGVhZHMudjkuZW51bXMuU2ltdWxhdGlv", "blR5cGVFbnVtLlNpbXVsYXRpb25UeXBlQgPgQQMSfgoTbW9kaWZpY2F0aW9u", "X21ldGhvZBgEIAEoDjJcLmdvb2dsZS5hZHMuZ29vZ2xlYWRzLnY5LmVudW1z", "LlNpbXVsYXRpb25Nb2RpZmljYXRpb25NZXRob2RFbnVtLlNpbXVsYXRpb25N", "b2RpZmljYXRpb25NZXRob2RCA+BBAxIcCgpzdGFydF9kYXRlGA0gASgJQgPg", "QQNIAogBARIaCghlbmRfZGF0ZRgOIAEoCUID4EEDSAOIAQESXAoSY3BjX2Jp", "ZF9wb2ludF9saXN0GAggASgLMjkuZ29vZ2xlLmFkcy5nb29nbGVhZHMudjku", "Y29tbW9uLkNwY0JpZFNpbXVsYXRpb25Qb2ludExpc3RCA+BBA0gAElwKEmNw", "dl9iaWRfcG9pbnRfbGlzdBgKIAEoCzI5Lmdvb2dsZS5hZHMuZ29vZ2xlYWRz", "LnY5LmNvbW1vbi5DcHZCaWRTaW11bGF0aW9uUG9pbnRMaXN0QgPgQQNIABJi", "ChV0YXJnZXRfY3BhX3BvaW50X2xpc3QYCSABKAsyPC5nb29nbGUuYWRzLmdv", "b2dsZWFkcy52OS5jb21tb24uVGFyZ2V0Q3BhU2ltdWxhdGlvblBvaW50TGlz", "dEID4EEDSAASZAoWdGFyZ2V0X3JvYXNfcG9pbnRfbGlzdBgLIAEoCzI9Lmdv", "b2dsZS5hZHMuZ29vZ2xlYWRzLnY5LmNvbW1vbi5UYXJnZXRSb2FzU2ltdWxh", "dGlvblBvaW50TGlzdEID4EEDSAA6nwHqQZsBCipnb29nbGVhZHMuZ29vZ2xl", "YXBpcy5jb20vQWRHcm91cFNpbXVsYXRpb24SbWN1c3RvbWVycy97Y3VzdG9t", "ZXJfaWR9L2FkR3JvdXBTaW11bGF0aW9ucy97YWRfZ3JvdXBfaWR9fnt0eXBl", "fX57bW9kaWZpY2F0aW9uX21ldGhvZH1+e3N0YXJ0X2RhdGV9fntlbmRfZGF0", "ZX1CDAoKcG9pbnRfbGlzdEIOCgxfYWRfZ3JvdXBfaWRCDQoLX3N0YXJ0X2Rh", "dGVCCwoJX2VuZF9kYXRlQoMCCiVjb20uZ29vZ2xlLmFkcy5nb29nbGVhZHMu", "djkucmVzb3VyY2VzQhZBZEdyb3VwU2ltdWxhdGlvblByb3RvUAFaSmdvb2ds", "ZS5nb2xhbmcub3JnL2dlbnByb3RvL2dvb2dsZWFwaXMvYWRzL2dvb2dsZWFk", "cy92OS9yZXNvdXJjZXM7cmVzb3VyY2VzogIDR0FBqgIhR29vZ2xlLkFkcy5H", "b29nbGVBZHMuVjkuUmVzb3VyY2VzygIhR29vZ2xlXEFkc1xHb29nbGVBZHNc", "VjlcUmVzb3VyY2Vz6gIlR29vZ2xlOjpBZHM6Okdvb2dsZUFkczo6Vjk6OlJl", "c291cmNlc2IGcHJvdG8z")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::Google.Ads.GoogleAds.V9.Common.SimulationReflection.Descriptor, global::Google.Ads.GoogleAds.V9.Enums.SimulationModificationMethodReflection.Descriptor, global::Google.Ads.GoogleAds.V9.Enums.SimulationTypeReflection.Descriptor, global::Google.Api.FieldBehaviorReflection.Descriptor, global::Google.Api.ResourceReflection.Descriptor, global::Google.Api.AnnotationsReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Ads.GoogleAds.V9.Resources.AdGroupSimulation), global::Google.Ads.GoogleAds.V9.Resources.AdGroupSimulation.Parser, new[]{ "ResourceName", "AdGroupId", "Type", "ModificationMethod", "StartDate", "EndDate", "CpcBidPointList", "CpvBidPointList", "TargetCpaPointList", "TargetRoasPointList" }, new[]{ "PointList", "AdGroupId", "StartDate", "EndDate" }, null, null, null) })); } #endregion } #region Messages /// <summary> /// An ad group simulation. Supported combinations of advertising /// channel type, simulation type and simulation modification method is /// detailed below respectively. /// /// 1. SEARCH - CPC_BID - DEFAULT /// 2. SEARCH - CPC_BID - UNIFORM /// 3. SEARCH - TARGET_CPA - UNIFORM /// 4. SEARCH - TARGET_ROAS - UNIFORM /// 5. DISPLAY - CPC_BID - DEFAULT /// 6. DISPLAY - CPC_BID - UNIFORM /// 7. DISPLAY - TARGET_CPA - UNIFORM /// 8. VIDEO - CPV_BID - DEFAULT /// 9. VIDEO - CPV_BID - UNIFORM /// </summary> public sealed partial class AdGroupSimulation : pb::IMessage<AdGroupSimulation> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<AdGroupSimulation> _parser = new pb::MessageParser<AdGroupSimulation>(() => new AdGroupSimulation()); private pb::UnknownFieldSet _unknownFields; private int _hasBits0; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pb::MessageParser<AdGroupSimulation> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Ads.GoogleAds.V9.Resources.AdGroupSimulationReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public AdGroupSimulation() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public AdGroupSimulation(AdGroupSimulation other) : this() { _hasBits0 = other._hasBits0; resourceName_ = other.resourceName_; adGroupId_ = other.adGroupId_; type_ = other.type_; modificationMethod_ = other.modificationMethod_; startDate_ = other.startDate_; endDate_ = other.endDate_; switch (other.PointListCase) { case PointListOneofCase.CpcBidPointList: CpcBidPointList = other.CpcBidPointList.Clone(); break; case PointListOneofCase.CpvBidPointList: CpvBidPointList = other.CpvBidPointList.Clone(); break; case PointListOneofCase.TargetCpaPointList: TargetCpaPointList = other.TargetCpaPointList.Clone(); break; case PointListOneofCase.TargetRoasPointList: TargetRoasPointList = other.TargetRoasPointList.Clone(); break; } _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public AdGroupSimulation Clone() { return new AdGroupSimulation(this); } /// <summary>Field number for the "resource_name" field.</summary> public const int ResourceNameFieldNumber = 1; private string resourceName_ = ""; /// <summary> /// Output only. The resource name of the ad group simulation. /// Ad group simulation resource names have the form: /// /// `customers/{customer_id}/adGroupSimulations/{ad_group_id}~{type}~{modification_method}~{start_date}~{end_date}` /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public string ResourceName { get { return resourceName_; } set { resourceName_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "ad_group_id" field.</summary> public const int AdGroupIdFieldNumber = 12; private long adGroupId_; /// <summary> /// Output only. Ad group id of the simulation. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public long AdGroupId { get { if ((_hasBits0 & 1) != 0) { return adGroupId_; } else { return 0L; } } set { _hasBits0 |= 1; adGroupId_ = value; } } /// <summary>Gets whether the "ad_group_id" field is set</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool HasAdGroupId { get { return (_hasBits0 & 1) != 0; } } /// <summary>Clears the value of the "ad_group_id" field</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void ClearAdGroupId() { _hasBits0 &= ~1; } /// <summary>Field number for the "type" field.</summary> public const int TypeFieldNumber = 3; private global::Google.Ads.GoogleAds.V9.Enums.SimulationTypeEnum.Types.SimulationType type_ = global::Google.Ads.GoogleAds.V9.Enums.SimulationTypeEnum.Types.SimulationType.Unspecified; /// <summary> /// Output only. The field that the simulation modifies. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public global::Google.Ads.GoogleAds.V9.Enums.SimulationTypeEnum.Types.SimulationType Type { get { return type_; } set { type_ = value; } } /// <summary>Field number for the "modification_method" field.</summary> public const int ModificationMethodFieldNumber = 4; private global::Google.Ads.GoogleAds.V9.Enums.SimulationModificationMethodEnum.Types.SimulationModificationMethod modificationMethod_ = global::Google.Ads.GoogleAds.V9.Enums.SimulationModificationMethodEnum.Types.SimulationModificationMethod.Unspecified; /// <summary> /// Output only. How the simulation modifies the field. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public global::Google.Ads.GoogleAds.V9.Enums.SimulationModificationMethodEnum.Types.SimulationModificationMethod ModificationMethod { get { return modificationMethod_; } set { modificationMethod_ = value; } } /// <summary>Field number for the "start_date" field.</summary> public const int StartDateFieldNumber = 13; private string startDate_; /// <summary> /// Output only. First day on which the simulation is based, in YYYY-MM-DD format. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public string StartDate { get { return startDate_ ?? ""; } set { startDate_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Gets whether the "start_date" field is set</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool HasStartDate { get { return startDate_ != null; } } /// <summary>Clears the value of the "start_date" field</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void ClearStartDate() { startDate_ = null; } /// <summary>Field number for the "end_date" field.</summary> public const int EndDateFieldNumber = 14; private string endDate_; /// <summary> /// Output only. Last day on which the simulation is based, in YYYY-MM-DD format /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public string EndDate { get { return endDate_ ?? ""; } set { endDate_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Gets whether the "end_date" field is set</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool HasEndDate { get { return endDate_ != null; } } /// <summary>Clears the value of the "end_date" field</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void ClearEndDate() { endDate_ = null; } /// <summary>Field number for the "cpc_bid_point_list" field.</summary> public const int CpcBidPointListFieldNumber = 8; /// <summary> /// Output only. Simulation points if the simulation type is CPC_BID. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public global::Google.Ads.GoogleAds.V9.Common.CpcBidSimulationPointList CpcBidPointList { get { return pointListCase_ == PointListOneofCase.CpcBidPointList ? (global::Google.Ads.GoogleAds.V9.Common.CpcBidSimulationPointList) pointList_ : null; } set { pointList_ = value; pointListCase_ = value == null ? PointListOneofCase.None : PointListOneofCase.CpcBidPointList; } } /// <summary>Field number for the "cpv_bid_point_list" field.</summary> public const int CpvBidPointListFieldNumber = 10; /// <summary> /// Output only. Simulation points if the simulation type is CPV_BID. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public global::Google.Ads.GoogleAds.V9.Common.CpvBidSimulationPointList CpvBidPointList { get { return pointListCase_ == PointListOneofCase.CpvBidPointList ? (global::Google.Ads.GoogleAds.V9.Common.CpvBidSimulationPointList) pointList_ : null; } set { pointList_ = value; pointListCase_ = value == null ? PointListOneofCase.None : PointListOneofCase.CpvBidPointList; } } /// <summary>Field number for the "target_cpa_point_list" field.</summary> public const int TargetCpaPointListFieldNumber = 9; /// <summary> /// Output only. Simulation points if the simulation type is TARGET_CPA. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public global::Google.Ads.GoogleAds.V9.Common.TargetCpaSimulationPointList TargetCpaPointList { get { return pointListCase_ == PointListOneofCase.TargetCpaPointList ? (global::Google.Ads.GoogleAds.V9.Common.TargetCpaSimulationPointList) pointList_ : null; } set { pointList_ = value; pointListCase_ = value == null ? PointListOneofCase.None : PointListOneofCase.TargetCpaPointList; } } /// <summary>Field number for the "target_roas_point_list" field.</summary> public const int TargetRoasPointListFieldNumber = 11; /// <summary> /// Output only. Simulation points if the simulation type is TARGET_ROAS. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public global::Google.Ads.GoogleAds.V9.Common.TargetRoasSimulationPointList TargetRoasPointList { get { return pointListCase_ == PointListOneofCase.TargetRoasPointList ? (global::Google.Ads.GoogleAds.V9.Common.TargetRoasSimulationPointList) pointList_ : null; } set { pointList_ = value; pointListCase_ = value == null ? PointListOneofCase.None : PointListOneofCase.TargetRoasPointList; } } private object pointList_; /// <summary>Enum of possible cases for the "point_list" oneof.</summary> public enum PointListOneofCase { None = 0, CpcBidPointList = 8, CpvBidPointList = 10, TargetCpaPointList = 9, TargetRoasPointList = 11, } private PointListOneofCase pointListCase_ = PointListOneofCase.None; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public PointListOneofCase PointListCase { get { return pointListCase_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void ClearPointList() { pointListCase_ = PointListOneofCase.None; pointList_ = null; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override bool Equals(object other) { return Equals(other as AdGroupSimulation); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool Equals(AdGroupSimulation other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (ResourceName != other.ResourceName) return false; if (AdGroupId != other.AdGroupId) return false; if (Type != other.Type) return false; if (ModificationMethod != other.ModificationMethod) return false; if (StartDate != other.StartDate) return false; if (EndDate != other.EndDate) return false; if (!object.Equals(CpcBidPointList, other.CpcBidPointList)) return false; if (!object.Equals(CpvBidPointList, other.CpvBidPointList)) return false; if (!object.Equals(TargetCpaPointList, other.TargetCpaPointList)) return false; if (!object.Equals(TargetRoasPointList, other.TargetRoasPointList)) return false; if (PointListCase != other.PointListCase) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override int GetHashCode() { int hash = 1; if (ResourceName.Length != 0) hash ^= ResourceName.GetHashCode(); if (HasAdGroupId) hash ^= AdGroupId.GetHashCode(); if (Type != global::Google.Ads.GoogleAds.V9.Enums.SimulationTypeEnum.Types.SimulationType.Unspecified) hash ^= Type.GetHashCode(); if (ModificationMethod != global::Google.Ads.GoogleAds.V9.Enums.SimulationModificationMethodEnum.Types.SimulationModificationMethod.Unspecified) hash ^= ModificationMethod.GetHashCode(); if (HasStartDate) hash ^= StartDate.GetHashCode(); if (HasEndDate) hash ^= EndDate.GetHashCode(); if (pointListCase_ == PointListOneofCase.CpcBidPointList) hash ^= CpcBidPointList.GetHashCode(); if (pointListCase_ == PointListOneofCase.CpvBidPointList) hash ^= CpvBidPointList.GetHashCode(); if (pointListCase_ == PointListOneofCase.TargetCpaPointList) hash ^= TargetCpaPointList.GetHashCode(); if (pointListCase_ == PointListOneofCase.TargetRoasPointList) hash ^= TargetRoasPointList.GetHashCode(); hash ^= (int) pointListCase_; if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else if (ResourceName.Length != 0) { output.WriteRawTag(10); output.WriteString(ResourceName); } if (Type != global::Google.Ads.GoogleAds.V9.Enums.SimulationTypeEnum.Types.SimulationType.Unspecified) { output.WriteRawTag(24); output.WriteEnum((int) Type); } if (ModificationMethod != global::Google.Ads.GoogleAds.V9.Enums.SimulationModificationMethodEnum.Types.SimulationModificationMethod.Unspecified) { output.WriteRawTag(32); output.WriteEnum((int) ModificationMethod); } if (pointListCase_ == PointListOneofCase.CpcBidPointList) { output.WriteRawTag(66); output.WriteMessage(CpcBidPointList); } if (pointListCase_ == PointListOneofCase.TargetCpaPointList) { output.WriteRawTag(74); output.WriteMessage(TargetCpaPointList); } if (pointListCase_ == PointListOneofCase.CpvBidPointList) { output.WriteRawTag(82); output.WriteMessage(CpvBidPointList); } if (pointListCase_ == PointListOneofCase.TargetRoasPointList) { output.WriteRawTag(90); output.WriteMessage(TargetRoasPointList); } if (HasAdGroupId) { output.WriteRawTag(96); output.WriteInt64(AdGroupId); } if (HasStartDate) { output.WriteRawTag(106); output.WriteString(StartDate); } if (HasEndDate) { output.WriteRawTag(114); output.WriteString(EndDate); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { if (ResourceName.Length != 0) { output.WriteRawTag(10); output.WriteString(ResourceName); } if (Type != global::Google.Ads.GoogleAds.V9.Enums.SimulationTypeEnum.Types.SimulationType.Unspecified) { output.WriteRawTag(24); output.WriteEnum((int) Type); } if (ModificationMethod != global::Google.Ads.GoogleAds.V9.Enums.SimulationModificationMethodEnum.Types.SimulationModificationMethod.Unspecified) { output.WriteRawTag(32); output.WriteEnum((int) ModificationMethod); } if (pointListCase_ == PointListOneofCase.CpcBidPointList) { output.WriteRawTag(66); output.WriteMessage(CpcBidPointList); } if (pointListCase_ == PointListOneofCase.TargetCpaPointList) { output.WriteRawTag(74); output.WriteMessage(TargetCpaPointList); } if (pointListCase_ == PointListOneofCase.CpvBidPointList) { output.WriteRawTag(82); output.WriteMessage(CpvBidPointList); } if (pointListCase_ == PointListOneofCase.TargetRoasPointList) { output.WriteRawTag(90); output.WriteMessage(TargetRoasPointList); } if (HasAdGroupId) { output.WriteRawTag(96); output.WriteInt64(AdGroupId); } if (HasStartDate) { output.WriteRawTag(106); output.WriteString(StartDate); } if (HasEndDate) { output.WriteRawTag(114); output.WriteString(EndDate); } if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public int CalculateSize() { int size = 0; if (ResourceName.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(ResourceName); } if (HasAdGroupId) { size += 1 + pb::CodedOutputStream.ComputeInt64Size(AdGroupId); } if (Type != global::Google.Ads.GoogleAds.V9.Enums.SimulationTypeEnum.Types.SimulationType.Unspecified) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Type); } if (ModificationMethod != global::Google.Ads.GoogleAds.V9.Enums.SimulationModificationMethodEnum.Types.SimulationModificationMethod.Unspecified) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) ModificationMethod); } if (HasStartDate) { size += 1 + pb::CodedOutputStream.ComputeStringSize(StartDate); } if (HasEndDate) { size += 1 + pb::CodedOutputStream.ComputeStringSize(EndDate); } if (pointListCase_ == PointListOneofCase.CpcBidPointList) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(CpcBidPointList); } if (pointListCase_ == PointListOneofCase.CpvBidPointList) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(CpvBidPointList); } if (pointListCase_ == PointListOneofCase.TargetCpaPointList) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(TargetCpaPointList); } if (pointListCase_ == PointListOneofCase.TargetRoasPointList) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(TargetRoasPointList); } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(AdGroupSimulation other) { if (other == null) { return; } if (other.ResourceName.Length != 0) { ResourceName = other.ResourceName; } if (other.HasAdGroupId) { AdGroupId = other.AdGroupId; } if (other.Type != global::Google.Ads.GoogleAds.V9.Enums.SimulationTypeEnum.Types.SimulationType.Unspecified) { Type = other.Type; } if (other.ModificationMethod != global::Google.Ads.GoogleAds.V9.Enums.SimulationModificationMethodEnum.Types.SimulationModificationMethod.Unspecified) { ModificationMethod = other.ModificationMethod; } if (other.HasStartDate) { StartDate = other.StartDate; } if (other.HasEndDate) { EndDate = other.EndDate; } switch (other.PointListCase) { case PointListOneofCase.CpcBidPointList: if (CpcBidPointList == null) { CpcBidPointList = new global::Google.Ads.GoogleAds.V9.Common.CpcBidSimulationPointList(); } CpcBidPointList.MergeFrom(other.CpcBidPointList); break; case PointListOneofCase.CpvBidPointList: if (CpvBidPointList == null) { CpvBidPointList = new global::Google.Ads.GoogleAds.V9.Common.CpvBidSimulationPointList(); } CpvBidPointList.MergeFrom(other.CpvBidPointList); break; case PointListOneofCase.TargetCpaPointList: if (TargetCpaPointList == null) { TargetCpaPointList = new global::Google.Ads.GoogleAds.V9.Common.TargetCpaSimulationPointList(); } TargetCpaPointList.MergeFrom(other.TargetCpaPointList); break; case PointListOneofCase.TargetRoasPointList: if (TargetRoasPointList == null) { TargetRoasPointList = new global::Google.Ads.GoogleAds.V9.Common.TargetRoasSimulationPointList(); } TargetRoasPointList.MergeFrom(other.TargetRoasPointList); break; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 10: { ResourceName = input.ReadString(); break; } case 24: { Type = (global::Google.Ads.GoogleAds.V9.Enums.SimulationTypeEnum.Types.SimulationType) input.ReadEnum(); break; } case 32: { ModificationMethod = (global::Google.Ads.GoogleAds.V9.Enums.SimulationModificationMethodEnum.Types.SimulationModificationMethod) input.ReadEnum(); break; } case 66: { global::Google.Ads.GoogleAds.V9.Common.CpcBidSimulationPointList subBuilder = new global::Google.Ads.GoogleAds.V9.Common.CpcBidSimulationPointList(); if (pointListCase_ == PointListOneofCase.CpcBidPointList) { subBuilder.MergeFrom(CpcBidPointList); } input.ReadMessage(subBuilder); CpcBidPointList = subBuilder; break; } case 74: { global::Google.Ads.GoogleAds.V9.Common.TargetCpaSimulationPointList subBuilder = new global::Google.Ads.GoogleAds.V9.Common.TargetCpaSimulationPointList(); if (pointListCase_ == PointListOneofCase.TargetCpaPointList) { subBuilder.MergeFrom(TargetCpaPointList); } input.ReadMessage(subBuilder); TargetCpaPointList = subBuilder; break; } case 82: { global::Google.Ads.GoogleAds.V9.Common.CpvBidSimulationPointList subBuilder = new global::Google.Ads.GoogleAds.V9.Common.CpvBidSimulationPointList(); if (pointListCase_ == PointListOneofCase.CpvBidPointList) { subBuilder.MergeFrom(CpvBidPointList); } input.ReadMessage(subBuilder); CpvBidPointList = subBuilder; break; } case 90: { global::Google.Ads.GoogleAds.V9.Common.TargetRoasSimulationPointList subBuilder = new global::Google.Ads.GoogleAds.V9.Common.TargetRoasSimulationPointList(); if (pointListCase_ == PointListOneofCase.TargetRoasPointList) { subBuilder.MergeFrom(TargetRoasPointList); } input.ReadMessage(subBuilder); TargetRoasPointList = subBuilder; break; } case 96: { AdGroupId = input.ReadInt64(); break; } case 106: { StartDate = input.ReadString(); break; } case 114: { EndDate = input.ReadString(); break; } } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 10: { ResourceName = input.ReadString(); break; } case 24: { Type = (global::Google.Ads.GoogleAds.V9.Enums.SimulationTypeEnum.Types.SimulationType) input.ReadEnum(); break; } case 32: { ModificationMethod = (global::Google.Ads.GoogleAds.V9.Enums.SimulationModificationMethodEnum.Types.SimulationModificationMethod) input.ReadEnum(); break; } case 66: { global::Google.Ads.GoogleAds.V9.Common.CpcBidSimulationPointList subBuilder = new global::Google.Ads.GoogleAds.V9.Common.CpcBidSimulationPointList(); if (pointListCase_ == PointListOneofCase.CpcBidPointList) { subBuilder.MergeFrom(CpcBidPointList); } input.ReadMessage(subBuilder); CpcBidPointList = subBuilder; break; } case 74: { global::Google.Ads.GoogleAds.V9.Common.TargetCpaSimulationPointList subBuilder = new global::Google.Ads.GoogleAds.V9.Common.TargetCpaSimulationPointList(); if (pointListCase_ == PointListOneofCase.TargetCpaPointList) { subBuilder.MergeFrom(TargetCpaPointList); } input.ReadMessage(subBuilder); TargetCpaPointList = subBuilder; break; } case 82: { global::Google.Ads.GoogleAds.V9.Common.CpvBidSimulationPointList subBuilder = new global::Google.Ads.GoogleAds.V9.Common.CpvBidSimulationPointList(); if (pointListCase_ == PointListOneofCase.CpvBidPointList) { subBuilder.MergeFrom(CpvBidPointList); } input.ReadMessage(subBuilder); CpvBidPointList = subBuilder; break; } case 90: { global::Google.Ads.GoogleAds.V9.Common.TargetRoasSimulationPointList subBuilder = new global::Google.Ads.GoogleAds.V9.Common.TargetRoasSimulationPointList(); if (pointListCase_ == PointListOneofCase.TargetRoasPointList) { subBuilder.MergeFrom(TargetRoasPointList); } input.ReadMessage(subBuilder); TargetRoasPointList = subBuilder; break; } case 96: { AdGroupId = input.ReadInt64(); break; } case 106: { StartDate = input.ReadString(); break; } case 114: { EndDate = input.ReadString(); break; } } } } #endif } #endregion } #endregion Designer generated code
44.580231
434
0.686622
[ "Apache-2.0" ]
friedenberg/google-ads-dotnet
src/V9/Types/AdGroupSimulation.g.cs
34,728
C#
//--------------------------------------------------------------------------- // // Copyright (C) Microsoft Corporation. All rights reserved. // // File: DocumentPageView.cs // // Description: Provides a view port for a page of content for a DocumentPage. // //--------------------------------------------------------------------------- using System.Windows.Automation; // AutomationPattern using System.Windows.Automation.Peers; // AutomationPeer using System.Windows.Controls; // StretchDirection using System.Windows.Controls.Primitives; // DocumentViewerBase using System.Windows.Documents; // DocumentPaginator using System.Windows.Media; // Visual using System.Windows.Media.Imaging; // RenderTargetBitmap using System.Windows.Threading; // Dispatcher using MS.Internal; // Invariant using MS.Internal.Documents; // DocumentPageHost, DocumentPageTextView using MS.Internal.Automation; // TextAdaptor using MS.Internal.KnownBoxes; // BooleanBoxes namespace System.Windows.Controls.Primitives { /// <summary> /// Provides a view port for a page of content for a DocumentPage. /// </summary> public class DocumentPageView : FrameworkElement, IServiceProvider, IDisposable { //------------------------------------------------------------------- // // Constructors // //------------------------------------------------------------------- #region Constructors /// <summary> /// Create an instance of a DocumentPageView. /// </summary> /// <remarks> /// This does basic initialization of the DocumentPageView. All subclasses /// must call the base constructor to perform this initialization. /// </remarks> public DocumentPageView() : base() { _pageZoom = 1.0; } /// <summary> /// Static ctor. Initializes property metadata. /// </summary> static DocumentPageView() { ClipToBoundsProperty.OverrideMetadata(typeof(DocumentPageView), new PropertyMetadata(BooleanBoxes.TrueBox)); } #endregion //------------------------------------------------------------------- // // Public Properties // //------------------------------------------------------------------- #region Public Properties /// <summary> /// The Paginator from which this DocumentPageView retrieves pages. /// </summary> public DocumentPaginator DocumentPaginator { get { return _documentPaginator; } set { CheckDisposed(); if (_documentPaginator != value) { // Cleanup all state associated with old Paginator. if (_documentPaginator != null) { _documentPaginator.GetPageCompleted -= new GetPageCompletedEventHandler(HandleGetPageCompleted); _documentPaginator.PagesChanged -= new PagesChangedEventHandler(HandlePagesChanged); DisposeCurrentPage(); DisposeAsyncPage(); } Invariant.Assert(_documentPage == null); Invariant.Assert(_documentPageAsync == null); _documentPaginator = value; _textView = null; // Register for events on new Paginator and invalidate // measure to force content update. if (_documentPaginator != null) { _documentPaginator.GetPageCompleted += new GetPageCompletedEventHandler(HandleGetPageCompleted); _documentPaginator.PagesChanged += new PagesChangedEventHandler(HandlePagesChanged); } InvalidateMeasure(); } } } /// <summary> /// The DocumentPage for the displayed page. /// </summary> public DocumentPage DocumentPage { get { return (_documentPage == null) ? DocumentPage.Missing : _documentPage; } } /// <summary> /// The page number displayed; no content is displayed if this number is negative. /// PageNumber is zero-based. /// </summary> public int PageNumber { get { return (int) GetValue(PageNumberProperty); } set { SetValue(PageNumberProperty, value); } } /// <summary> /// Controls the stretching behavior for the page. /// </summary> public Stretch Stretch { get { return (Stretch)GetValue(StretchProperty); } set { SetValue(StretchProperty, value); } } /// <summary> /// Specifies the directions in which page may be stretched. /// </summary> public StretchDirection StretchDirection { get { return (StretchDirection)GetValue(StretchDirectionProperty); } set { SetValue(StretchDirectionProperty, value); } } #region Public Dynamic Properties /// <summary> /// <see cref="PageNumber"/> /// </summary> public static readonly DependencyProperty PageNumberProperty = DependencyProperty.Register( "PageNumber", typeof(int), typeof(DocumentPageView), new FrameworkPropertyMetadata( 0, FrameworkPropertyMetadataOptions.AffectsMeasure, new PropertyChangedCallback(OnPageNumberChanged))); /// <summary> /// <see cref="Stretch" /> /// </summary> public static readonly DependencyProperty StretchProperty = Viewbox.StretchProperty.AddOwner( typeof(DocumentPageView), new FrameworkPropertyMetadata( Stretch.Uniform, FrameworkPropertyMetadataOptions.AffectsMeasure)); /// <summary> /// <see cref="StretchDirection" /> /// </summary> public static readonly DependencyProperty StretchDirectionProperty = Viewbox.StretchDirectionProperty.AddOwner( typeof(DocumentPageView), new FrameworkPropertyMetadata( StretchDirection.DownOnly, FrameworkPropertyMetadataOptions.AffectsMeasure)); #endregion Public Dynamic Properties #endregion Public Properties //------------------------------------------------------------------- // // Public Events // //------------------------------------------------------------------- #region Public Events /// <summary> /// Fired after a DocumentPage.Visual is connected. /// </summary> public event EventHandler PageConnected; /// <summary> /// Fired after a DocumentPage.Visual is disconnected. /// </summary> public event EventHandler PageDisconnected; #endregion Public Events //------------------------------------------------------------------- // // Protected Methods // //------------------------------------------------------------------- #region Protected Methods /// <summary> /// Content measurement. /// </summary> /// <param name="availableSize">Available size that parent can give to the child. This is soft constraint.</param> /// <returns>The DocumentPageView's desired size.</returns> protected override sealed Size MeasureOverride(Size availableSize) { Size newPageSize, pageZoom; Size pageSize; Size desiredSize = new Size(); // If no page is available, return (0,0) as size. CheckDisposed(); if (_suspendLayout) { desiredSize = this.DesiredSize; } else if (_documentPaginator != null) { // Reflow content if needed. if (ShouldReflowContent()) { // Reflow is disabled when dealing with infinite size in both directions. // If only one dimention is infinte, calculate value based on PageSize of the // document and Stretching properties. if (!Double.IsInfinity(availableSize.Width) || !Double.IsInfinity(availableSize.Height)) { pageSize = _documentPaginator.PageSize; if (Double.IsInfinity(availableSize.Width)) { newPageSize = new Size(); newPageSize.Height = availableSize.Height / _pageZoom; newPageSize.Width = newPageSize.Height * (pageSize.Width / pageSize.Height); // Keep aspect ratio. } else if (Double.IsInfinity(availableSize.Height)) { newPageSize = new Size(); newPageSize.Width = availableSize.Width / _pageZoom; newPageSize.Height = newPageSize.Width * (pageSize.Height / pageSize.Width); // Keep aspect ratio. } else { newPageSize = new Size(availableSize.Width / _pageZoom, availableSize.Height / _pageZoom); } if (!DoubleUtil.AreClose(pageSize, newPageSize)) { _documentPaginator.PageSize = newPageSize; } } } // If the main page or pending async page are not available yet, // asynchronously request new page from Paginator. if (_documentPage == null && _documentPageAsync == null) { if (PageNumber >= 0) { if (_useAsynchronous) { _documentPaginator.GetPageAsync(PageNumber, this); } else { _documentPageAsync = _documentPaginator.GetPage(PageNumber); if (_documentPageAsync == null) { _documentPageAsync = DocumentPage.Missing; } } } else { _documentPage = DocumentPage.Missing; } } // If pending async page is available, discard the main page and // set _documentPage to _documentPageAsync. if (_documentPageAsync != null) { // Do cleanup for currently used page, because it gets replaced. DisposeCurrentPage(); // DisposeCurrentPage raises PageDisposed and DocumentPage.PageDestroyed events. // Handlers for those events may dispose _documentPageAsync. Treat this situation // as missing page. if (_documentPageAsync == null) { _documentPageAsync = DocumentPage.Missing; } if (_pageVisualClone != null) { RemoveDuplicateVisual(); } // Replace the main page with cached async page. _documentPage = _documentPageAsync; if (_documentPage != DocumentPage.Missing) { _documentPage.PageDestroyed += new EventHandler(HandlePageDestroyed); _documentPageAsync.PageDestroyed -= new EventHandler(HandleAsyncPageDestroyed); } _documentPageAsync = null; // Set a flag that will indicate that a PageConnected must be fired in // ArrangeOverride _newPageConnected = true; } // If page is available, return its size as desired size. if (_documentPage != null && _documentPage != DocumentPage.Missing) { pageSize = new Size(_documentPage.Size.Width * _pageZoom, _documentPage.Size.Height * _pageZoom); pageZoom = Viewbox.ComputeScaleFactor(availableSize, pageSize, this.Stretch, this.StretchDirection); desiredSize = new Size(pageSize.Width * pageZoom.Width, pageSize.Height * pageZoom.Height); } if (_pageVisualClone != null) { desiredSize = _visualCloneSize; } } return desiredSize; } /// <summary> /// Content arrangement. /// </summary> /// <param name="finalSize">The final size that element should use to arrange itself and its children.</param> protected override sealed Size ArrangeOverride(Size finalSize) { Transform pageTransform; ScaleTransform pageScaleTransform; Visual pageVisual; Size pageSize, pageZoom; CheckDisposed(); if (_pageVisualClone == null) { if (_pageHost == null) { _pageHost = new DocumentPageHost(); this.AddVisualChild(_pageHost); } Invariant.Assert(_pageHost != null); pageVisual = (_documentPage == null) ? null : _documentPage.Visual; if (pageVisual == null) { // Remove existing visiual children. _pageHost.PageVisual = null; // Reset offset and transform on the page host before Arrange _pageHost.CachedOffset = new Point(); _pageHost.RenderTransform = null; // Size for the page host needs to be set to finalSize _pageHost.Arrange(new Rect(_pageHost.CachedOffset, finalSize)); } else { // Add visual representing the page contents. For performance reasons // first check if it is already insered there. if (_pageHost.PageVisual != pageVisual) { // There might be a case where a visual associated with a page was // inserted to a visual tree before. It got removed later, but GC did not // destroy its parent yet. To workaround this case always check for the parent // of page visual and disconnect it, when necessary. DocumentPageHost.DisconnectPageVisual(pageVisual); _pageHost.PageVisual = pageVisual; } // Compute transform to be applied to the page visual. First take into account // mirroring transform, if necessary. Apply also scaling transform. pageSize = _documentPage.Size; pageTransform = Transform.Identity; // DocumentPage.Visual is always LeftToRight, so if the current // FlowDirection is RightToLeft, need to unmirror the child visual. if (FlowDirection == FlowDirection.RightToLeft) { pageTransform = new MatrixTransform(-1.0, 0.0, 0.0, 1.0, pageSize.Width, 0.0); } // Apply zooming if (!DoubleUtil.IsOne(_pageZoom)) { pageScaleTransform = new ScaleTransform(_pageZoom, _pageZoom); if (pageTransform == Transform.Identity) { pageTransform = pageScaleTransform; } else { pageTransform = new MatrixTransform(pageTransform.Value * pageScaleTransform.Value); } pageSize = new Size(pageSize.Width * _pageZoom, pageSize.Height * _pageZoom); } // Apply stretch properties pageZoom = Viewbox.ComputeScaleFactor(finalSize, pageSize, this.Stretch, this.StretchDirection); if (!DoubleUtil.IsOne(pageZoom.Width) || !DoubleUtil.IsOne(pageZoom.Height)) { pageScaleTransform = new ScaleTransform(pageZoom.Width, pageZoom.Height); if (pageTransform == Transform.Identity) { pageTransform = pageScaleTransform; } else { pageTransform = new MatrixTransform(pageTransform.Value * pageScaleTransform.Value); } pageSize = new Size(pageSize.Width * pageZoom.Width, pageSize.Height * pageZoom.Height); } // Set offset and transform on the page host before Arrange _pageHost.CachedOffset = new Point((finalSize.Width - pageSize.Width) / 2, (finalSize.Height - pageSize.Height) / 2); _pageHost.RenderTransform = pageTransform; // Arrange pagehost to original size of the page. _pageHost.Arrange(new Rect(_pageHost.CachedOffset, _documentPage.Size)); } // Fire [....] notification if new page was connected. if (_newPageConnected) { OnPageConnected(); } // Transform for the page has been changed, need to notify TextView about the changes. OnTransformChangedAsync(); } else { if (_pageHost.PageVisual != _pageVisualClone) { // Remove existing visiual children. _pageHost.PageVisual = _pageVisualClone; // Size for the page host needs to be set to finalSize // Use previous offset and transform _pageHost.Arrange(new Rect(_pageHost.CachedOffset, finalSize)); } } return base.ArrangeOverride(finalSize); } /// <summary> /// Derived class must implement to support Visual children. The method must return /// the child at the specified index. Index must be between 0 and GetVisualChildrenCount-1. /// </summary> protected override Visual GetVisualChild(int index) { if (index != 0 || _pageHost == null) { throw new ArgumentOutOfRangeException("index", index, SR.Get(SRID.Visual_ArgumentOutOfRange)); } return _pageHost; } /// <summary> /// Dispose the object. /// </summary> protected void Dispose() { if (!_disposed) { _disposed = true; // Cleanup all state associated with Paginator. if (_documentPaginator != null) { _documentPaginator.GetPageCompleted -= new GetPageCompletedEventHandler(HandleGetPageCompleted); _documentPaginator.PagesChanged -= new PagesChangedEventHandler(HandlePagesChanged); _documentPaginator.CancelAsync(this); DisposeCurrentPage(); DisposeAsyncPage(); } Invariant.Assert(_documentPage == null); Invariant.Assert(_documentPageAsync == null); _documentPaginator = null; _textView = null; } } /// <summary> /// Returns service objects associated with this control. /// This method should be called by IServiceProvider.GetService implementation /// for DocumentPageView or subclasses. /// </summary> /// <param name="serviceType">Specifies the type of service object to get.</param> protected object GetService(Type serviceType) { object service = null; if (serviceType == null) { throw new ArgumentNullException("serviceType"); } CheckDisposed(); // No service is available if the Content does not provide // any services. if (_documentPaginator != null && _documentPaginator is IServiceProvider) { // Following services are available: // (1) TextView - wrapper for TextView exposed by the current page. // (2) TextContainer - the service object is retrieved from DocumentPaginator. if (serviceType == typeof(ITextView)) { if (_textView == null) { ITextContainer tc = ((IServiceProvider)_documentPaginator).GetService(typeof(ITextContainer)) as ITextContainer; if (tc != null) { _textView = new DocumentPageTextView(this, tc); } } service = _textView; } else if (serviceType == typeof(TextContainer) || serviceType == typeof(ITextContainer)) { service = ((IServiceProvider)_documentPaginator).GetService(serviceType); } } return service; } /// <summary> /// Creates AutomationPeer (<see cref="UIElement.OnCreateAutomationPeer"/>) /// </summary> protected override AutomationPeer OnCreateAutomationPeer() { return new DocumentPageViewAutomationPeer(this); } #endregion Protected Methods //------------------------------------------------------------------- // // Protected Properties // //------------------------------------------------------------------- #region Protected Properties /// <summary> /// Whether this DocumentPageView has been disposed. /// </summary> protected bool IsDisposed { get { return _disposed; } } /// <summary> /// Derived classes override this property to enable the Visual code to enumerate /// the Visual children. Derived classes need to return the number of children /// from this method. /// </summary> protected override int VisualChildrenCount { get { return _pageHost != null ? 1 : 0; } } #endregion Protected Properties //------------------------------------------------------------------- // // Internal Methods // //------------------------------------------------------------------- #region Internal Methods /// <summary> /// Sets the zoom applied to the page being displayed. /// </summary> /// <param name="pageZoom">Page zooom value.</param> internal void SetPageZoom(double pageZoom) { Invariant.Assert(!DoubleUtil.LessThanOrClose(pageZoom, 0d) && !Double.IsInfinity(pageZoom)); Invariant.Assert(!_disposed); if (!DoubleUtil.AreClose(_pageZoom, pageZoom)) { _pageZoom = pageZoom; InvalidateMeasure(); } } /// <summary> /// Suspends page layout. /// </summary> internal void SuspendLayout() { _suspendLayout = true; _pageVisualClone = DuplicatePageVisual(); _visualCloneSize = this.DesiredSize; } /// <summary> /// Resumes page layout. /// </summary> internal void ResumeLayout() { _suspendLayout = false; _pageVisualClone = null; InvalidateMeasure(); } /// <summary> /// Duplicates the current page visual, if possible /// </summary> internal void DuplicateVisual() { if (_documentPage != null && _pageVisualClone == null) { _pageVisualClone = DuplicatePageVisual(); _visualCloneSize = this.DesiredSize; InvalidateArrange(); } } /// <summary> /// Clears the duplicated page visual, if one exists. /// </summary> internal void RemoveDuplicateVisual() { if (_pageVisualClone != null) { _pageVisualClone = null; InvalidateArrange(); } } #endregion Internal Methods //------------------------------------------------------------------- // // Internal Properties // //------------------------------------------------------------------- #region Internal Properties /// <summary> /// Default is true. Controls whether we use asynchronous mode to /// request the DocumentPage. In some cases, such as synchronous /// printing, we don't want to wait for the asynchronous events. /// </summary> internal bool UseAsynchronousGetPage { get { return _useAsynchronous; } set { _useAsynchronous = value; } } /// <summary> /// The DocumentPage for the displayed page. /// </summary> internal DocumentPage DocumentPageInternal { get { return _documentPage; } } #endregion Internal Properties //------------------------------------------------------------------- // // Private Methods // //------------------------------------------------------------------- #region Private Methods /// <summary> /// Handles PageDestroyed event raised for the current DocumentPage. /// </summary> /// <param name="sender">Source of the event.</param> /// <param name="e">Not used.</param> private void HandlePageDestroyed(object sender, EventArgs e) { if (!_disposed) { InvalidateMeasure(); DisposeCurrentPage(); } } /// <summary> /// Handles PageDestroyed event raised for the cached async DocumentPage. /// </summary> /// <param name="sender">Source of the event.</param> /// <param name="e">Not used.</param> private void HandleAsyncPageDestroyed(object sender, EventArgs e) { if (!_disposed) { DisposeAsyncPage(); } } /// <summary> /// Handles GetPageCompleted event raised by the DocumentPaginator. /// </summary> /// <param name="sender">Source of the event.</param> /// <param name="e">Details about this event.</param> private void HandleGetPageCompleted(object sender, GetPageCompletedEventArgs e) { if (!_disposed && (e != null) && !e.Cancelled && e.Error == null) { if (e.PageNumber == this.PageNumber && e.UserState == this) { if (_documentPageAsync != null && _documentPageAsync != DocumentPage.Missing) { _documentPageAsync.PageDestroyed -= new EventHandler(HandleAsyncPageDestroyed); } _documentPageAsync = e.DocumentPage; if (_documentPageAsync == null) { _documentPageAsync = DocumentPage.Missing; } if (_documentPageAsync != DocumentPage.Missing) { _documentPageAsync.PageDestroyed += new EventHandler(HandleAsyncPageDestroyed); } InvalidateMeasure(); } // else; the page is not ours } } /// <summary> /// Handles PagesChanged event raised by the DocumentPaginator. /// </summary> /// <param name="sender">Source of the event.</param> /// <param name="e">Details about this event.</param> private void HandlePagesChanged(object sender, PagesChangedEventArgs e) { if (!_disposed && (e != null)) { if (this.PageNumber >= e.Start && (e.Count == int.MaxValue || this.PageNumber <= e.Start + e.Count)) { OnPageContentChanged(); } } } /// <summary> /// Async notification about transform changes for embedded page. /// </summary> private void OnTransformChangedAsync() { Dispatcher.BeginInvoke(DispatcherPriority.Normal, new DispatcherOperationCallback(OnTransformChanged), null); } /// <summary> /// Notification about transform changes for embedded page. /// </summary> /// <param name="arg">Not used.</param> /// <returns>Not used.</returns> private object OnTransformChanged(object arg) { if (_textView != null && _documentPage != null) { _textView.OnTransformChanged(); } return null; } /// <summary> /// Raises PageConnected event. /// </summary> private void OnPageConnected() { _newPageConnected = false; if (_textView != null) { _textView.OnPageConnected(); } if (this.PageConnected != null && _documentPage != null) { this.PageConnected(this, EventArgs.Empty); } } /// <summary> /// Raises PageDisconnected event. /// </summary> private void OnPageDisconnected() { if (_textView != null) { _textView.OnPageDisconnected(); } if (this.PageDisconnected != null) { this.PageDisconnected(this, EventArgs.Empty); } } /// <summary> /// Responds to page content change. /// </summary> private void OnPageContentChanged() { // Force remeasure which will cause to reget DocumentPage InvalidateMeasure(); // Do cleanup for currently used page, because it gets replaced. DisposeCurrentPage(); DisposeAsyncPage(); } /// <summary> /// Disposes the current DocumentPage. /// </summary> private void DisposeCurrentPage() { // Do cleanup for currently used page, because it gets replaced. if (_documentPage != null) { // Remove visual for currently used page. if (_pageHost != null) { _pageHost.PageVisual = null; } // Clear TextView & DocumentPage if (_documentPage != DocumentPage.Missing) { _documentPage.PageDestroyed -= new EventHandler(HandlePageDestroyed); } if (_documentPage is IDisposable) { ((IDisposable)_documentPage).Dispose(); } _documentPage = null; OnPageDisconnected(); } } /// <summary> /// Disposes pending async DocumentPage. /// </summary> private void DisposeAsyncPage() { // Do cleanup for cached async page. if (_documentPageAsync != null) { if (_documentPageAsync != DocumentPage.Missing) { _documentPageAsync.PageDestroyed -= new EventHandler(HandleAsyncPageDestroyed); } if (_documentPageAsync is IDisposable) { ((IDisposable)_documentPageAsync).Dispose(); } _documentPageAsync = null; } } /// <summary> /// Checks if the instance is already disposed. /// </summary> private void CheckDisposed() { if (_disposed) { throw new ObjectDisposedException(typeof(DocumentPageView).ToString()); } } /// <summary> /// Check whether content needs to be reflowed. /// </summary> /// <returns>True, if content needs to be reflowed.</returns> private bool ShouldReflowContent() { bool shouldReflow = false; DocumentViewerBase hostViewer; if (DocumentViewerBase.GetIsMasterPage(this)) { hostViewer = GetHostViewer(); if (hostViewer != null) { shouldReflow = hostViewer.IsMasterPageView(this); } } return shouldReflow; } /// <summary> /// Retrieves DocumentViewerBase that hosts this view. /// </summary> /// <returns>DocumentViewerBase that hosts this view.</returns> private DocumentViewerBase GetHostViewer() { DocumentViewerBase hostViewer = null; Visual visualParent; // First do quick check for TemplatedParent. It will cover good // amount of cases, because static viewers will have their // DocumentPageViews defined in the style. // If quick check does not work, do a visual tree walk. if (this.TemplatedParent is DocumentViewerBase) { hostViewer = (DocumentViewerBase)this.TemplatedParent; } else { // Check if hosted by DocumentViewerBase. visualParent = VisualTreeHelper.GetParent(this) as Visual; while (visualParent != null) { if (visualParent is DocumentViewerBase) { hostViewer = (DocumentViewerBase)visualParent; break; } visualParent = VisualTreeHelper.GetParent(visualParent) as Visual; } } return hostViewer; } /// <summary> /// The PageNumber has changed and needs to be updated. /// </summary> private static void OnPageNumberChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { Invariant.Assert(d != null && d is DocumentPageView); ((DocumentPageView)d).OnPageContentChanged(); } /// <summary> /// Duplicates content of the PageVisual. /// </summary> private DrawingVisual DuplicatePageVisual() { DrawingVisual drawingVisual = null; if (_pageHost != null && _pageHost.PageVisual != null && _documentPage.Size != Size.Empty) { const double maxWidth = 4096.0; const double maxHeight = maxWidth; Rect pageVisualRect = new Rect(_documentPage.Size); pageVisualRect.Width = Math.Min(pageVisualRect.Width, maxWidth); pageVisualRect.Height = Math.Min(pageVisualRect.Height, maxHeight); drawingVisual = new DrawingVisual(); try { if(pageVisualRect.Width > 1.0 && pageVisualRect.Height > 1.0) { RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap((int)pageVisualRect.Width, (int)pageVisualRect.Height, 96.0, 96.0, PixelFormats.Pbgra32); renderTargetBitmap.Render(_pageHost.PageVisual); ImageBrush imageBrush = new ImageBrush(renderTargetBitmap); drawingVisual.Opacity = 0.50; using (DrawingContext dc = drawingVisual.RenderOpen()) { dc.DrawRectangle(imageBrush, null, pageVisualRect); } } } catch(System.OverflowException) { // Ignore overflow exception - caused by render target creation not possible under current memory conditions. } } return drawingVisual; } #endregion Private Methods //------------------------------------------------------------------- // // Private Fields // //------------------------------------------------------------------- #region Private Fields private DocumentPaginator _documentPaginator; private double _pageZoom; private DocumentPage _documentPage; private DocumentPage _documentPageAsync; private DocumentPageTextView _textView; private DocumentPageHost _pageHost; private Visual _pageVisualClone; private Size _visualCloneSize; private bool _useAsynchronous = true; private bool _suspendLayout; private bool _disposed; private bool _newPageConnected; #endregion Private Fields //------------------------------------------------------------------- // // IServiceProvider Members // //------------------------------------------------------------------- #region IServiceProvider Members /// <summary> /// Returns service objects associated with this control. /// </summary> /// <param name="serviceType">Specifies the type of service object to get.</param> object IServiceProvider.GetService(Type serviceType) { return this.GetService(serviceType); } #endregion IServiceProvider Members //------------------------------------------------------------------- // // IDisposable Members // //------------------------------------------------------------------- #region IDisposable Members /// <summary> /// Dispose the object. /// </summary> void IDisposable.Dispose() { this.Dispose(); } #endregion IDisposable Members } }
37.904717
176
0.486797
[ "Apache-2.0" ]
295007712/295007712.github.io
sourceCode/dotNet4.6/wpf/src/Framework/System/Windows/Controls/Primitives/DocumentPageView.cs
40,179
C#
// Copyright © 2017 Dmitry Sikorsky. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; using System.Linq; using ExtCore.Data.EntityFramework; using Microsoft.EntityFrameworkCore; using Platformus.Barebone.Data.Extensions; using Platformus.ECommerce.Data.Abstractions; using Platformus.ECommerce.Data.Entities; namespace Platformus.ECommerce.Data.EntityFramework.SqlServer { /// <summary> /// Implements the <see cref="IPositionRepository"/> interface and represents the repository /// for manipulating the <see cref="Position"/> entities in the context of SQL Server database. /// </summary> public class PositionRepository : RepositoryBase<Position>, IPositionRepository { /// <summary> /// Gets the position by the identifier. /// </summary> /// <param name="id">The unique identifier of the position.</param> /// <returns>Found position with the given identifier.</returns> public Position WithKey(int id) { return this.dbSet.Find(id); } /// <summary> /// Gets the positions filtered by the cart identifier using sorting by identifier (ascending). /// </summary> /// <param name="cartId">The unique identifier of the cart these positions belongs to.</param> /// <returns>Found positions.</returns> public IEnumerable<Position> FilteredByCartId(int cartId) { return this.dbSet.AsNoTracking().Where(p => p.CartId == cartId).OrderBy(p => p.Id); } /// <summary> /// Gets the positions filtered by the cart identifier using the given filtering, sorting, and paging. /// </summary> /// <param name="cartId">The unique identifier of the cart these positions belongs to.</param> /// <param name="orderBy">The position property name to sort by.</param> /// <param name="direction">The sorting direction.</param> /// <param name="skip">The number of positions that should be skipped.</param> /// <param name="take">The number of positions that should be taken.</param> /// <param name="filter">The filtering query.</param> /// <returns>Found positions using the given filtering, sorting, and paging.</returns> public IEnumerable<Position> Range(int cartId, string orderBy, string direction, int skip, int take, string filter) { return this.GetFilteredPositions(dbSet.AsNoTracking(), cartId, filter).OrderBy(orderBy, direction).Skip(skip).Take(take); } /// <summary> /// Creates the position. /// </summary> /// <param name="position">The position to create.</param> public void Create(Position position) { this.dbSet.Add(position); } /// <summary> /// Edits the position. /// </summary> /// <param name="position">The position to edit.</param> public void Edit(Position position) { this.storageContext.Entry(position).State = EntityState.Modified; } /// <summary> /// Deletes the position specified by the identifier. /// </summary> /// <param name="id">The unique identifier of the position to delete.</param> public void Delete(int id) { this.Delete(this.WithKey(id)); } /// <summary> /// Deletes the position. /// </summary> /// <param name="position">The position to delete.</param> public void Delete(Position position) { this.dbSet.Remove(position); } /// <summary> /// Counts the number of the positions filtered by the cart identifier with the given filtering. /// </summary> /// <param name="cartId">The unique identifier of the cart these positions belongs to.</param> /// <param name="filter">The filtering query.</param> /// <returns>The number of positions found.</returns> public int Count(int cartId, string filter) { return this.GetFilteredPositions(dbSet, cartId, filter).Count(); } private IQueryable<Position> GetFilteredPositions(IQueryable<Position> positions, int cartId, string filter) { positions = positions.Where(p => p.CartId == cartId); if (string.IsNullOrEmpty(filter)) return positions; return positions.Where(p => true); } } }
37.892857
127
0.677191
[ "Apache-2.0" ]
5118234/Platformus
src/Platformus.ECommerce.Data.EntityFramework.SqlServer/PositionRepository.cs
4,247
C#
using System; using System.Threading.Tasks; using ConfigureAwaitChecker.Tests; using ConfigureAwaitChecker.Tests.TestClasses; [CheckerTests.ExpectedResult(new[] { true })] public class SimpleLambdaWithBraces_Missing : TestClassBase { #pragma warning disable 1998 public async Task FooBar() #pragma warning restore 1998 { var func = (Func<Task>)(async () => await (Task.Delay(1))); } }
24.5
61
0.765306
[ "MIT" ]
pmiossec/ConfigureAwaitChecker
ConfigureAwaitChecker.Tests/TestClasses/SimpleLambdaWithBraces_Missing.cs
394
C#
// <auto-generated> // automatically generated by the FlatBuffers compiler, do not modify // </auto-generated> namespace KeywordTest { using global::System; using global::System.Collections.Generic; using global::FlatBuffers; public struct KeywordsInTable : IFlatbufferObject { private Table __p; public ByteBuffer ByteBuffer { get { return __p.bb; } } public static void ValidateVersion() { FlatBufferConstants.FLATBUFFERS_2_0_0(); } public static KeywordsInTable GetRootAsKeywordsInTable(ByteBuffer _bb) { return GetRootAsKeywordsInTable(_bb, new KeywordsInTable()); } public static KeywordsInTable GetRootAsKeywordsInTable(ByteBuffer _bb, KeywordsInTable obj) { return (obj.__assign(_bb.GetInt(_bb.Position) + _bb.Position, _bb)); } public void __init(int _i, ByteBuffer _bb) { __p = new Table(_i, _bb); } public KeywordsInTable __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; } public KeywordTest.ABC Is { get { int o = __p.__offset(4); return o != 0 ? (KeywordTest.ABC)__p.bb.GetInt(o + __p.bb_pos) : KeywordTest.ABC.@void; } } public bool MutateIs(KeywordTest.ABC @is) { int o = __p.__offset(4); if (o != 0) { __p.bb.PutInt(o + __p.bb_pos, (int)@is); return true; } else { return false; } } public KeywordTest.@public Private { get { int o = __p.__offset(6); return o != 0 ? (KeywordTest.@public)__p.bb.GetInt(o + __p.bb_pos) : KeywordTest.@public.NONE; } } public bool MutatePrivate(KeywordTest.@public @private) { int o = __p.__offset(6); if (o != 0) { __p.bb.PutInt(o + __p.bb_pos, (int)@private); return true; } else { return false; } } public int Type { get { int o = __p.__offset(8); return o != 0 ? __p.bb.GetInt(o + __p.bb_pos) : (int)0; } } public bool MutateType(int type) { int o = __p.__offset(8); if (o != 0) { __p.bb.PutInt(o + __p.bb_pos, type); return true; } else { return false; } } public static Offset<KeywordTest.KeywordsInTable> CreateKeywordsInTable(FlatBufferBuilder builder, KeywordTest.ABC @is = KeywordTest.ABC.@void, KeywordTest.@public @private = KeywordTest.@public.NONE, int type = 0) { builder.StartTable(3); KeywordsInTable.AddType(builder, type); KeywordsInTable.AddPrivate(builder, @private); KeywordsInTable.AddIs(builder, @is); return KeywordsInTable.EndKeywordsInTable(builder); } public static void StartKeywordsInTable(FlatBufferBuilder builder) { builder.StartTable(3); } public static void AddIs(FlatBufferBuilder builder, KeywordTest.ABC @is) { builder.AddInt(0, (int)@is, 0); } public static void AddPrivate(FlatBufferBuilder builder, KeywordTest.@public @private) { builder.AddInt(1, (int)@private, 0); } public static void AddType(FlatBufferBuilder builder, int type) { builder.AddInt(2, type, 0); } public static Offset<KeywordTest.KeywordsInTable> EndKeywordsInTable(FlatBufferBuilder builder) { int o = builder.EndTable(); return new Offset<KeywordTest.KeywordsInTable>(o); } public KeywordsInTableT UnPack() { var _o = new KeywordsInTableT(); this.UnPackTo(_o); return _o; } public void UnPackTo(KeywordsInTableT _o) { _o.Is = this.Is; _o.Private = this.Private; _o.Type = this.Type; } public static Offset<KeywordTest.KeywordsInTable> Pack(FlatBufferBuilder builder, KeywordsInTableT _o) { if (_o == null) return default(Offset<KeywordTest.KeywordsInTable>); return CreateKeywordsInTable( builder, _o.Is, _o.Private, _o.Type); } } public class KeywordsInTableT { [Newtonsoft.Json.JsonProperty("is")] public KeywordTest.ABC Is { get; set; } [Newtonsoft.Json.JsonProperty("private")] public KeywordTest.@public Private { get; set; } [Newtonsoft.Json.JsonProperty("type")] public int Type { get; set; } public KeywordsInTableT() { this.Is = KeywordTest.ABC.@void; this.Private = KeywordTest.@public.NONE; this.Type = 0; } } }
45.255814
184
0.712744
[ "Apache-2.0" ]
0gap/flatbuffers
tests/KeywordTest/KeywordsInTable.cs
3,892
C#
using System; using System.Linq; using System.Collections.Generic; using System.Runtime.InteropServices; using Torque3D.Engine; using Torque3D.Util; namespace Torque3D { public unsafe class sgLightObjectData : GameBaseData { public sgLightObjectData(bool pRegister = false) : base(pRegister) { } public sgLightObjectData(string pName, bool pRegister = false) : this(false) { Name = pName; if (pRegister) registerObject(); } public sgLightObjectData(string pName, string pParent, bool pRegister = false) : this(pName, pRegister) { CopyFrom(Sim.FindObject<SimObject>(pParent)); } public sgLightObjectData(string pName, SimObject pParent, bool pRegister = false) : this(pName, pRegister) { CopyFrom(pParent); } public sgLightObjectData(SimObject pObj) : base(pObj) { } public sgLightObjectData(IntPtr pObjPtr) : base(pObjPtr) { } protected override void CreateSimObjectPtr() { ObjectPtr = InternalUnsafeMethods.sgLightObjectData_create(); } #region UnsafeNativeMethods new internal struct InternalUnsafeMethods { [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate IntPtr _sgLightObjectData_create(); private static _sgLightObjectData_create _sgLightObjectData_createFunc; internal static IntPtr sgLightObjectData_create() { if (_sgLightObjectData_createFunc == null) { _sgLightObjectData_createFunc = (_sgLightObjectData_create)Marshal.GetDelegateForFunctionPointer(Torque3D.DllLoadUtils.GetProcAddress(Torque3D.Torque3DLibHandle, "fn_sgLightObjectData_create"), typeof(_sgLightObjectData_create)); } return _sgLightObjectData_createFunc(); } } #endregion #region Functions #endregion #region Properties #endregion } }
22.670455
141
0.672682
[ "MIT" ]
lukaspj/T3D-CSharp-Tools
BaseLibrary/Torque3D/Engine/sgLightObjectData.cs
1,995
C#
using System; using System.Threading.Tasks; using Microsoft.Azure.WebJobs; using Microsoft.Extensions.Logging; using System.Linq; using System.Net.Http; using System.IO; using Newtonsoft.Json; using Microsoft.AspNetCore.Http; using Microsoft.Azure.WebJobs.Extensions.Http; using Hanselman.Functions.Helpers; // LotanB cheered 5 May 17, 2019 // LotanB cheered 10 May 17, 2019 // ElectricHavoc cheered 5 May 17, 2019 // ElectricHavoc cheered 295 May 17, 2019 // LotanB gifted 3 subs May 17, 2019 // ClintonRocksmith cheered 100 June 14, 2019 // ClintonRocksmith cheered 3000 June 14, 2019 namespace Hanselman.Functions { public static class TimerFunctions { [FunctionName(nameof(GetBlogFeed))] public static HttpResponseMessage GetBlogFeed( [HttpTrigger(AuthorizationLevel.Function, "get", Route = null)]HttpRequest req, [Blob("hanselman/blog.json", FileAccess.Read, Connection = "AzureWebJobsStorage")]Stream inBlob, ILogger log) { return BlobHelpers.BlobToHttpResponseMessage(inBlob, log, "blog"); } [FunctionName(nameof(GetBlogLastUpdate))] public static HttpResponseMessage GetBlogLastUpdate( [HttpTrigger(AuthorizationLevel.Function, "get", Route = null)]HttpRequest req, [Blob("hanselman/blog-lastupdate.json", FileAccess.Read, Connection = "AzureWebJobsStorage")]Stream inBlob, ILogger log) { return BlobHelpers.BlobToHttpResponseMessage(inBlob, log, "blog"); } [FunctionName(nameof(BlogUpdate))] public static async Task BlogUpdate( [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)]HttpRequest req, [Blob("hanselman/blog.json", FileAccess.Write, Connection = "AzureWebJobsStorage")]Stream outBlogBlob, [Blob("hanselman/blog-lastupdate.json", FileAccess.Write, Connection = "AzureWebJobsStorage")]Stream outLastUpdateBlog, [Blob("hanselman/blog-lastupdate.json", FileAccess.Read, Connection = "AzureWebJobsStorage")]Stream inLastUpdateBlog, [HttpClientFactory]HttpClient client, ILogger log) { var feedurl = "http://feeds.hanselman.com/ScottHanselman"; try { log.LogInformation("Getting blog feed."); var feed = await client.GetStringAsync(feedurl); log.LogInformation("Parsing blog feed."); var blogItems = FeedItemHelpers.ParseBlogFeed(feed); var pubDate = blogItems.FirstOrDefault()?.PublishDate; if (TimeHelpers.CheckIfNewEntry(outLastUpdateBlog, inLastUpdateBlog, log, pubDate)) { //Send push notification log.LogInformation("Parsing blog feed."); } var json = JsonConvert.SerializeObject(blogItems, Formatting.None); log.LogInformation("Writting feed to blob."); using (var writer = new StreamWriter(outBlogBlob)) { writer.Write(json); } log.LogInformation("Blog function finished."); } catch (Exception ex) { log.LogError(ex, "Unable to get blog feed"); } } } }
36.483871
131
0.628352
[ "MIT" ]
jonathanpeppers/Hanselman.Forms
src/Hanselman.Functions/Triggers/BlogFunctions.cs
3,393
C#
namespace EightOffSolitaireCP.Data; [SingletonGame] public class BasicData : IGameInfo, ISolitaireData { EnumSolitaireMoveType ISolitaireData.MoveColumns => EnumSolitaireMoveType.OneCardOnly; //this is default. can change to what i want. int ISolitaireData.WasteColumns => 0; int ISolitaireData.WasteRows => 0; int ISolitaireData.WastePiles => 8; //default is 7. can change to what it really is. int ISolitaireData.Rows => 1; int ISolitaireData.Columns => 4; bool ISolitaireData.IsKlondike => false; int ISolitaireData.CardsNeededWasteBegin => 48; int ISolitaireData.CardsNeededMainBegin => 4; int ISolitaireData.Deals => -1; int ISolitaireData.CardsToDraw => 1; bool ISolitaireData.SuitsNeedToMatchForMainPile => true; bool ISolitaireData.ShowNextNeededOnMain => false; bool ISolitaireData.MainRound => false; //if its round suits; then will be true EnumGameType IGameInfo.GameType => EnumGameType.NewGame; bool IGameInfo.CanHaveExtraComputerPlayers => false; EnumPlayerChoices IGameInfo.SinglePlayerChoice => EnumPlayerChoices.Solitaire; EnumPlayerType IGameInfo.PlayerType => EnumPlayerType.SingleOnly; string IGameInfo.GameName => "Eight Off Solitaire"; //replace with real name. int IGameInfo.NoPlayers => 0; int IGameInfo.MinPlayers => 0; int IGameInfo.MaxPlayers => 0; bool IGameInfo.CanAutoSave => true; EnumSuggestedOrientation IGameInfo.SuggestedOrientation => EnumSuggestedOrientation.Landscape; //most solitaire games has to be landscape. EnumSmallestSuggested IGameInfo.SmallestSuggestedSize => EnumSmallestSuggested.AnyDevice; }
31.45283
142
0.754649
[ "MIT" ]
musictopia2/GamingPackXV3
CP/Games/EightOffSolitaireCP/Data/BasicData.cs
1,667
C#
using System.Reflection; using System.Runtime.Serialization.Json; using EssentialUIKit.ViewModels.Tracking; namespace EssentialUIKit.DataService { public class TrainStatusDataService { #region Fields private static TrainStatusDataService trainStatusDataService; private TrainStatusPageViewModel trainStatusPageViewModel; #endregion #region Properties /// <summary> /// Gets an instance of the <see cref="TrainStatusDataService"/>. /// </summary> public static TrainStatusDataService Instance => trainStatusDataService ?? (trainStatusDataService = new TrainStatusDataService()); /// <summary> /// Gets or sets the value of train status page view model. /// </summary> public TrainStatusPageViewModel TrainStatusPageViewModel => this.trainStatusPageViewModel = PopulateData<TrainStatusPageViewModel>("trainstatus.json"); #endregion #region Methods /// <summary> /// Populates the data for view model from json file. /// </summary> /// <typeparam name="T">Type of view model.</typeparam> /// <param name="fileName">Json file to fetch data.</param> /// <returns>Returns the view model object.</returns> private static T PopulateData<T>(string fileName) { var file = "EssentialUIKit.Data." + fileName; var assembly = typeof(App).GetTypeInfo().Assembly; T data; using (var stream = assembly.GetManifestResourceStream(file)) { var serializer = new DataContractJsonSerializer(typeof(T)); data = (T)serializer.ReadObject(stream); } return data; } #endregion } }
30.15
139
0.627418
[ "MIT" ]
Boolynn/essential-ui-kit-for-xamarin.forms
EssentialUIKit/DataService/TrainStatusDataService.cs
1,811
C#
using Flurl; using Flurl.Http; using Vulder.Timetable.Core; using Vulder.Timetable.Infrastructure.Api.Models; namespace Vulder.Timetable.Infrastructure.Api; public static class SchoolApi { public static async Task<GetSchoolResponse> GetSchoolModel(Guid? schoolId) { return await Constants.BaseApiUrl .AppendPathSegment("/school/GetSchool") .SetQueryParam("schoolId", schoolId) .WithClient(new FlurlClient(new HttpClient(new HttpClientHandler { ServerCertificateCustomValidationCallback = (_, _, _, _) => true }))) .GetAsync() .ReceiveJson<GetSchoolResponse>(); } }
31.181818
80
0.663265
[ "Apache-2.0" ]
VulderApp/Timetable
src/Vulder.Timetable.Infrastructure/Api/SchoolApi.cs
686
C#
using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.Linq; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Classification; using Microsoft.VisualStudio.Utilities; namespace Redwood.VS2013Extension.RwHtmlEditorExtensions.Classification { [Export(typeof(IClassifierProvider))] [ContentType("htmlx")] internal class RwHtmlClassifierProvider : IClassifierProvider { [Import] internal IClassificationTypeRegistryService Registry = null; public IClassifier GetClassifier(ITextBuffer textBuffer) { return textBuffer.Properties.GetOrCreateSingletonProperty(() => new RwHtmlClassifier(Registry, textBuffer)); } } }
30.12
120
0.759628
[ "Apache-2.0" ]
exyi/redwood
src/Redwood.VS2013Extension/RwHtmlEditorExtensions/Classification/RwHtmlClassifierProvider.cs
755
C#
using System; using System.Collections; using System.Collections.Generic; using System.Runtime.Serialization; using JsonSubTypes; using Newtonsoft.Json; using Bitmovin.Api.Sdk.Common; using Bitmovin.Api.Sdk.Models; namespace Bitmovin.Api.Sdk.Models { /// <summary> /// EnhancedDeinterlaceFilter /// </summary> public class EnhancedDeinterlaceFilter : Filter { [JsonProperty(PropertyName = "type")] private readonly string _type = "ENHANCED_DEINTERLACE"; /// <summary> /// Parity /// </summary> [JsonProperty(PropertyName = "parity")] public EnhancedDeinterlaceParity? Parity { get; set; } /// <summary> /// Mode /// </summary> [JsonProperty(PropertyName = "mode")] public EnhancedDeinterlaceMode? Mode { get; set; } /// <summary> /// AutoEnable /// </summary> [JsonProperty(PropertyName = "autoEnable")] public EnhancedDeinterlaceAutoEnable? AutoEnable { get; set; } } }
25.9
70
0.627413
[ "MIT" ]
bitmovin/bitmovin-api-sdk-dotnet
src/Bitmovin.Api.Sdk/Models/EnhancedDeinterlaceFilter.cs
1,036
C#
/* * _____ ______ * /_ / ____ ____ ____ _________ / __/ /_ * / / / __ \/ __ \/ __ \/ ___/ __ \/ /_/ __/ * / /__/ /_/ / / / / /_/ /\_ \/ /_/ / __/ /_ * /____/\____/_/ /_/\__ /____/\____/_/ \__/ * /____/ * * Authors: * 钟峰(Popeye Zhong) <zongsoft@gmail.com> * * Copyright (C) 2010-2020 Zongsoft Studio <http://www.zongsoft.com> * * This file is part of Zongsoft.Commands library. * * The Zongsoft.Commands is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3.0 of the License, * or (at your option) any later version. * * The Zongsoft.Commands is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the Zongsoft.Commands library. If not, see <http://www.gnu.org/licenses/>. */ using System; using System.Linq; using System.ComponentModel; using Microsoft.Extensions.Configuration; using Zongsoft.Services; namespace Zongsoft.Configuration.Commands { [DisplayName("Text.ConfigurationCommand.Name")] [Description("Text.ConfigurationCommand.Description")] public class ConfigurationCommand : CommandBase<CommandContext> { #region 成员字段 private IConfiguration _configuration; #endregion #region 构造函数 public ConfigurationCommand() : base("Options") { _configuration = Zongsoft.Services.ApplicationContext.Current.Configuration; } public ConfigurationCommand(string name) : base(name) { _configuration = Zongsoft.Services.ApplicationContext.Current.Configuration; } #endregion #region 公共属性 public IConfiguration Configuration { get => _configuration; set => _configuration = value ?? throw new ArgumentNullException(); } #endregion #region 执行方法 protected override object OnExecute(CommandContext context) { if(context.Parameter is IConfiguration configuration) _configuration = configuration; //打印配置信息 Print(_configuration, context.Output, false, 0); return _configuration; } #endregion #region 静态方法 internal static IConfiguration GetConfiguration(CommandTreeNode node) { if(node == null) return null; if(node.Command is ConfigurationCommand command) return command.Configuration; return GetConfiguration(node.Parent); } internal static void Print(IConfiguration configuration, ICommandOutlet output, bool simplify, int depth) { if(configuration == null) return; if(configuration is IConfigurationRoot root) { int index = 0; foreach(var provider in root.Providers) { output.WriteLine(CommandOutletContent .Create(CommandOutletColor.Gray, $"[{++index}] ") .AppendLine(CommandOutletColor.DarkYellow, provider.GetType().FullName) .Append(CommandOutletColor.DarkGray, provider.ToString()) ); var keys = provider.GetChildKeys(Array.Empty<string>(), null).Distinct(StringComparer.OrdinalIgnoreCase); foreach(var key in keys) { output.WriteLine("\t" + key); } if(keys.Any()) output.WriteLine(); } } else if(configuration is IConfigurationSection section) { if(depth > 0) output.Write(new string(' ', depth * 4)); if(section.Value == null) { if(depth > 0 && simplify) output.WriteLine(CommandOutletColor.DarkYellow, section.Key); else output.WriteLine(CommandOutletColor.DarkYellow, section.Path); } else { var content = simplify ? CommandOutletContent.Create("") : CommandOutletContent.Create(CommandOutletColor.DarkGreen, ConfigurationPath.GetParentPath(section.Path)) .Append(CommandOutletColor.DarkCyan, ":"); output.WriteLine(content .Append(CommandOutletColor.Green, section.Key) .Append(CommandOutletColor.DarkMagenta, "=") .Append(CommandOutletColor.DarkGray, section.Value) ); } foreach(var child in section.GetChildren()) { Print(child, output, simplify, depth + 1); } } } #endregion } }
27.916667
110
0.685419
[ "MIT" ]
Zongsoft/Zongsoft.Framework
Zongsoft.Commands/src/Configuration/ConfigurationCommand.cs
4,413
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace WPF_Application { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } } }
22.678571
45
0.71811
[ "MIT" ]
Daniel-Svensson/MSBuildSdkExtras
TestProjects/Windows-Desktop-C#/WPF-Application/MainWindow.xaml.cs
635
C#
namespace AsterNET.Manager.Event { /// <summary> /// A LeaveEvent is triggered when a channel leaves a queue.<br/> /// It is implemented in apps/app_queue.c /// </summary> public class LeaveEvent : QueueEvent { public LeaveEvent(ManagerConnection source) : base(source) { } } }
20.928571
66
0.68942
[ "MIT" ]
1stco/AsterNET
Asterisk.2013/OldAsterNET/Asterisk.NET/Manager/Event/LeaveEvent.cs
293
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PacmanEsimerkki4 { class Esimerkki4Program { static void Main(string[] args) { /** * Esimerkki4Program.cs * * Jos EN TUNTISI ohjelmoinnista seuraavia konsepteja: * - Luokan parametrillinen rakentaja * - Rajapinta ja rajapinnan toteutus * * Jos TUNNEN ohjelmoinnista seuraavan konseptin: * - Staattinen luokan metodi tai staattinen luokan muuttuja * - Parametrilliset metodit * * niin silloin toteutus olisi esimerkin näköinen. * Katso kohdat läpi ja siirry Esimerkki5Program.cs ohjelmaan. * * Esimerkki on aivan sama kuin edellinen esimerkki 3. Nyt erona * on se, että jatketaan saman opitun asian hyödyntämistä ja * tehdään Hedelmä luokan Katoa()-metodista myös parametrillinen, * joka ottaa vastaan packan olion. * * Nyt ohjelma on ihan toimiva ja käytännöllinen. Hedelma-luokan * Katoa()-metodissa on kerrottu asiasta lisää. Tämän hyvä * puoli on se, ettei tehdä mitään outoa kikkailua, joka voisi * myöhemmin aiheuttaa outoja bugeja ja ongelmia. * * Tässäkin on huonot puolensa ja yksi esimerkki on vielä * kerrottu seuraavassa viimeisessä esimerkissä. Siinä päästään * hieman pienempään riippuvuuteen luokkien kesken, koska nyt * Hedelmä luokka tietää, että Packman luokka on olemassa ja toisinpäin. * Tällöin puhutaan myös vahvasta riippuvuudesta mikä välillä * tuo suuremmissa ohjelmissa ongelmia. * * Tätä suosittelisin eniten. Seuraava esimerkki on vielä parempi * mutta en tiedä kuinka ymmärrettävä se on. * **/ Pacman pacman1 = new Pacman(); // Luodaan uusi pacman1 olio Hedelma hedelma1 = new Hedelma(); // Luodaan hedelma1 olio Hedelma hedelma2 = new Hedelma(); // Luodaan hedelma2 olio Hedelma hedelma3 = new Hedelma(); // Luodaan hedelma3 olio pacman1.Syo(hedelma1); // kutsutaan olion Syo-metodia pacman1.Syo(hedelma2); // kutsutaan olion Syo-metodia pacman1.Syo(hedelma3); // kutsutaan olion Syo-metodia Console.WriteLine(pacman1.pisteet); Pacman pacman2 = new Pacman(); // Luodaan uusi pacman2 olio Hedelma hedelma4 = new Hedelma(); Hedelma hedelma5 = new Hedelma(); pacman2.Syo(hedelma4); pacman2.Syo(hedelma5); Console.WriteLine(pacman2.pisteet); Console.ReadKey(); } } class Pacman { public int pisteet; // packan luokan staattinen ominaisuus public Pacman() { pisteet = 0; // pisteet muuttujan alustus rakentajassa } public void TulostaTiedot() { Console.WriteLine(pisteet); } public void Syo(Hedelma hedelma) { Console.WriteLine("Hedelmä syöty"); // Huomaa tässä this. // This viittaa olioon itseensä, joten tässä kohdin // hedelmän Katoa() metodille annetaan nykyinen olio mikä // alunperin tätä Syo()-metodia kutsuu. Tällainen rakenne // ei ole kovin harvinainen mutta melko hyödyllinen ja // tehokas oikein käytettynä. hedelma.Katoa(this); } } class Hedelma { public bool nakyvissa; // ominaisuus näkyvyyden määrittämiseen public Hedelma() { nakyvissa = true; // nakyvissa muuttujan alustus rakentajassa } public void Katoa(Pacman pacman) { // Nyt voimme kutsua täällä packman olion pisteet muuttujaa // ja kasvattaa sitä yhdellä. Eli kun packan olio välitetään // parametrina niin kyse on samasta oliosta mikä on jo luotu // pääohjelmassa. Kun olio tai luokka annetaan parametrina // niin tietoa ei kopioida vaan tässä viitataan käytännössä // siihen muistipaikkaan missä olio on ohjelman muistissa ja // sieltä löytyy oikea olio. // // Vertaa tätä kun parametrina on jokin perustietotyyppi, // esimerkiksi int tai double. Näiden perustietotyyppien kohdalla // parametri käsitellään eri tavoin ja siitä luodaan kopio // kun se annetaan parametrina. nakyvissa = false; Console.WriteLine("Hedelmä piilotettu"); pacman.pisteet++; // tämä olio on siis se "this" kun Katoa()-metodia kutsutaan. } } }
38.869231
92
0.580843
[ "MIT" ]
nyluntu/PacmanEsimerkki
PacmanEsimerkki/Esimerkki4Program.cs
5,157
C#
// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // 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 Google.Api.Ads.AdWords.v201809; using NUnit.Framework; using CSharpExamples = Google.Api.Ads.AdWords.Examples.CSharp.v201809; using VBExamples = Google.Api.Ads.AdWords.Examples.VB.v201809; namespace Google.Api.Ads.AdWords.Tests.v201809 { /// <summary> /// Test cases for all the code examples under v201809\Migration. /// </summary> internal class MigrationTest : VersionedExampleTestsBase { private long campaignId; private long adGroupId; private long adId; /// <summary> /// Inits this instance. /// </summary> [SetUp] public void Init() { campaignId = utils.CreateSearchCampaign(user, BiddingStrategyType.MANUAL_CPC); adGroupId = utils.CreateAdGroup(user, campaignId); adId = utils.CreateExpandedTextAd(user, adGroupId, false); } /// <summary> /// Tests the MigrateToExtensionSettings VB.NET code example. /// </summary> [Test] public void MigrateToExtensionSettingsVBExample() { RunExample(delegate() { new VBExamples.MigrateToExtensionSettings().Run(user); }); } /// <summary> /// Tests the MigrateToExtensionSettings C# code example. /// </summary> [Test] public void MigrateToExtensionSettingsCSharpExample() { RunExample(delegate() { new CSharpExamples.MigrateToExtensionSettings().Run(user); }); } } }
33.15873
98
0.657731
[ "Apache-2.0" ]
CoryLiseno/googleads-dotnet-lib
tests/AdWords/v201809/MigrationTest.cs
2,091
C#
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ namespace Microsoft.ServiceFabric.Client.Http.Serialization { using System; using System.Collections.Generic; using Microsoft.ServiceFabric.Common; using Newtonsoft.Json; using Newtonsoft.Json.Linq; /// <summary> /// Converter for <see cref="ApplicationUpgradeUpdateDescription" />. /// </summary> internal class ApplicationUpgradeUpdateDescriptionConverter { /// <summary> /// Deserializes the JSON representation of the object. /// </summary> /// <param name="reader">The <see cref="T: Newtonsoft.Json.JsonReader" /> to read from.</param> /// <returns>The object Value.</returns> internal static ApplicationUpgradeUpdateDescription Deserialize(JsonReader reader) { return reader.Deserialize(GetFromJsonProperties); } /// <summary> /// Gets the object from Json properties. /// </summary> /// <param name="reader">The <see cref="T: Newtonsoft.Json.JsonReader" /> to read from, reader must be placed at first property.</param> /// <returns>The object Value.</returns> internal static ApplicationUpgradeUpdateDescription GetFromJsonProperties(JsonReader reader) { var name = default(ApplicationName); var upgradeKind = default(UpgradeKind?); var applicationHealthPolicy = default(ApplicationHealthPolicy); var updateDescription = default(RollingUpgradeUpdateDescription); do { var propName = reader.ReadPropertyName(); if (string.Compare("Name", propName, StringComparison.Ordinal) == 0) { name = ApplicationNameConverter.Deserialize(reader); } else if (string.Compare("UpgradeKind", propName, StringComparison.Ordinal) == 0) { upgradeKind = UpgradeKindConverter.Deserialize(reader); } else if (string.Compare("ApplicationHealthPolicy", propName, StringComparison.Ordinal) == 0) { applicationHealthPolicy = ApplicationHealthPolicyConverter.Deserialize(reader); } else if (string.Compare("UpdateDescription", propName, StringComparison.Ordinal) == 0) { updateDescription = RollingUpgradeUpdateDescriptionConverter.Deserialize(reader); } else { reader.SkipPropertyValue(); } } while (reader.TokenType != JsonToken.EndObject); return new ApplicationUpgradeUpdateDescription( name: name, upgradeKind: upgradeKind, applicationHealthPolicy: applicationHealthPolicy, updateDescription: updateDescription); } /// <summary> /// Serializes the object to JSON. /// </summary> /// <param name="writer">The <see cref="T: Newtonsoft.Json.JsonWriter" /> to write to.</param> /// <param name="obj">The object to serialize to JSON.</param> internal static void Serialize(JsonWriter writer, ApplicationUpgradeUpdateDescription obj) { // Required properties are always serialized, optional properties are serialized when not null. writer.WriteStartObject(); writer.WriteProperty(obj.UpgradeKind, "UpgradeKind", UpgradeKindConverter.Serialize); writer.WriteProperty(obj.Name, "Name", ApplicationNameConverter.Serialize); if (obj.ApplicationHealthPolicy != null) { writer.WriteProperty(obj.ApplicationHealthPolicy, "ApplicationHealthPolicy", ApplicationHealthPolicyConverter.Serialize); } if (obj.UpdateDescription != null) { writer.WriteProperty(obj.UpdateDescription, "UpdateDescription", RollingUpgradeUpdateDescriptionConverter.Serialize); } writer.WriteEndObject(); } } }
44.363636
144
0.59745
[ "MIT" ]
aL3891/service-fabric-client-dotnet
src/Microsoft.ServiceFabric.Client.Http/Serialization/ApplicationUpgradeUpdateDescriptionConverter.cs
4,392
C#
using Microsoft.AspNet.Identity; using Microsoft.Owin; using Microsoft.Owin.Security.Cookies; using Owin; namespace WebApplication24 { public partial class Startup { // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864 public void ConfigureAuth(IAppBuilder app) { // Enable the application to use a cookie to store information for the signed in user app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, LoginPath = new PathString("/Account/Login") }); // Use a cookie to temporarily store information about a user logging in with a third party login provider app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie); // Uncomment the following lines to enable logging in with third party login providers //app.UseMicrosoftAccountAuthentication( // clientId: "", // clientSecret: ""); //app.UseTwitterAuthentication( // consumerKey: "", // consumerSecret: ""); //app.UseFacebookAuthentication( // appId: "", // appSecret: ""); //app.UseGoogleAuthentication(); } } }
37.236842
121
0.625442
[ "Apache-2.0" ]
JannekeliCosta/MyBrendanForsterWebApplication
danger/seriously/WebApplication24/App_Start/Startup.Auth.cs
1,417
C#
using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using ModernDev.InTouch; using VKSaver.Core.ViewModels; namespace VKSaver.Common { public sealed class VKAudioSeeMoreTemplateSelector : DataTemplateSelector { public DataTemplate AudioTemplate { get; set; } public DataTemplate SeeAlsoTemplate { get; set; } protected override DataTemplate SelectTemplateCore(object item, DependencyObject container) { var audio = item as Audio; if (audio == null) return null; if (audio.Title == MainViewModel.VKSAVER_SEE_ALSO_TEXT) return SeeAlsoTemplate; return AudioTemplate; } } }
28.36
99
0.654443
[ "Apache-2.0" ]
RomanGL/VKSaver
VKSaver2/VKSaver/VKSaver.UWP/Common/VKAudioSeeMoreTemplateSelector.cs
711
C#
namespace MassTransit.Pipeline.Pipes { using System; using System.Collections.Concurrent; using System.Diagnostics; using System.Threading.Tasks; using GreenPipes; using SendPipeSpecifications; public class SendPipe : ISendPipe { readonly ConcurrentDictionary<Type, IMessagePipe> _outputPipes; readonly ISendPipeSpecification _specification; public SendPipe(ISendPipeSpecification specification) { _specification = specification; _outputPipes = new ConcurrentDictionary<Type, IMessagePipe>(); } void IProbeSite.Probe(ProbeContext context) { var scope = context.CreateScope("sendPipe"); foreach (var outputPipe in _outputPipes.Values) outputPipe.Probe(scope); } [DebuggerNonUserCode] [DebuggerStepThrough] Task ISendContextPipe.Send<T>(SendContext<T> context) { return _outputPipes.GetOrAdd(typeof(T), x => new MessagePipe<T>(_specification.GetMessageSpecification<T>())).Send(context); } interface IMessagePipe : IProbeSite { Task Send<T>(SendContext<T> context) where T : class; } class MessagePipe<TMessage> : IMessagePipe where TMessage : class { readonly Lazy<IMessageSendPipe<TMessage>> _output; readonly IMessageSendPipeSpecification<TMessage> _specification; public MessagePipe(IMessageSendPipeSpecification<TMessage> specification) { _specification = specification; _output = new Lazy<IMessageSendPipe<TMessage>>(CreateFilter); } Task IMessagePipe.Send<T>(SendContext<T> context) { return _output.Value.Send((SendContext<TMessage>)context); } public void Probe(ProbeContext context) { _output.Value.Probe(context); } IMessageSendPipe<TMessage> CreateFilter() { IPipe<SendContext<TMessage>> messagePipe = _specification.BuildMessagePipe(); return new MessageSendPipe<TMessage>(messagePipe); } } } }
30.0125
137
0.579758
[ "ECL-2.0", "Apache-2.0" ]
Aerodynamite/MassTrans
src/MassTransit/Pipeline/Pipes/SendPipe.cs
2,401
C#
/* Copyright (C) 2012 dbreeze.tiesky.com / Alex Solovyov / Ivars Sudmalis. It's free software for those who think that it should be free. https://github.com/hhblaze/Biser */ using System; using System.Collections.Generic; using System.Linq; using System.Text; //using System.Threading.Tasks; namespace DBreeze.Utils { public static partial class Biser { /// <summary> /// Biser JSON decoder /// </summary> public class JsonDecoder { internal string encoded = null; long len = 0; StringBuilder sb = null; internal int encPos = -1; JsonSettings jsonSettings = null; public JsonDecoder(string encoded, JsonSettings settings = null) { jsonSettings = (settings == null) ? new JsonSettings() : settings; this.encoded = encoded; if (encoded == null || encoded.Length == 0) return; sb = new StringBuilder(); len = encoded.Length; } bool CheckSkip(char c) { return (c == ' ' || c == '\t' || c == '\n' || c == '\r'); } public bool CheckNull() { bool ret = false; bool start = false; while (true) { this.encPos++; if (this.encPos >= len) break; var c = this.encoded[this.encPos]; if (CheckSkip(c)) continue; if (!start) if (c == ',') continue; else start = true; if (!ret) { if (c == 'n' //&& //this.encoded[this.encPos + 1] == 'u' // && //this.encoded[this.encPos + 2] == 'l' // && //this.encoded[this.encPos + 3] == 'l' ) { ret = true; this.encPos += 3; } else { this.encPos--; return false; } } if (c == ',' || c == ']' || c == '}') { this.encPos--; break; } } return ret; } string GetNumber(bool checkNull) { if (checkNull && CheckNull()) return null; bool start = false; #if NET35 sb.Length = 0; #else sb.Clear(); #endif while (true) { this.encPos++; if (this.encPos >= len) break; var c = this.encoded[this.encPos]; if (CheckSkip(c)) continue; if (!start) if (c == ',') continue; else start = true; if (c == ',' || c == ']' || c == '}') { this.encPos--; break; } sb.Append(c); } return sb.ToString(); } string GetBoolean(bool checkNull) { if (checkNull && CheckNull()) return null; bool start = false; #if NET35 sb.Length = 0; #else sb.Clear(); #endif while (true) { this.encPos++; if (this.encPos >= len) break; var c = this.encoded[this.encPos]; if (CheckSkip(c)) continue; if (!start) if (c == ',') continue; else start = true; if (c == ',' || c == ']' || c == '}') { this.encPos--; break; } sb.Append(c); } return sb.ToString(); } /// <summary> /// Must be used as a default call, while analyzing Dictionary key or the Class property /// </summary> public void SkipValue() { bool start = true; char d = ' '; //default for number char o = ' '; int cnt = 0; while (true) { this.encPos++; if (this.encPos >= len) break; var c = this.encoded[this.encPos]; if (CheckSkip(c)) continue; if (start) { if (c == '\"') { d = '\"'; o = '\"'; } else if (c == '[') { d = '['; o = ']'; } else if (c == '{') { d = '{'; o = '}'; } else if (c == 'n') //null { this.encPos += 3; return; } start = false; } else { if (d == ' ' && (c == ',' || c == '}' || c == ']')) { this.encPos--; return; } else if (d == '\"') { if (c == '\\') { this.encPos++; continue; } else if (c == o) return; } else if (d == '[' || d == '{') { if (c == d) { cnt++; } else if (c == o) { if (cnt == 0) return; else cnt--; } } } } } /// <summary> /// Skips : /// </summary> void SkipDelimiter() { while (true) { this.encPos++; if (this.encPos >= len) break; var c = this.encoded[this.encPos]; if (c == ':') return; else continue; } } string GetStr(bool checkNull = true) { if (checkNull && CheckNull()) return null; #if NET35 sb.Length = 0; #else sb.Clear(); #endif bool state = false; //0 - before strting, 1 - inSTring while (true) { this.encPos++; if (this.encPos >= len) break; var c = this.encoded[this.encPos]; if (state) { if (c == '\\') { this.encPos++; c = this.encoded[this.encPos]; } else if (c == '\"') break; sb.Append(c); } else { if (c == '}')//probably end of object, that even didn't start return String.Empty; else if (c == '\"') state = true; continue; } } return sb.ToString(); } /// <summary> /// Returns Key, Value must be retrieved extra /// </summary> /// <typeparam name="K">Dictionary Key type</typeparam> /// <returns></returns> public IEnumerable<K> GetDictionary<K>(bool checkNull = false) { if (checkNull && this.CheckNull()) { } else { char eoc = '}'; //end of collection char soc = '{'; //start of collection int state = 0; //collection start string s; while (true) { this.encPos++; if (this.encPos >= len) break; var c = this.encoded[this.encPos]; if (CheckSkip(c)) continue; if (c == ',') continue; if (c == eoc) break; if (state == 0) { if (c == soc) state = 1; //In collection } else { this.encPos--; } if (state == 1) { s = GetStr(false); SkipDelimiter(); yield return (K)Convert.ChangeType(s, typeof(K)); } } } }//eof public IEnumerable<int> GetList(bool checkNull = false) { if (checkNull && this.CheckNull()) { } else { char eoc = ']'; //end of collection char soc = '['; //start of collection int state = 0; //collection start while (true) { this.encPos++; if (this.encPos >= len) break; var c = this.encoded[this.encPos]; if (CheckSkip(c)) continue; if (c == ',') continue; if (c == eoc) break; if (state == 0) { if (c == soc) state = 1; //In collection } else { this.encPos--; } if (state == 1) { yield return 1; } } } }//eof public DateTime GetDateTime() { return ParseDateTime(); } public DateTime? GetDateTime_NULL() { if (CheckNull()) return null; return ParseDateTime(); } DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); DateTime ParseDateTime() { ulong v; DateTime rdt; string s; switch (this.jsonSettings.DateFormat) { case JsonSettings.DateTimeStyle.Default: //var tt3f = jsts1.P17.ToUniversalTime().Subtract(new DateTime(1970,1,1,0,0,0,DateTimeKind.Utc)).TotalMilliseconds * 10000; /*"\/Date(13257180000000000)\/"*/ s = GetStr(false); // StringBuilder dsb = new StringBuilder(); #if NET35 sb.Length = 0; #else sb.Clear(); #endif for (int i = 6; i < s.Length - 2; i++) sb.Append(s[i]); //v = Convert.ToUInt64(s.Substring(0, s.Length - 2).Replace("/Date(", "")) / 10000; v = Convert.ToUInt64(sb.ToString()) / 10000; //time if not UTC must be brought to UTC, stored in UTC and restored in UTC rdt = epoch.AddMilliseconds(v); return DateTime.SpecifyKind(rdt, DateTimeKind.Utc); case JsonSettings.DateTimeStyle.EpochTime: //var tt3f = jsts1.P17.ToUniversalTime().Subtract(new DateTime(1970,1,1,0,0,0,DateTimeKind.Utc)).TotalMilliseconds * 10000; /*"P17":13257818550000000*/ v = Convert.ToUInt64(GetNumber(false)) / 10000; //time if not UTC must be brought to UTC, stored in UTC and restored in UTC rdt = epoch.AddMilliseconds(v); return DateTime.SpecifyKind(rdt, DateTimeKind.Utc); case JsonSettings.DateTimeStyle.ISO: case JsonSettings.DateTimeStyle.Javascript: /* * Encoder * new DateTime(2018, 6, 5, 17,44,15,443, DateTimeKind.Local).ToString("o"); //Encoder ISO "2018-06-05T17:44:15.4430000Z" or "2018-06-05T17:44:15.4430000+02:00" */ s = GetStr(false); return DateTime.Parse(s, null, System.Globalization.DateTimeStyles.RoundtripKind); } return DateTime.MinValue; } public TimeSpan GetTimeSpan() { var s = GetStr(true); return s == null ? new TimeSpan() : (TimeSpan)TimeSpan.Parse(s); } public int GetInt() { return Int32.Parse(GetNumber(false)); } public int? GetInt_NULL() { var v = GetNumber(true); return v == null ? null : (int?)Int32.Parse(v); } public long GetLong() { return Int64.Parse(GetNumber(false)); } public long? GetLong_NULL() { var v = GetNumber(true); return v == null ? null : (long?)Int64.Parse(v); } public ulong GetULong() { return UInt64.Parse(GetNumber(false)); } public ulong? GetULong_NULL() { var v = GetNumber(true); return v == null ? null : (ulong?)UInt64.Parse(v); } public uint GetUInt() { return UInt32.Parse(GetNumber(false)); } public uint? GetUInt_NULL() { var v = GetNumber(true); return v == null ? null : (uint?)UInt32.Parse(v); } public short GetShort() { return short.Parse(GetNumber(false)); } public short? GetShort_NULL() { var v = GetNumber(true); return v == null ? null : (short?)short.Parse(v); } public ushort GetUShort() { return ushort.Parse(GetNumber(false)); } public ushort? GetUShort_NULL() { var v = GetNumber(true); return v == null ? null : (ushort?)ushort.Parse(v); } public bool GetBool() { var v = GetBoolean(false); return v.Equals("true", StringComparison.OrdinalIgnoreCase) ? true : false; } public bool? GetBool_NULL() { var v = GetBoolean(true); return v == null ? null : (bool?)(v.Equals("true", StringComparison.OrdinalIgnoreCase) ? true : false); } public sbyte GetSByte() { return sbyte.Parse(GetNumber(false)); } public sbyte? GetSByte_NULL() { var v = GetNumber(true); return v == null ? null : (sbyte?)sbyte.Parse(v); } public byte GetByte() { return byte.Parse(GetNumber(false)); } public byte? GetByte_NULL() { var v = GetNumber(true); return v == null ? null : (byte?)byte.Parse(v); } public float GetFloat() { return float.Parse(GetNumber(false), System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture); } public float? GetFloat_NULL() { var v = GetNumber(true); return v == null ? null : (float?)float.Parse(v, System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture); } public double GetDouble() { return double.Parse(GetNumber(false), System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture); } public double? GetDouble_NULL() { var v = GetNumber(true); return v == null ? null : (double?)double.Parse(v, System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture); } public decimal GetDecimal() { return decimal.Parse(GetNumber(false), System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture); } public decimal? GetDecimal_NULL() { var v = GetNumber(true); return v == null ? null : (decimal?)decimal.Parse(v, System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture); } public char GetChar() { return GetStr(false)[0]; } public char? GetChar_NULL() { var v = GetStr(true); return v == null ? null : (char?)v[0]; } public string GetString() { return GetStr(true); } public byte[] GetByteArray() { var v = GetStr(true); return v == null ? null : Convert.FromBase64String(v); } public Guid GetGuid() { var v = GetStr(false); return new Guid(v); } public Guid? GetGuid_NULL() { var v = GetStr(true); return v == null ? null : (Guid?)(new Guid(v)); } }//eoc } }
31.677711
185
0.32804
[ "BSD-2-Clause" ]
ScriptBox99/DBreeze
DBreeze/Utils/BiserJsonDecoder.cs
21,036
C#
// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) // Distributed under the MIT license. See the LICENSE.md file in the project root for more information. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using Xenko.Core.Annotations; using Xenko.Core.Diagnostics; using Xenko.Core.IO; namespace Xenko.Core.Reflection { public class LoadedAssembly { public string Path { get; } public Assembly Assembly { get; } public LoadedAssembly([NotNull] string path, [NotNull] Assembly assembly) { Path = path; Assembly = assembly; } } public class AssemblyContainer { [ItemNotNull, NotNull] private readonly List<LoadedAssembly> loadedAssemblies = new List<LoadedAssembly>(); private readonly Dictionary<string, LoadedAssembly> loadedAssembliesByName = new Dictionary<string, LoadedAssembly>(StringComparer.InvariantCultureIgnoreCase); private static readonly string[] KnownAssemblyExtensions = { ".dll", ".exe" }; [ThreadStatic] private static AssemblyContainer loadingInstance; [ThreadStatic] private static LoggerResult log; [ThreadStatic] private static List<string> searchDirectoryList; /// <summary> /// The default assembly container loader. /// </summary> public static readonly AssemblyContainer Default = new AssemblyContainer(); static AssemblyContainer() { AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve; } /// <summary> /// Gets a copy of the list of loaded assemblies. /// </summary> /// <value> /// The loaded assemblies. /// </value> [ItemNotNull, NotNull] public IList<LoadedAssembly> LoadedAssemblies { get { lock (loadedAssemblies) { return loadedAssemblies.ToList(); } } } [CanBeNull] public Assembly LoadAssemblyFromPath([NotNull] string assemblyFullPath, ILogger outputLog = null, List<string> lookupDirectoryList = null) { if (assemblyFullPath == null) throw new ArgumentNullException(nameof(assemblyFullPath)); log = new LoggerResult(); lookupDirectoryList = lookupDirectoryList ?? new List<string>(); assemblyFullPath = Path.GetFullPath(Path.Combine(Environment.CurrentDirectory, assemblyFullPath)); var assemblyDirectory = Path.GetDirectoryName(assemblyFullPath); if (assemblyDirectory == null || !Directory.Exists(assemblyDirectory)) { throw new ArgumentException("Invalid assembly path. Doesn't contain directory information"); } if (!lookupDirectoryList.Contains(assemblyDirectory, StringComparer.InvariantCultureIgnoreCase)) { lookupDirectoryList.Add(assemblyDirectory); } var previousLookupList = searchDirectoryList; try { loadingInstance = this; searchDirectoryList = lookupDirectoryList; return LoadAssemblyFromPathInternal(assemblyFullPath); } finally { loadingInstance = null; searchDirectoryList = previousLookupList; if (outputLog != null) { log.CopyTo(outputLog); } } } public bool UnloadAssembly([NotNull] Assembly assembly) { lock (loadedAssemblies) { var loadedAssembly = loadedAssemblies.FirstOrDefault(x => x.Assembly == assembly); if (loadedAssembly == null) return false; loadedAssemblies.Remove(loadedAssembly); loadedAssembliesByName.Remove(loadedAssembly.Path); return true; } } [CanBeNull] private Assembly LoadAssemblyByName([NotNull] string assemblyName) { if (assemblyName == null) throw new ArgumentNullException(nameof(assemblyName)); var assemblyPartialPathList = new List<string>(); assemblyPartialPathList.AddRange(KnownAssemblyExtensions.Select(knownExtension => assemblyName + knownExtension)); foreach (var directoryPath in searchDirectoryList) { foreach (var assemblyPartialPath in assemblyPartialPathList) { var assemblyFullPath = Path.Combine(directoryPath, assemblyPartialPath); if (File.Exists(assemblyFullPath)) { return LoadAssemblyFromPathInternal(assemblyFullPath); } } } return null; } [CanBeNull] private Assembly LoadAssemblyFromPathInternal([NotNull] string assemblyFullPath) { if (assemblyFullPath == null) throw new ArgumentNullException(nameof(assemblyFullPath)); assemblyFullPath = Path.GetFullPath(assemblyFullPath); try { lock (loadedAssemblies) { LoadedAssembly loadedAssembly; if (loadedAssembliesByName.TryGetValue(assemblyFullPath, out loadedAssembly)) { return loadedAssembly.Assembly; } if (!File.Exists(assemblyFullPath)) return null; // Find pdb (if it exists) var pdbFullPath = Path.ChangeExtension(assemblyFullPath, ".pdb"); if (!File.Exists(pdbFullPath)) pdbFullPath = null; // PreLoad the assembly into memory without locking it var assemblyBytes = File.ReadAllBytes(assemblyFullPath); var pdbBytes = pdbFullPath != null ? File.ReadAllBytes(pdbFullPath) : null; // Load the assembly into the current AppDomain Assembly assembly; if (new UDirectory(AppDomain.CurrentDomain.BaseDirectory) == new UFile(assemblyFullPath).GetFullDirectory()) { // If loading from base directory, don't even try to load through byte array, as Assembly.Load will notice there is a "safer" version to load // This happens usually when opening Xenko assemblies themselves assembly = Assembly.LoadFrom(assemblyFullPath); } else { // TODO: Is using AppDomain would provide more opportunities for unloading? assembly = pdbBytes != null ? Assembly.Load(assemblyBytes, pdbBytes) : Assembly.Load(assemblyBytes); loadedAssembly = new LoadedAssembly(assemblyFullPath, assembly); loadedAssemblies.Add(loadedAssembly); loadedAssembliesByName.Add(assemblyFullPath, loadedAssembly); // Force assembly resolve with proper name // (doing it here, because if done later, loadingInstance will be set to null and it won't work) Assembly.Load(assembly.FullName); } // Make sure that all referenced assemblies are loaded here foreach (var assemblyRef in assembly.GetReferencedAssemblies()) { Assembly.Load(assemblyRef); } // Make sure that Module initializer are called if (assembly.GetTypes().Length > 0) { foreach (var module in assembly.Modules) { RuntimeHelpers.RunModuleConstructor(module.ModuleHandle); } } return assembly; } } catch (Exception exception) { log.Error($"Error while loading assembly reference [{assemblyFullPath}]", exception); var loaderException = exception as ReflectionTypeLoadException; if (loaderException != null) { foreach (var exceptionForType in loaderException.LoaderExceptions) { log.Error("Unable to load type. See exception.", exceptionForType); } } } return null; } [CanBeNull] private static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args) { // If it is handled by current thread, then we can handle it here. var container = loadingInstance; if (container != null) { var assemblyName = new AssemblyName(args.Name); return container.LoadAssemblyByName(assemblyName.Name); } return null; } } }
39.260331
167
0.56173
[ "MIT" ]
Aminator/xenko
sources/core/Xenko.Core.Design/Reflection/AssemblyContainer.cs
9,501
C#
// <auto-generated> // automatically generated by the FlatBuffers compiler, do not modify // </auto-generated> namespace rlbot.flat { public enum RenderType : sbyte { DrawLine2D = 1, DrawLine3D = 2, DrawLine2D_3D = 3, DrawRect2D = 4, DrawRect3D = 5, DrawString2D = 6, DrawString3D = 7, DrawCenteredRect3D = 8, }; }
14.909091
70
0.698171
[ "MIT" ]
Turnerj/RocketBot
src/rlbot.flat/rlbot/flat/RenderType.cs
328
C#
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // <auto-generated/> // Template Source: Templates\CSharp\Requests\MethodRequest.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; using System.Net.Http; using System.Threading; /// <summary> /// The type WorkbookFunctionsNetworkDaysRequest. /// </summary> public partial class WorkbookFunctionsNetworkDaysRequest : BaseRequest, IWorkbookFunctionsNetworkDaysRequest { /// <summary> /// Constructs a new WorkbookFunctionsNetworkDaysRequest. /// </summary> public WorkbookFunctionsNetworkDaysRequest( string requestUrl, IBaseClient client, IEnumerable<Option> options) : base(requestUrl, client, options) { this.ContentType = "application/json"; this.RequestBody = new WorkbookFunctionsNetworkDaysRequestBody(); } /// <summary> /// Gets the request body. /// </summary> public WorkbookFunctionsNetworkDaysRequestBody RequestBody { get; private set; } /// <summary> /// Issues the POST request. /// </summary> public System.Threading.Tasks.Task<WorkbookFunctionResult> PostAsync() { return this.PostAsync(CancellationToken.None); } /// <summary> /// Issues the POST request. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The task to await for async call.</returns> public System.Threading.Tasks.Task<WorkbookFunctionResult> PostAsync( CancellationToken cancellationToken) { this.Method = "POST"; return this.SendAsync<WorkbookFunctionResult>(this.RequestBody, cancellationToken); } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> public IWorkbookFunctionsNetworkDaysRequest Expand(string value) { this.QueryOptions.Add(new QueryOption("$expand", value)); return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> public IWorkbookFunctionsNetworkDaysRequest Select(string value) { this.QueryOptions.Add(new QueryOption("$select", value)); return this; } } }
35.632184
153
0.589032
[ "MIT" ]
OfficeGlobal/msgraph-beta-sdk-dotnet
src/Microsoft.Graph/Requests/Generated/WorkbookFunctionsNetworkDaysRequest.cs
3,100
C#
using Microsoft.Framework.Configuration; using System; using System.Collections.Generic; namespace Orchard.Configuration { internal class InternalConfigurationSource : IConfigurationSource { private readonly IDictionary<string, string> _values; public InternalConfigurationSource() { _values = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); } public void Load() { throw new NotSupportedException(); } public IEnumerable<string> ProduceConfigurationSections(IEnumerable<string> earlierKeys, string prefix, string delimiter) { throw new NotImplementedException(); } public void Set(string key, string value) { _values.Add(key, value); } public bool TryGet(string key, out string value) { return _values.TryGetValue(key, out value); } } }
30.6
131
0.665577
[ "BSD-3-Clause" ]
BilalHasanKhan/Brochard
src/Orchard.Configuration/InternalConfigurationSource.cs
920
C#
using System; using System.Threading; using System.Threading.Tasks; using UnityEngine; public interface ICountDownable { /// <summary> /// CD时长 /// </summary> TimeSpan CDTimeSpan { get; } /// <summary> /// 距离结束时刻时长 /// </summary> TimeSpan Delta2Finish { get; } /// <summary> /// 结束时刻 /// </summary> DateTimeOffset FinishTime { get; } /// <summary> /// <para/> -2 :没有Start /// <para/> -1 :计时被取消 /// <para/> 0 :计时完成 /// </summary> Task<int> FinishTask { get; } /// <summary> /// 显示为指定时间 /// </summary> /// <param name="delta2End"></param> void Show(TimeSpan delta2End); void SetCancellationToken(CancellationToken token); Task<int> ReStartCD(); Task<int> StartCD(DateTimeOffset finishTime, TimeSpan? cdTime = null, CancellationToken token = default); Task<int> StartCD(TimeSpan cdTime, DateTimeOffset? startTime = null, CancellationToken token = default); } public abstract class BaseCountDown : MonoBehaviour, ICountDownable { public DateTimeOffset FinishTime { get; private set; } public TimeSpan Delta2Finish { get; private set; } public TimeSpan CDTimeSpan { get; private set; } CancellationToken cancellationToken = default; private TaskCompletionSource<int> source; public Task<int> FinishTask => source?.Task ?? Task.FromResult(-2); public Task<int> StartCD(DateTimeOffset finishTime, TimeSpan? cdTime = null, CancellationToken token = default) { source?.TrySetResult(-1); source = new TaskCompletionSource<int>(); cancellationToken = token; FinishTime = finishTime; if (cdTime.HasValue) { CDTimeSpan = (TimeSpan)cdTime; } else { CDTimeSpan = finishTime - DateTimeOffset.UtcNow; } Tick(DateTimeOffset.UtcNow); return source.Task; } public Task<int> StartCD(TimeSpan cdTime, DateTimeOffset? startTime = null, CancellationToken token = default) { source?.TrySetResult(-1); source = new TaskCompletionSource<int>(); cancellationToken = token; CDTimeSpan = cdTime; if (startTime.HasValue) { FinishTime = (DateTimeOffset)startTime + cdTime; } else { FinishTime = DateTimeOffset.UtcNow + cdTime; } Tick(DateTimeOffset.UtcNow); return source.Task; } public Task<int> ReStartCD() { return StartCD(CDTimeSpan); } public void SetCancellationToken(CancellationToken token) { cancellationToken = token; } protected void Tick(DateTimeOffset now) { var cd = FinishTime - now; Delta2Finish = cd; Show(cd); if (cd.TotalSeconds <= 0) { source?.TrySetResult(0); } else { if (cancellationToken.IsCancellationRequested) { source?.TrySetResult(-1); } } } public abstract void Show(TimeSpan delta2End); }
26.194915
115
0.599806
[ "MIT" ]
KumoKyaku/Megumin.Explosion
Megumin.UnityPackage/Packages/megumin.explosion4unity/Runtime/Scripts/NewClass/CD/CountDownable.cs
3,163
C#
using System; using System.Collections.Generic; using System.Text; using System.Linq; using SeoSchema; using SeoSchema.Enumerations; using SuperStructs; namespace SeoSchema.Entities { /// <summary> /// ATM/cash machine. /// <see cref="https://schema.org/AutomatedTeller"/> /// </summary> public class AutomatedTeller : IEntity { /// Description of fees, commissions, and other terms applied either to a class of financial product, or by a financial service organization. public Or<string, Uri>? FeesAndCommissionsSpecification { get; set; } /// The currency accepted. /// /// Use standard formats: ISO 4217 currency format e.g. "USD"; Ticker symbol for cryptocurrencies e.g. "BTC"; well known names for Local Exchange Tradings Systems (LETS) and other currency types e.g. "Ithaca HOUR". public Or<string>? CurrenciesAccepted { get; set; } /// The general opening hours for a business. Opening hours can be specified as a weekly time range, starting with days, then times per day. Multiple days can be listed with commas ',' separating each day. Day or time ranges are specified using a hyphen '-'. /// /// /// Days are specified using the following two-letter combinations: Mo, Tu, We, Th, Fr, Sa, Su. /// Times are specified using 24:00 time. For example, 3pm is specified as 15:00. /// Here is an example: <time itemprop="openingHours" datetime="Tu,Th 16:00-20:00">Tuesdays and Thursdays 4-8pm</time>. /// If a business is open 7 days a week, then it can be specified as <time itemprop="openingHours" datetime="Mo-Su">Monday through Sunday, all day</time>. public Or<string>? OpeningHours { get; set; } /// Cash, Credit Card, Cryptocurrency, Local Exchange Tradings System, etc. public Or<string>? PaymentAccepted { get; set; } /// The price range of the business, for example $$$. public Or<string>? PriceRange { get; set; } /// For a NewsMediaOrganization or other news-related Organization, a statement about public engagement activities (for news media, the newsroom’s), including involving the public - digitally or otherwise -- in coverage decisions, reporting and activities after publication. public Or<CreativeWork, Uri>? ActionableFeedbackPolicy { get; set; } /// Physical address of the item. public Or<PostalAddress, string>? Address { get; set; } /// The overall rating, based on a collection of reviews or ratings, of the item. public Or<AggregateRating>? AggregateRating { get; set; } /// Alumni of an organization. Inverse property: alumniOf. public Or<Person>? Alumni { get; set; } /// The geographic area where a service or offered item is provided. Supersedes serviceArea. public Or<AdministrativeArea, GeoShape, Place, string>? AreaServed { get; set; } /// An award won by or for this item. Supersedes awards. public Or<string>? Award { get; set; } /// The brand(s) associated with a product or service, or the brand(s) maintained by an organization or business person. public Or<Brand, Organization>? Brand { get; set; } /// A contact point for a person or organization. Supersedes contactPoints. public Or<ContactPoint>? ContactPoint { get; set; } /// For an Organization (e.g. NewsMediaOrganization), a statement describing (in news media, the newsroom’s) disclosure and correction policy for errors. public Or<CreativeWork, Uri>? CorrectionsPolicy { get; set; } /// A relationship between an organization and a department of that organization, also described as an organization (allowing different urls, logos, opening hours). For example: a store with a pharmacy, or a bakery with a cafe. public Or<Organization>? Department { get; set; } /// The date that this organization was dissolved. public Or<SuperStructs.Date>? DissolutionDate { get; set; } /// Statement on diversity policy by an Organization e.g. a NewsMediaOrganization. For a NewsMediaOrganization, a statement describing the newsroom’s diversity policy on both staffing and sources, typically providing staffing data. public Or<CreativeWork, Uri>? DiversityPolicy { get; set; } /// For an Organization (often but not necessarily a NewsMediaOrganization), a report on staffing diversity issues. In a news context this might be for example ASNE or RTDNA (US) reports, or self-reported. public Or<Article, Uri>? DiversityStaffingReport { get; set; } /// The Dun & Bradstreet DUNS number for identifying an organization or business person. public Or<string>? Duns { get; set; } /// Email address. public Or<string>? Email { get; set; } /// Someone working for this organization. Supersedes employees. public Or<Person>? Employee { get; set; } /// Statement about ethics policy, e.g. of a NewsMediaOrganization regarding journalistic and publishing practices, or of a Restaurant, a page describing food source policies. In the case of a NewsMediaOrganization, an ethicsPolicy is typically a statement describing the personal, organizational, and corporate standards of behavior expected by the organization. public Or<CreativeWork, Uri>? EthicsPolicy { get; set; } /// Upcoming or past event associated with this place, organization, or action. Supersedes events. public Or<Event>? Event { get; set; } /// The fax number. public Or<string>? FaxNumber { get; set; } /// A person who founded this organization. Supersedes founders. public Or<Person>? Founder { get; set; } /// The date that this organization was founded. public Or<SuperStructs.Date>? FoundingDate { get; set; } /// The place where the Organization was founded. public Or<Place>? FoundingLocation { get; set; } /// A person or organization that supports (sponsors) something through some kind of financial contribution. public Or<Organization, Person>? Funder { get; set; } /// The Global Location Number (GLN, sometimes also referred to as International Location Number or ILN) of the respective organization, person, or place. The GLN is a 13-digit number used to identify parties and physical locations. public Or<string>? GlobalLocationNumber { get; set; } /// Indicates an OfferCatalog listing for this Organization, Person, or Service. public Or<OfferCatalog>? HasOfferCatalog { get; set; } /// Points-of-Sales operated by the organization or person. public Or<Place>? HasPOS { get; set; } /// The International Standard of Industrial Classification of All Economic Activities (ISIC), Revision 4 code for a particular organization, business person, or place. public Or<string>? IsicV4 { get; set; } /// Of a Person, and less typically of an Organization, to indicate a topic that is known about - suggesting possible expertise but not implying it. We do not distinguish skill levels here, or yet relate this to educational content, events, objectives or JobPosting descriptions. public Or<string, Thing, Uri>? KnowsAbout { get; set; } /// Of a Person, and less typically of an Organization, to indicate a known language. We do not distinguish skill levels or reading/writing/speaking/signing here. Use language codes from the IETF BCP 47 standard. public Or<Language, string>? KnowsLanguage { get; set; } /// The official name of the organization, e.g. the registered company name. public Or<string>? LegalName { get; set; } /// An organization identifier that uniquely identifies a legal entity as defined in ISO 17442. public Or<string>? LeiCode { get; set; } /// The location of for example where the event is happening, an organization is located, or where an action takes place. public Or<Place, PostalAddress, string>? Location { get; set; } /// An associated logo. public Or<ImageObject, Uri>? Logo { get; set; } /// A pointer to products or services offered by the organization or person. Inverse property: offeredBy. public Or<Offer>? MakesOffer { get; set; } /// A member of an Organization or a ProgramMembership. Organizations can be members of organizations; ProgramMembership is typically for individuals. Supersedes members, musicGroupMember. Inverse property: memberOf. public Or<Organization, Person>? Member { get; set; } /// An Organization (or ProgramMembership) to which this Person or Organization belongs. Inverse property: member. public Or<Organization, ProgramMembership>? MemberOf { get; set; } /// The North American Industry Classification System (NAICS) code for a particular organization or business person. public Or<string>? Naics { get; set; } /// The number of employees in an organization e.g. business. public Or<QuantitativeValue>? NumberOfEmployees { get; set; } /// For an Organization (often but not necessarily a NewsMediaOrganization), a description of organizational ownership structure; funding and grants. In a news/media setting, this is with particular reference to editorial independence. Note that the funder is also available and can be used to make basic funder information machine-readable. public Or<AboutPage, CreativeWork, string, Uri>? OwnershipFundingInfo { get; set; } /// Products owned by the organization or person. public Or<OwnershipInfo, Product>? Owns { get; set; } /// The larger organization that this organization is a subOrganization of, if any. Supersedes branchOf. Inverse property: subOrganization. public Or<Organization>? ParentOrganization { get; set; } /// The publishingPrinciples property indicates (typically via URL) a document describing the editorial principles of an Organization (or individual e.g. a Person writing a blog) that relate to their activities as a publisher, e.g. ethics or diversity policies. When applied to a CreativeWork (e.g. NewsArticle) the principles are those of the party primarily responsible for the creation of the CreativeWork. /// /// While such policies are most typically expressed in natural language, sometimes related information (e.g. indicating a funder) can be expressed using schema.org terminology. public Or<CreativeWork, Uri>? PublishingPrinciples { get; set; } /// A review of the item. Supersedes reviews. public Or<Review>? Review { get; set; } /// A pointer to products or services sought by the organization or person (demand). public Or<Demand>? Seeks { get; set; } /// A person or organization that supports a thing through a pledge, promise, or financial contribution. e.g. a sponsor of a Medical Study or a corporate sponsor of an event. public Or<Organization, Person>? Sponsor { get; set; } /// A relationship between two organizations where the first includes the second, e.g., as a subsidiary. See also: the more specific 'department' property. Inverse property: parentOrganization. public Or<Organization>? SubOrganization { get; set; } /// The Tax / Fiscal ID of the organization or person, e.g. the TIN in the US or the CIF/NIF in Spain. public Or<string>? TaxID { get; set; } /// The telephone number. public Or<string>? Telephone { get; set; } /// For an Organization (typically a NewsMediaOrganization), a statement about policy on use of unnamed sources and the decision process required. public Or<CreativeWork, Uri>? UnnamedSourcesPolicy { get; set; } /// The Value-added Tax ID of the organization or person. public Or<string>? VatID { get; set; } /// A property-value pair representing an additional characteristics of the entitity, e.g. a product feature or another characteristic for which there is no matching property in schema.org. /// /// Note: Publishers should be aware that applications designed to use specific schema.org properties (e.g. http://schema.org/width, http://schema.org/color, http://schema.org/gtin13, ...) will typically expect such data to be provided using those properties, rather than using the generic property/value mechanism. public Or<PropertyValue>? AdditionalProperty { get; set; } /// An amenity feature (e.g. a characteristic or service) of the Accommodation. This generic property does not make a statement about whether the feature is included in an offer for the main accommodation or available at extra costs. public Or<LocationFeatureSpecification>? AmenityFeature { get; set; } /// A short textual code (also called "store code") that uniquely identifies a place of business. The code is typically assigned by the parentOrganization and used in structured URLs. /// /// For example, in the URL http://www.starbucks.co.uk/store-locator/etc/detail/3047 the code "3047" is a branchCode for a particular branch. public Or<string>? BranchCode { get; set; } /// The basic containment relation between a place and one that contains it. Supersedes containedIn. Inverse property: containsPlace. public Or<Place>? ContainedInPlace { get; set; } /// The basic containment relation between a place and another that it contains. Inverse property: containedInPlace. public Or<Place>? ContainsPlace { get; set; } /// The geo coordinates of the place. public Or<GeoCoordinates, GeoShape>? Geo { get; set; } /// Represents a relationship between two geometries (or the places they represent), relating a containing geometry to a contained geometry. "a contains b iff no points of b lie in the exterior of a, and at least one point of the interior of b lies in the interior of a". As defined in DE-9IM. public Or<GeospatialGeometry, Place>? GeospatiallyContains { get; set; } /// Represents a relationship between two geometries (or the places they represent), relating a geometry to another that covers it. As defined in DE-9IM. public Or<GeospatialGeometry, Place>? GeospatiallyCoveredBy { get; set; } /// Represents a relationship between two geometries (or the places they represent), relating a covering geometry to a covered geometry. "Every point of b is a point of (the interior or boundary of) a". As defined in DE-9IM. public Or<GeospatialGeometry, Place>? GeospatiallyCovers { get; set; } /// Represents a relationship between two geometries (or the places they represent), relating a geometry to another that crosses it: "a crosses b: they have some but not all interior points in common, and the dimension of the intersection is less than that of at least one of them". As defined in DE-9IM. public Or<GeospatialGeometry, Place>? GeospatiallyCrosses { get; set; } /// Represents spatial relations in which two geometries (or the places they represent) are topologically disjoint: they have no point in common. They form a set of disconnected geometries." (a symmetric relationship, as defined in DE-9IM) public Or<GeospatialGeometry, Place>? GeospatiallyDisjoint { get; set; } /// Represents spatial relations in which two geometries (or the places they represent) are topologically equal, as defined in DE-9IM. "Two geometries are topologically equal if their interiors intersect and no part of the interior or boundary of one geometry intersects the exterior of the other" (a symmetric relationship) public Or<GeospatialGeometry, Place>? GeospatiallyEquals { get; set; } /// Represents spatial relations in which two geometries (or the places they represent) have at least one point in common. As defined in DE-9IM. public Or<GeospatialGeometry, Place>? GeospatiallyIntersects { get; set; } /// Represents a relationship between two geometries (or the places they represent), relating a geometry to another that geospatially overlaps it, i.e. they have some but not all points in common. As defined in DE-9IM. public Or<GeospatialGeometry, Place>? GeospatiallyOverlaps { get; set; } /// Represents spatial relations in which two geometries (or the places they represent) touch: they have at least one boundary point in common, but no interior points." (a symmetric relationship, as defined in DE-9IM ) public Or<GeospatialGeometry, Place>? GeospatiallyTouches { get; set; } /// Represents a relationship between two geometries (or the places they represent), relating a geometry to one that contains it, i.e. it is inside (i.e. within) its interior. As defined in DE-9IM. public Or<GeospatialGeometry, Place>? GeospatiallyWithin { get; set; } /// A URL to a map of the place. Supersedes map, maps. public Or<Map, Uri>? HasMap { get; set; } /// A flag to signal that the item, event, or place is accessible for free. Supersedes free. public Or<bool>? IsAccessibleForFree { get; set; } /// The total number of individuals that may attend an event or venue. public Or<int>? MaximumAttendeeCapacity { get; set; } /// The opening hours of a certain place. public Or<OpeningHoursSpecification>? OpeningHoursSpecification { get; set; } /// A photograph of this place. Supersedes photos. public Or<ImageObject, Photograph>? Photo { get; set; } /// A flag to signal that the Place is open to public visitors. If this property is omitted there is no assumed default boolean value public Or<bool>? PublicAccess { get; set; } /// Indicates whether it is allowed to smoke in the place, e.g. in the restaurant, hotel or hotel room. public Or<bool>? SmokingAllowed { get; set; } /// The special opening hours of a certain place. /// /// Use this to explicitly override general opening hours brought in scope by openingHoursSpecification or openingHours. public Or<OpeningHoursSpecification>? SpecialOpeningHoursSpecification { get; set; } /// An additional type for the item, typically used for adding more specific types from external vocabularies in microdata syntax. This is a relationship between something and a class that the thing is in. In RDFa syntax, it is better to use the native RDFa syntax - the 'typeof' attribute - for multiple types. Schema.org tools may have only weaker understanding of extra types, in particular those defined externally. public Or<Uri>? AdditionalType { get; set; } /// An alias for the item. public Or<string>? AlternateName { get; set; } /// A description of the item. public Or<string>? Description { get; set; } /// A sub property of description. A short description of the item used to disambiguate from other, similar items. Information from other properties (in particular, name) may be necessary for the description to be useful for disambiguation. public Or<string>? DisambiguatingDescription { get; set; } /// The identifier property represents any kind of identifier for any kind of Thing, such as ISBNs, GTIN codes, UUIDs etc. Schema.org provides dedicated properties for representing many of these, either as textual strings or as URL (URI) links. See background notes for more details. public Or<PropertyValue, string, Uri>? Identifier { get; set; } /// An image of the item. This can be a URL or a fully described ImageObject. public Or<ImageObject, Uri>? Image { get; set; } /// Indicates a page (or other CreativeWork) for which this thing is the main entity being described. See background notes for details. Inverse property: mainEntity. public Or<CreativeWork, Uri>? MainEntityOfPage { get; set; } /// The name of the item. public Or<string>? Name { get; set; } /// Indicates a potential Action, which describes an idealized action in which this thing would play an 'object' role. public Or<Action>? PotentialAction { get; set; } /// URL of a reference Web page that unambiguously indicates the item's identity. E.g. the URL of the item's Wikipedia page, Wikidata entry, or official website. public Or<Uri>? SameAs { get; set; } /// A CreativeWork or Event about this Thing.. Inverse property: about. public Or<CreativeWork, Event>? SubjectOf { get; set; } /// URL of the item. public Or<Uri>? Url { get; set; } } }
67.811075
427
0.703382
[ "MIT" ]
jefersonsv/SeoSchema
src/SeoSchema/Entities/AutomatedTeller.cs
20,824
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.Collections.Generic; namespace Roslynator.CSharp.Analyzers.Tests { internal static class ReplaceForEachWithFor { private static void Foo() { var items = new List<object>(); foreach (object item in items) { } } } }
25
160
0.627368
[ "Apache-2.0" ]
ADIX7/Roslynator
src/Tests/Analyzers.Tests.Old/ReplaceForEachWithFor.cs
477
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool from CryptoGateway Software Inc. // Tool name: CGW X-Script RDB visual Layer Generator // // Archymeta Information Technologies Co., Ltd. // // Changes to this file, could be overwritten if the code is re-generated. // Add (if not yet) a code-manager node to the generator to specify // how existing files are processed. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Configuration; using System.Collections.Generic; using System.Reflection; using System.Linq; using System.Linq.Expressions; using System.Threading; using System.Runtime.Serialization; namespace CryptoGateway.RDB.Data.MembershipPlus { /// <summary> /// A structure representing a block of pages. /// </summary> [DataContract] [Serializable] public class UserAppMemberPageBlock { /// <summary> /// The total number of entities. /// </summary> [DataMember] public Int64 TotalEntities { get { return _totalEntities; } set { _totalEntities = value; } } private Int64 _totalEntities = 0; /// <summary> /// The total number of pages. /// </summary> [DataMember] public Int64 TotalPages { get { return _totalPages; } set { _totalPages = value; } } private Int64 _totalPages = 0; /// <summary> /// The number of pages inside the block. /// </summary> [DataMember] public int BlockCount { get { return _blockCount; } set { _blockCount = value; } } private int _blockCount = 0; /// <summary> /// Whether or not this is the last blcok of pages inside the data set. /// </summary> [DataMember] public bool IsLastBlock { get; set; } /// <summary> /// The collection of pages inside the block. /// </summary> [DataMember] public UserAppMemberPage[] Pages { get; set; } } /// <summary> /// A structure representing a page of entity <see cref="UserAppMember" />. /// </summary> [DataContract] [Serializable] public class UserAppMemberPage { /// <summary> /// The zero based index of the page. /// </summary> [DataMember] public int Index_ { get { return _index; } set { _index = value; } } private int _index = 0; /// <summary> /// The page identifier. /// </summary> [DataMember] public string PageNumber { get { return (Index_ + 1).ToString(); } set { } } /// <summary> /// The first entity of the page. /// </summary> [DataMember] public UserAppMember FirstItem { get; set; } /// <summary> /// The last entity of the page. /// </summary> [DataMember] public UserAppMember LastItem { get; set; } /// <summary> /// Whether or not the current page is the last page of the data set. /// </summary> [DataMember] public bool IsLastPage { get; set; } /// <summary> /// The collection of entities inside the page. /// </summary> public List<UserAppMember> Items { get; set; } public UserAppMemberPage(int idx) { _index = idx; } } }
24.509317
80
0.488596
[ "Apache-2.0" ]
colinvo/membership-plus
Service/Shared/Model/UserAppMemberPage.cs
3,946
C#
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using System; using System.Diagnostics; using System.Management.Automation; using System.Threading; using Microsoft.Azure.Commands.RecoveryServices.SiteRecovery; using Microsoft.WindowsAzure.Management.SiteRecovery.Models; namespace Microsoft.Azure.Commands.RecoveryServices { /// <summary> /// Used to initiate a commit operation. /// </summary> [Cmdlet(VerbsData.Update, "AzureSiteRecoveryProtectionEntity")] [OutputType(typeof(ASRJob))] public class UpdateAzureSiteRecoveryProtectionEntity : RecoveryServicesCmdletBase { #region Parameters /// <summary> /// ID of the PE object to Update user information on. /// </summary> private string protectionEntityId; /// <summary> /// Protection container ID of the object to Update user information on. /// </summary> private string protectionContainerId; /// <summary> /// Job response. /// </summary> private JobResponse jobResponse = null; /// <summary> /// Gets or sets Protection Entity object. /// </summary> [Parameter(Mandatory = true, ValueFromPipeline = true)] [ValidateNotNullOrEmpty] public ASRProtectionEntity ProtectionEntity { get; set; } /// <summary> /// Gets or sets switch parameter. This is required to wait for job completion. /// </summary> [Parameter] public SwitchParameter WaitForCompletion { get; set; } #endregion Parameters /// <summary> /// ProcessRecord of the command. /// </summary> public override void ExecuteCmdlet() { try { this.WriteWarningWithTimestamp( string.Format( Properties.Resources.CmdletWillBeDeprecatedSoon, this.MyInvocation.MyCommand.Name)); this.protectionContainerId = this.ProtectionEntity.ProtectionContainerId; this.protectionEntityId = this.ProtectionEntity.ID; this.SyncOwnerInformationOnPE(); } catch (Exception exception) { this.HandleException(exception); } } /// <summary> /// Handles interrupts. /// </summary> protected override void StopProcessing() { // Ctrl + C and etc base.StopProcessing(); this.StopProcessingFlag = true; } /// <summary> /// Syncs the owner information. /// </summary> private void SyncOwnerInformationOnPE() { this.jobResponse = RecoveryServicesClient.UpdateAzureSiteRecoveryProtectionEntity( this.protectionContainerId, this.protectionEntityId); this.WriteJob(this.jobResponse.Job); if (this.WaitForCompletion) { this.WaitForJobCompletion(this.jobResponse.Job.ID); } } /// <summary> /// Writes Job /// </summary> /// <param name="job">Job object</param> private void WriteJob(Microsoft.WindowsAzure.Management.SiteRecovery.Models.Job job) { this.WriteObject(new ASRJob(job)); } } }
33.348837
95
0.555788
[ "MIT" ]
FosterMichelle/azure-powershell
src/ServiceManagement/RecoveryServices/Commands.RecoveryServices/Service/UpdateAzureSiteRecoveryProtectionEntity.cs
4,176
C#
// Copyright 2010 Chris Patterson // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. namespace Stact.Internal { public class AlphaMemoryElementReference<T> : ElementReference<T> { readonly Element<T> _element; AlphaMemory _alphaMemory; public AlphaMemoryElementReference(AlphaMemory<T> alphaMemory, Element<T> element) { _alphaMemory = alphaMemory; _element = element; } public Element<T> Element { get { return _element; } } } }
31.5
85
0.709325
[ "Apache-2.0" ]
Nangal/Stact
src/Stact.Playground/Rules/Internal/AlphaMemoryElementReference.cs
1,010
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("ConexaoSQLServer")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ConexaoSQLServer")] [assembly: AssemblyCopyright("Copyright © 2020")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("586aaee2-0b12-4178-ab23-3278b1277cf6")] // 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" ]
maxwellmiquelino/csharp
ConexaoSQLServer/ConexaoSQLServer/Properties/AssemblyInfo.cs
1,403
C#
namespace SpecFlow.VisualStudio.SpecFlowConnector.Generation; public interface ISpecFlowGenerator { string Generate(string projectFolder, string configFilePath, string targetExtension, string featureFilePath, string targetNamespace, string projectDefaultNamespace, bool saveResultToFile); }
38
112
0.835526
[ "MIT" ]
SpecFlowOSS/SpecFlow.VS
Connectors/SpecFlow.VisualStudio.SpecFlowConnector.V1/Generation/ISpecFlowGenerator.cs
304
C#
using System; using System.Collections.Immutable; using System.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Agoda.Analyzers.AgodaCustom; using Agoda.Analyzers.Helpers; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Agoda.Analyzers.CodeFixes.AgodaCustom { [ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(AG0022RemoveSyncMethodFixProvider)), Shared] public class AG0022RemoveSyncMethodFixProvider : CodeFixProvider { public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(AG0022DoNotExposeBothSyncAndAsyncVersionsOfMethods.DIAGNOSTIC_ID); public override Task RegisterCodeFixesAsync(CodeFixContext context) { foreach (var diagnostic in context.Diagnostics) { context.RegisterCodeFix( CodeAction.Create( CustomRulesResources.AG0022FixTitle, cancellationToken => GetTransformedDocumentAsync(context.Document, diagnostic, cancellationToken), nameof(AG0022RemoveSyncMethodFixProvider)), diagnostic); } return Task.CompletedTask; } private async Task<Document> GetTransformedDocumentAsync(Document document, Diagnostic diagnostic, CancellationToken cancellationToken) { var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); if (root.FindNode(diagnostic.Location.SourceSpan) is MethodDeclarationSyntax node) { var newRoot = root.RemoveNode(node, SyntaxRemoveOptions.KeepNoTrivia); var updatedDocument = document.WithSyntaxRoot(newRoot); return updatedDocument; } return document; } } }
43.568627
160
0.636364
[ "Apache-2.0" ]
agoda-com/AgodaAnalyzers
src/Agoda.Analyzers.CodeFixes/AgodaCustom/AG0022RemoveSyncMethodFixProvider.cs
2,224
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using Rudrac.TowerDefence; namespace Rudrac.TowerDefence.Combat { [RequireComponent(typeof(AudioSource))] public class AttackedSoundeffect : MonoBehaviour,IAttackable { public AudioClip[] clips; public void OnAttack(GameObject attacker, Attack attack) { GetComponent<AudioSource>().PlayOneShot(clips[Random.Range(0, clips.Length)]); } } }
25.263158
90
0.708333
[ "Apache-2.0" ]
venkatesh21m/TowerDefenceGame
TowerDefence/Assets/_Scripts/Engine/Combat/Monobehaviours/Attackables/AttackedSoundeffect.cs
480
C#
using System; using System.Diagnostics; using System.Runtime.InteropServices; namespace Cerevo.UB300_Win.Api { public partial class SwApiCommand { internal byte[] ToBytes() { var len = Marshal.SizeOf(this.GetType()); var buffer = new byte[len]; var ptr = Marshal.AllocHGlobal(len); try { Marshal.StructureToPtr(this, ptr, true); Marshal.Copy(ptr, buffer, 0, len); } finally { Marshal.FreeHGlobal(ptr); } return buffer; } internal static T FromBytes<T>(byte[] buffer) where T : SwApiCommand { return FromBytes<T>(buffer, 0); } internal static T FromBytes<T>(byte[] buffer, int offset) where T : SwApiCommand { if(!CheckSize<T>(buffer, offset)) { return null; } var len = Marshal.SizeOf(typeof(T)); var ptr = Marshal.AllocHGlobal(len); try { Marshal.Copy(buffer, offset, ptr, len); return (T)Marshal.PtrToStructure(ptr, typeof(T)); } finally { Marshal.FreeHGlobal(ptr); } } internal static bool CheckSize<T>(byte[] buffer) where T : SwApiCommand { return CheckSize<T>(buffer, 0); } internal static bool CheckSize<T>(byte[] buffer, int offset) where T : SwApiCommand { Debug.Assert(buffer.Length >= (Marshal.SizeOf(typeof(T)) + offset)); return buffer.Length >= (Marshal.SizeOf(typeof(T)) + offset); } internal static SwApiId GetApiId(byte[] buffer) { if(buffer.Length < 4) return SwApiId.Null; return (SwApiId)BitConverter.ToUInt32(buffer, 0); } } }
32.392857
93
0.545755
[ "BSD-3-Clause" ]
cerevo/LiveWedgeWindowsApp
UB300_Win.Api/Commands.Marshalling.cs
1,816
C#
using System; using System.IO; using System.Text; using System.Text.Json.Serialization; using System.Threading.Tasks; using Hippo.Extensions; using Hippo.Models; using Hippo.Repositories; using Hippo.Schedulers; using Hippo.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc.Infrastructure; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.IdentityModel.Tokens; using Microsoft.OpenApi.Models; namespace Hippo.Proxies { public class ProxyStartup { public void ConfigureServices(IServiceCollection services) { services.AddReverseProxy() .LoadFromHippoChannels(); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { // TODO: Configure an exception handler. app.UseHsts(); } app.UseHttpsRedirection(); app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapReverseProxy(); }); } } }
26.018182
79
0.654787
[ "Apache-2.0" ]
adamreese/hippo
Hippo/Proxies/ProxyStartup.cs
1,431
C#
namespace Binance.Spot { using System; using System.Collections.Generic; using System.Net.Http; using System.Threading.Tasks; using Binance.Spot.Models; public class Fiat : SpotService { public Fiat(string baseUrl = DEFAULT_SPOT_BASE_URL, string apiKey = null, string apiSecret = null) : this(new HttpClient(), baseUrl: baseUrl, apiKey: apiKey, apiSecret: apiSecret) { } public Fiat(HttpClient httpClient, string baseUrl = DEFAULT_SPOT_BASE_URL, string apiKey = null, string apiSecret = null) : base(httpClient, baseUrl: baseUrl, apiKey: apiKey, apiSecret: apiSecret) { } private const string GET_FIAT_DEPOSIT_WITHDRAW_HISTORY = "/sapi/v1/fiat/orders"; /// <summary> /// - If beginTime and endTime are not sent, the recent 30-day data will be returned.<para /> /// Weight(IP): 1. /// </summary> /// <param name="transactionType">* `0` - deposit.<para /> /// * `1` - withdraw.</param> /// <param name="beginTime"></param> /// <param name="endTime">UTC timestamp in ms.</param> /// <param name="page">Default 1.</param> /// <param name="rows">Default 100, max 500.</param> /// <param name="recvWindow">The value cannot be greater than 60000.</param> /// <returns>History of deposit/withdraw orders.</returns> public async Task<string> GetFiatDepositWithdrawHistory(FiatOrderTransactionType transactionType, long? beginTime = null, long? endTime = null, int? page = null, int? rows = null, long? recvWindow = null) { var result = await this.SendSignedAsync<string>( GET_FIAT_DEPOSIT_WITHDRAW_HISTORY, HttpMethod.Get, query: new Dictionary<string, object> { { "transactionType", transactionType }, { "beginTime", beginTime }, { "endTime", endTime }, { "page", page }, { "rows", rows }, { "recvWindow", recvWindow }, { "timestamp", DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() }, }); return result; } private const string GET_FIAT_PAYMENTS_HISTORY = "/sapi/v1/fiat/payments"; /// <summary> /// - If beginTime and endTime are not sent, the recent 30-day data will be returned.<para /> /// Weight(IP): 1. /// </summary> /// <param name="transactionType">* `0` - deposit.<para /> /// * `1` - withdraw.</param> /// <param name="beginTime"></param> /// <param name="endTime">UTC timestamp in ms.</param> /// <param name="page">Default 1.</param> /// <param name="rows">Default 100, max 500.</param> /// <param name="recvWindow">The value cannot be greater than 60000.</param> /// <returns>History of fiat payments.</returns> public async Task<string> GetFiatPaymentsHistory(FiatPaymentTransactionType transactionType, long? beginTime = null, long? endTime = null, int? page = null, int? rows = null, long? recvWindow = null) { var result = await this.SendSignedAsync<string>( GET_FIAT_PAYMENTS_HISTORY, HttpMethod.Get, query: new Dictionary<string, object> { { "transactionType", transactionType }, { "beginTime", beginTime }, { "endTime", endTime }, { "page", page }, { "rows", rows }, { "recvWindow", recvWindow }, { "timestamp", DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() }, }); return result; } } }
44.206897
212
0.558502
[ "MIT" ]
binance/binance-connector-dotnet
Src/Spot/Fiat.cs
3,846
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; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; namespace Silk.NET.SilkTouch { public partial class NativeApiGenerator { private Dictionary<INamedTypeSymbol, Func<ImmutableArray<TypedConstant>, (int, string, INativeContextOverride)?>> _nativeContextAttributes = new(SymbolEqualityComparer.Default); private void ProcessNativeContextOverrides ( EntryPoint[] entrypoints, ref List<MemberDeclarationSyntax> members, ITypeSymbol classSymbol, INamedTypeSymbol excludeFromOverrideAttribute ) { var overrides = FindNativeContextOverrides(classSymbol); StatementSyntax last = ReturnStatement ( ObjectCreationExpression( QualifiedName( QualifiedName( QualifiedName( QualifiedName( IdentifierName("Silk"), IdentifierName("NET")), IdentifierName("Core")), IdentifierName("Contexts")), IdentifierName("DefaultNativeContext"))) .WithArgumentList( ArgumentList( SingletonSeparatedList( Argument( IdentifierName("n"))))) ); foreach (var (attSymbol, attId, lib, @override) in overrides.OrderBy(x => x.Item2)) { var name = $"OVERRIDE_{attId}"; members.Add(@override.Type(name, lib, entrypoints.Where(x => x.SourceSymbol.GetAttributes() .All(x2 => { if (!SymbolEqualityComparer.Default.Equals(x2.AttributeClass, excludeFromOverrideAttribute)) return true; var matchId = (int) x2.ConstructorArguments[0].Value!; return matchId != attId; })).ToArray())); last = IfStatement ( BinaryExpression ( SyntaxKind.EqualsExpression, IdentifierName("n"), LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(lib)) ), ReturnStatement(ObjectCreationExpression(IdentifierName(name), ArgumentList(), null)), ElseClause(last) ); } members.Add ( MethodDeclaration(IdentifierName("INativeContext"), Identifier("CreateDefaultContext")) .WithModifiers(TokenList(Token(SyntaxKind.PublicKeyword), Token(SyntaxKind.StaticKeyword))) .WithParameterList ( ParameterList ( SingletonSeparatedList (Parameter(Identifier("n")).WithType(PredefinedType(Token(SyntaxKind.StringKeyword)))) ) ) .WithBody(Block(last)) ); } private IEnumerable<(INamedTypeSymbol, int, string, INativeContextOverride)> FindNativeContextOverrides(ITypeSymbol symbol) { var attributes = symbol.GetAttributes(); foreach (var attribute in attributes) { if (attribute.AttributeClass is null) continue; if (_nativeContextAttributes.TryGetValue(attribute.AttributeClass, out var f)) { var v = f(attribute.ConstructorArguments); if (v.HasValue) yield return (attribute.AttributeClass, v.Value.Item1, v.Value.Item2, v.Value.Item3); } } } } }
41.214953
131
0.521995
[ "MIT" ]
KyleGalvin/Silk.NET
src/Core/Silk.NET.SilkTouch/NativeContextOverrideGeneration.cs
4,412
C#
using System; using System.Text; using System.Web; using System.Web.Http.Description; namespace quickdemoemployee.Areas.HelpPage { public static class ApiDescriptionExtensions { /// <summary> /// Generates an URI-friendly ID for the <see cref="ApiDescription"/>. E.g. "Get-Values-id_name" instead of "GetValues/{id}?name={name}" /// </summary> /// <param name="description">The <see cref="ApiDescription"/>.</param> /// <returns>The ID as a string.</returns> public static string GetFriendlyId(this ApiDescription description) { string path = description.RelativePath; string[] urlParts = path.Split('?'); string localPath = urlParts[0]; string queryKeyString = null; if (urlParts.Length > 1) { string query = urlParts[1]; string[] queryKeys = HttpUtility.ParseQueryString(query).AllKeys; queryKeyString = String.Join("_", queryKeys); } StringBuilder friendlyPath = new StringBuilder(); friendlyPath.AppendFormat("{0}-{1}", description.HttpMethod.Method, localPath.Replace("/", "-").Replace("{", String.Empty).Replace("}", String.Empty)); if (queryKeyString != null) { friendlyPath.AppendFormat("_{0}", queryKeyString.Replace('.', '-')); } return friendlyPath.ToString(); } } }
38.641026
144
0.573988
[ "MIT" ]
mkrtrptn/quickdemoemployee
quickdemoemployee/quickdemoemployee/Areas/HelpPage/ApiDescriptionExtensions.cs
1,507
C#
// <copyright file="GenerateCSClientInterop.cs" company="2018 Omar Tawfik"> // Copyright (c) 2018 Omar Tawfik. All rights reserved. Licensed under the MIT License. See LICENSE file in the project root for license information. // </copyright> namespace SmallBasic.Generators.Interop { using System.Collections.Generic; using System.Linq; using SmallBasic.Utilities; public sealed class GenerateCSClientInterop : BaseConverterTask<InteropTypeCollection> { protected override void Generate(InteropTypeCollection model) { this.Blank(); this.Line(@"/// <reference path=""../node_modules/@dotnet/jsinterop/dist/Microsoft.JSInterop.d.ts"" />"); this.Blank(); this.Line("export module CSIntrop {"); this.Indent(); foreach (InteropType type in model) { this.Line($"export module {type.Name} {{"); this.Indent(); foreach (Method method in type.Methods) { this.Line($"export function {method.Name.ToLowerFirstChar()}({method.Parameters.Select(p => $"{p.Name}: {p.Type}").Join(", ")}): Promise<{method.ReturnType ?? "void"}> {{"); this.Indent(); IEnumerable<string> arguments = new string[] { @"""SmallBasic.Editor""", $@"""CSIntrop.{type.Name}.{method.Name}""" }.Concat(method.Parameters.Select(p => p.Name)); if (method.ReturnType.IsDefault()) { this.Line($"return DotNet.invokeMethodAsync<boolean>({arguments.Join(", ")}).then(() => {{"); this.Indent(); this.Line("Promise.resolve();"); this.Unindent(); this.Line("});"); } else { this.Line($"return DotNet.invokeMethodAsync<{method.ReturnType}>({arguments.Join(", ")});"); } this.Unbrace(); } this.Unbrace(); } this.Unbrace(); } } }
37.816667
193
0.496695
[ "MIT" ]
alisonlu/smallbasic-editor
Source/SmallBasic.Generators/Interop/GenerateCSClientInterop.cs
2,271
C#
using System; namespace Build.Buildary { public class Travis { public enum EventTypeEnum { Push, PullRequest, Api, Cron, Unknown } public static bool IsTravis => Environment.GetEnvironmentVariable("TRAVIS") == "true"; public static EventTypeEnum EventType { get { switch(Environment.GetEnvironmentVariable("TRAVIS_EVENT_TYPE")) { case "push": return EventTypeEnum.Push; case "pull_request": return EventTypeEnum.PullRequest; case "api": return EventTypeEnum.Api; case "cron": return EventTypeEnum.Cron; default: return EventTypeEnum.Unknown; } } } public static bool IsTagBuild => !string.IsNullOrEmpty(Tag); public static string Tag => Environment.GetEnvironmentVariable("TRAVIS_TAG"); public static string Branch => Environment.GetEnvironmentVariable("TRAVIS_BRANCH"); public static string Commit => Environment.GetEnvironmentVariable("TRAVIS_COMMIT"); public static bool IsPullRequest { get { bool.TryParse(Environment.GetEnvironmentVariable("TRAVIS_PULL_REQUEST"), out var result); return result; } } } }
28.745455
105
0.508539
[ "MIT" ]
MaxMommersteeg/dotnet-buildary
Travis.cs
1,583
C#
public class Solution { public int TitleToNumber(string s) { if(string.IsNullOrEmpty(s)) return 0; int number = 0; int factor = 1; for(int i = s.Length - 1; i >= 0; --i) { int digit = s[i] - 'A' + 1; number += digit * factor; factor *= 26; } return number; } }
25.714286
46
0.455556
[ "MIT" ]
xtt129/LeetCode
C#/ExcelSheetColumnNumber.cs
360
C#
using System; namespace SpeakerMeet.API.Tests { internal class SpeakerService { private object _fakeRepository; private IGravatarService fakeGravatarService; public SpeakerService(object fakeRepository, IGravatarService fakeGravatarService) { _fakeRepository = fakeRepository; this.fakeGravatarService = fakeGravatarService; } public object Id { get; internal set; } internal object Get(object id) { throw new NotImplementedException(); } } }
24.652174
90
0.645503
[ "MIT" ]
nadvolod/speaker-meet
SpeakerMeet/SpeakerMeet/SpeakerService.cs
569
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.Buffers.Text; using System.Collections.Sequences; namespace System.Buffers { public static class Sequence { public static ReadOnlySpan<byte> ToSpan(this ReadOnlySequence<byte> sequence) { SequencePosition position = sequence.Start; ResizableArray<byte> array = new ResizableArray<byte>(1024); while (sequence.TryGet(ref position, out ReadOnlyMemory<byte> buffer)) { array.AddAll(buffer.Span); } array.Resize(array.Count); return array.Span.Slice(0, array.Count); } public static ReadOnlySpan<byte> ToSpan<T>(this T sequence) where T : ISequence<ReadOnlyMemory<byte>> { SequencePosition position = sequence.Start; ResizableArray<byte> array = new ResizableArray<byte>(1024); while (sequence.TryGet(ref position, out ReadOnlyMemory<byte> buffer)) { array.AddAll(buffer.Span); } array.Resize(array.Count); return array.Span.Slice(0, array.Count); } // TODO: this cannot be an extension method (as I would like it to be). // If I make it an extensions method, the compiler complains Span<T> cannot // be used as a type parameter. public static long IndexOf(ReadOnlySequence<byte> sequence, byte value) { SequencePosition position = sequence.Start; int totalIndex = 0; while (sequence.TryGet(ref position, out ReadOnlyMemory<byte> memory)) { var index = memory.Span.IndexOf(value); if (index != -1) return index + totalIndex; totalIndex += memory.Length; } return -1; } public static long IndexOf(ReadOnlySequence<byte> sequence, byte v1, byte v2) { SequencePosition position = sequence.Start; int totalIndex = 0; while (sequence.TryGet(ref position, out ReadOnlyMemory<byte> memory)) { var span = memory.Span; var index = span.IndexOf(v1); if (index != -1) { if (span.Length > index + 1) { if (span[index + 1] == v2) return index + totalIndex; else throw new NotImplementedException(); // need to check farther in the span } else { if (sequence.TryGet(ref position, out var next, false)) { var nextSpan = next.Span; if (nextSpan.Length > 0) { if (next.Span[0] == v2) return totalIndex + index; } } } } totalIndex += memory.Length; } return -1; } public static SequencePosition? PositionOf(this ReadOnlySequence<byte> sequence, byte value) { SequencePosition position = sequence.Start; SequencePosition result = position; while (sequence.TryGet(ref position, out ReadOnlyMemory<byte> memory)) { var index = MemoryExtensions.IndexOf(memory.Span, value); if (index != -1) { result = sequence.GetPosition(index, result); return result; } result = position; } return null; } public static SequencePosition? PositionAt(this ReadOnlySequence<byte> sequence, long index) { SequencePosition position = sequence.Start; SequencePosition result = position; while (sequence.TryGet(ref position, out ReadOnlyMemory<byte> memory)) { var span = memory.Span; if (span.Length > index) { result = sequence.GetPosition(index, result); return result; } index -= span.Length; result = position; } return null; } public static int Copy(ReadOnlySequence<byte> sequence, Span<byte> buffer) { int copied = 0; var position = sequence.Start; while (sequence.TryGet(ref position, out ReadOnlyMemory<byte> memory, true)) { var span = memory.Span; var toCopy = Math.Min(span.Length, buffer.Length - copied); span.Slice(0, toCopy).CopyTo(buffer.Slice(copied)); copied += toCopy; if (copied >= buffer.Length) break; } return copied; } public static int Copy(ReadOnlySequence<byte> sequence, SequencePosition from, Span<byte> buffer) { int copied = 0; while (sequence.TryGet(ref from, out ReadOnlyMemory<byte> memory, true)) { var span = memory.Span; var toCopy = Math.Min(span.Length, buffer.Length - copied); span.Slice(0, toCopy).CopyTo(buffer.Slice(copied)); copied += toCopy; if (copied >= buffer.Length) break; } return copied; } public static bool TryParse(ReadOnlySequence<byte> sequence, out int value, out int consumed) { var position = sequence.Start; if (sequence.TryGet(ref position, out ReadOnlyMemory<byte> memory)) { var span = memory.Span; if (Utf8Parser.TryParse(span, out value, out consumed) && consumed < span.Length) { return true; } Span<byte> temp = stackalloc byte[11]; // TODO: it would be good to have APIs to return constants related to sizes of needed buffers var copied = Copy(sequence, temp); // we need to slice temp, as we might stop zeroing stack allocated buffers if (Utf8Parser.TryParse(temp.Slice(0, copied), out value, out consumed)) { return true; } } value = default; consumed = default; return false; } public static bool TryParse(ReadOnlySequence<byte> sequence, out int value, out SequencePosition consumed) { if (!TryParse(sequence, out value, out int consumedBytes)) { consumed = default; return false; } consumed = sequence.PositionAt(consumedBytes).GetValueOrDefault(); return true; } } }
38.213904
148
0.519032
[ "MIT" ]
benaadams/corefxlab
src/System.Buffers.Experimental/System/Buffers/Sequences/SequenceExtensions.cs
7,148
C#
//----------------------------------------------------------------------------- // <copyright file="SqlDiagnosticListener.cs" company="Amazon.com"> // Copyright 2020 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. // </copyright> //----------------------------------------------------------------------------- #if !NET45 using Amazon.Runtime.Internal.Util; using Amazon.XRay.Recorder.AutoInstrumentation.Utils; using Amazon.XRay.Recorder.Core.Internal.Entities; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Data.Common; namespace Amazon.XRay.Recorder.AutoInstrumentation { /// <summary> /// Diagnostic listener for processing Sql query for System.Data.SqlClient and Microsoft.Data.SqlClient /// </summary> public class SqlDiagnosticListener : DiagnosticListenerBase { private static readonly Logger _logger = Logger.GetLogger(typeof(SqlDiagnosticListener)); internal override string Name => "SqlClientDiagnosticListener"; private static readonly ConcurrentDictionary<DbCommand, Subsegment> CurrentDbCommands = new ConcurrentDictionary<DbCommand, Subsegment>(); protected override void OnEvent(KeyValuePair<string, object> value) { try { switch (value.Key) { case "Microsoft.Data.SqlClient.WriteCommandBefore": { OnEventStart(value.Value); } break; case "System.Data.SqlClient.WriteCommandBefore": { OnEventStart(value.Value); } break; case "Microsoft.Data.SqlClient.WriteCommandAfter": { OnEventStop(value.Value); } break; case "System.Data.SqlClient.WriteCommandAfter": { OnEventStop(value.Value); } break; case "Microsoft.Data.SqlClient.WriteCommandError": { OnEventException(value.Value); } break; case "System.Data.SqlClient.WriteCommandError": { OnEventException(value.Value); } break; } } catch (Exception e) { _logger.Error(e, "Invalid diagnostic source key ({0})", value.Key); } } private void OnEventStart(object value) { // This class serves for tracing Sql command from both System.Data.SqlClient and Microsoft.Data.SqlClient and using fetch property works // fot both of these two cases var command = AgentUtil.FetchPropertyUsingReflection(value, "Command"); if (command is DbCommand dbcommand) { // Skip processing EntityFramework Core request if (SqlRequestUtil.IsTraceable() && CurrentDbCommands.TryAdd(dbcommand, null)) { SqlRequestUtil.BeginSubsegment(dbcommand); SqlRequestUtil.ProcessCommand(dbcommand); } } } private void OnEventStop(object value) { // This class serves for tracing Sql command from both System.Data.SqlClient and Microsoft.Data.SqlClient and using fetch property works // fot both of these two cases var command = AgentUtil.FetchPropertyUsingReflection(value, "Command"); if (command is DbCommand dbcommand) { if (CurrentDbCommands.TryRemove(dbcommand, out _)) { SqlRequestUtil.EndSubsegment(); } } } private void OnEventException(object value) { // This class serves for tracing Sql command from both System.Data.SqlClient and Microsoft.Data.SqlClient and using fetch property works // fot both of these two cases var command = AgentUtil.FetchPropertyUsingReflection(value, "Command"); var exc = AgentUtil.FetchPropertyUsingReflection(value, "Exception"); if (command is DbCommand dbcommand && exc is Exception exception) { if (CurrentDbCommands.TryRemove(dbcommand, out _)) { SqlRequestUtil.ProcessException(exception); SqlRequestUtil.EndSubsegment(); } } } } } #endif
41.037879
148
0.539413
[ "Apache-2.0" ]
QPC-database/aws-xray-dotnet-agent
src/sdk/Sql/SqlDiagnosticListener.cs
5,419
C#
using Microsoft.AspNetCore.Mvc; namespace Ion.MicroServices.ApiControllers.Demo.Controllers { [ApiController] [Route("[controller]")] public class WeatherForecastController : ControllerBase { private static readonly string[] Summaries = new[] { "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" }; private readonly ILogger<WeatherForecastController> _logger; public WeatherForecastController(ILogger<WeatherForecastController> logger) { this._logger = logger; } [HttpGet] public IEnumerable<WeatherForecast> Get() { return Enumerable.Range(1, 5).Select(index => new WeatherForecast { Date = DateTime.Now.AddDays(index), TemperatureC = Random.Shared.Next(-20, 55), Summary = Summaries[Random.Shared.Next(Summaries.Length)] }) .ToArray(); } } }
30.757576
106
0.596059
[ "MIT" ]
ionizd/ion
ion.microservices/ion-microservices-api-pkg/demo/Ion.MicroServices.ApiiControllers.Demo/Controllers/WeatherForecastController.cs
1,015
C#
using System; using System.Collections; using System.Collections.Generic; namespace Tests { internal class StrictReadOnlyList<T> : IReadOnlyList<T> { private readonly List<T> inner; public StrictReadOnlyList(IEnumerable<T> elements) => inner = new(elements); public T this[int index] => ((IReadOnlyList<T>)inner)[index]; public int Count => ((IReadOnlyCollection<T>)inner).Count; public IEnumerator<T> GetEnumerator() { throw new InvalidOperationException("The code should not use the enumerator for lists."); } IEnumerator IEnumerable.GetEnumerator() { throw new InvalidOperationException("The code should not use the enumerator for lists."); } } }
23.862069
92
0.731214
[ "MIT" ]
tsonto/ImmutableArraySegment
ImmutableArraySegment.Tests/StrictReadOnlyList.cs
694
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 Microsoft.TestUtilities; using Xunit; namespace Microsoft.AspNet.WebHooks { public class InstagramNotificationDataTests { private InstagramNotificationData _notificationData = new InstagramNotificationData(); [Fact] public void MediaId_Roundtrips() { PropertyAssert.Roundtrips(_notificationData, n => n.MediaId, PropertySetter.NullRoundtrips, roundtripValue: "Value"); } } }
30.8
129
0.720779
[ "Apache-2.0" ]
Mythz123/AspNetWebHooks
test/Microsoft.AspNet.WebHooks.Receivers.Instagram.Test/WebHooks/InstagramNotificationDataTests.cs
618
C#
using CodeWars; using NUnit.Framework; namespace CodeWarsTests { [TestFixture] public class GrasshopperBasicFunctionFixerTests { [Test] [TestCase(5, ExpectedResult = 10)] [TestCase(0, ExpectedResult = 5)] [TestCase(-5, ExpectedResult = 0)] public static int FixedTest(int num) { return GrasshopperBasicFunctionFixer.AddFive(num); } } }
23.388889
62
0.622328
[ "MIT" ]
a-kozhanov/codewars-csharp
CodeWarsTests/8kyu/GrasshopperBasicFunctionFixerTests.cs
423
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Dictionary_Builder.Properties { using System; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Dictionary_Builder.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } } }
43.75
184
0.615357
[ "Apache-2.0" ]
tanjera/infirmary-integrated
II Development Tools/Dictionary Builder/Properties/Resources.Designer.cs
2,802
C#
using Orchard.Localization; using Orchard.UI.Navigation; namespace Orchard.MediaLibrary.Providers { public class OEmbedMenu : INavigationProvider { public Localizer T { get; set; } public OEmbedMenu() { T = NullLocalizer.Instance; } public string MenuName { get { return "mediaproviders"; } } public void GetNavigation(NavigationBuilder builder) { builder.AddImageSet("oembed") .Add(T("Media Url"), "10", menu => menu.Action("Index", "OEmbed", new { area = "Orchard.MediaLibrary" }) .Permission(Permissions.ManageOwnMedia) .Permission(Permissions.ImportMediaContent)); } } }
33.818182
97
0.58871
[ "BSD-3-Clause" ]
1996dylanriley/Orchard
src/Orchard.Web/Modules/Orchard.MediaLibrary/Providers/OEmbedMenu.cs
746
C#
// SF API version v50.0 // Custom fields included: False // Relationship objects included: True using System; using NetCoreForce.Client.Models; using NetCoreForce.Client.Attributes; using Newtonsoft.Json; namespace NetCoreForce.Models { ///<summary> /// Flow Version ///<para>SObject Name: FlowVersionView</para> ///<para>Custom Object: False</para> ///</summary> public class SfFlowVersionView : SObject { [JsonIgnore] public static string SObjectTypeName { get { return "FlowVersionView"; } } ///<summary> /// Flow Version View ID /// <para>Name: Id</para> /// <para>SF Type: id</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "id")] [Updateable(false), Createable(false)] public string Id { get; set; } ///<summary> /// Durable ID /// <para>Name: DurableId</para> /// <para>SF Type: string</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "durableId")] [Updateable(false), Createable(false)] public string DurableId { get; set; } ///<summary> /// Flow Definition View ID /// <para>Name: FlowDefinitionViewId</para> /// <para>SF Type: string</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "flowDefinitionViewId")] [Updateable(false), Createable(false)] public string FlowDefinitionViewId { get; set; } ///<summary> /// Version Label /// <para>Name: Label</para> /// <para>SF Type: string</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "label")] [Updateable(false), Createable(false)] public string Label { get; set; } ///<summary> /// Version Description /// <para>Name: Description</para> /// <para>SF Type: string</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "description")] [Updateable(false), Createable(false)] public string Description { get; set; } ///<summary> /// Version Status /// <para>Name: Status</para> /// <para>SF Type: picklist</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "status")] [Updateable(false), Createable(false)] public string Status { get; set; } ///<summary> /// Version Number /// <para>Name: VersionNumber</para> /// <para>SF Type: int</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "versionNumber")] [Updateable(false), Createable(false)] public int? VersionNumber { get; set; } ///<summary> /// Process Type /// <para>Name: ProcessType</para> /// <para>SF Type: picklist</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "processType")] [Updateable(false), Createable(false)] public string ProcessType { get; set; } ///<summary> /// Is Template /// <para>Name: IsTemplate</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "isTemplate")] [Updateable(false), Createable(false)] public bool? IsTemplate { get; set; } ///<summary> /// Run in Mode /// <para>Name: RunInMode</para> /// <para>SF Type: picklist</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "runInMode")] [Updateable(false), Createable(false)] public string RunInMode { get; set; } ///<summary> /// Last Modified Date /// <para>Name: LastModifiedDate</para> /// <para>SF Type: datetime</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "lastModifiedDate")] [Updateable(false), Createable(false)] public DateTimeOffset? LastModifiedDate { get; set; } ///<summary> /// Is Swing Flow /// <para>Name: IsSwingFlow</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "isSwingFlow")] [Updateable(false), Createable(false)] public bool? IsSwingFlow { get; set; } ///<summary> /// Api Version /// <para>Name: ApiVersion</para> /// <para>SF Type: double</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "apiVersion")] [Updateable(false), Createable(false)] public double? ApiVersion { get; set; } ///<summary> /// Api Version Runtime /// <para>Name: ApiVersionRuntime</para> /// <para>SF Type: double</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "apiVersionRuntime")] [Updateable(false), Createable(false)] public double? ApiVersionRuntime { get; set; } } }
27.431138
55
0.644619
[ "MIT" ]
Mintish/NetCoreForce
src/NetCoreForce.Models/SfFlowVersionView.cs
4,581
C#
using Sce.Pss.Core; using System; namespace Sce.Pss.HighLevel.GameEngine2D { public class RotateBy : ActionTweenGenericVector2Rotation { public RotateBy(Vector2 target, float duration) { this.TargetValue = target; this.Duration = duration; this.IsRelative = true; this.Get = (() => base.Target.Rotation); this.Set = delegate(Vector2 value) { base.Target.Rotation = value; }; } } }
19.809524
58
0.692308
[ "MIT" ]
weimingtom/Sakura
Sce.Pss.HighLevel/GameEngine2D/RotateBy.cs
416
C#
using System; using System.Collections.Generic; using System.Text.RegularExpressions; using Microsoft.Extensions.DependencyInjection; using MigrationTools.Endpoints; namespace MigrationTools._EngineV1.Clients { public class WorkItemQueryBuilder : IWorkItemQueryBuilder { internal Dictionary<string, string> _parameters; internal string _Query; private readonly IServiceProvider _Services; public string Query { get => _Query; set => _Query = value; } public WorkItemQueryBuilder(IServiceProvider services) { _parameters = new Dictionary<string, string>(); _Services = services; } public void AddParameter(string name, string value) { if (_parameters.ContainsKey(name)) { throw new ArgumentException("The parameter key you are trying to add to the query already exists."); } _parameters.Add(name, value); } public IWorkItemQuery BuildWIQLQuery(IMigrationClient migrationClient) { if (string.IsNullOrEmpty(Query)) { throw new Exception("You must specify a Query"); } Query = WorkAroundForSOAPError(Query); // TODO: Remove this once bug fixed... https://dev.azure.com/nkdagility/migration-tools/_workitems/edit/5066 IWorkItemQuery wiq = _Services.GetRequiredService<IWorkItemQuery>(); wiq.Configure(migrationClient, _Query, _parameters); return wiq; } // Fix for Query SOAP error when passing parameters [Obsolete("Temporary work aorund for SOAP issue https://dev.azure.com/nkdagility/migration-tools/_workitems/edit/5066")] private string WorkAroundForSOAPError(string query) { foreach (var parameter in _parameters) { if (!int.TryParse(parameter.Value, out _)) { // only replace with pattern when not part of a larger string like an area path which is already quoted. query = Regex.Replace(query, $@"(?<=[=\s])@{parameter.Key}(?=$|\s)", $"'{parameter.Value}'"); } // replace the other occurences of this key query = query.Replace(string.Format($"@{parameter.Key}"), parameter.Value); } return query; } } }
38.492063
159
0.613196
[ "MIT" ]
Kota9006/TestMigration
src/MigrationTools/_EngineV1/Clients/WorkItemQueryBuilder.cs
2,427
C#
using System.Threading.Tasks; using NuKeeper.Abstractions.NuGet; using NuKeeper.Abstractions.RepositoryInspection; namespace NuKeeper.Update { public interface IUpdateRunner { Task Update(PackageUpdateSet updateSet, NuGetSources sources); } }
22
70
0.776515
[ "Apache-2.0" ]
Bouke/NuKeeper
NuKeeper.Update/IUpdateRunner.cs
264
C#
using System.Collections; using System.Collections.Generic; namespace Zpp.Mrp.MachineManagement { public class StackSet<T>:IStackSet<T> { private List<T> _list = new List<T>(); private int _count = 0; private Dictionary<T, int> _indices = new Dictionary<T, int>(); public StackSet() { } public StackSet(IEnumerable<T> list) { PushAll(list); } public void Push(T element) { // a set contains the element only once, else skip adding if (_indices.ContainsKey(element) == false) { _list.Add(element); _indices.Add(element, _count); _count++; } } public void Remove(T element) { if (element==null) { return; } _list.RemoveAt(_indices[element]); _count--; reIndexList(); } private void reIndexList() { _indices = new Dictionary<T, int>(); for(int i = 0; i < _count; i++) { _indices.Add(_list[i], i); } } public bool Any() { return _count > 0; } public T PopAny() { T element = _list[0]; _list.RemoveAt(0); _count--; return element; } public T GetAny() { return _list[0]; } IEnumerator IEnumerable.GetEnumerator() { return _list.GetEnumerator(); } public IEnumerator<T> GetEnumerator() { return _list.GetEnumerator(); } public void PushAll(IEnumerable<T> elements) { foreach (var element in elements) { Push(element); } } public int Count() { return _count; } public List<T> GetAll() { // create a copy of list List<T> all = new List<T>(); all.AddRange(_list); return all; } } }
21.653846
71
0.430728
[ "Apache-2.0" ]
LennertBerkhan/ng-erp-4.0
Zpp/Mrp/MachineManagement/StackSet.cs
2,252
C#
using RestWithASPNET.Model; using RestWithASPNET.Model.Base; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace RestWithASPNET.Repository.Generic { public interface IRepository<T> where T : BaseEntity { T Create(T item); T Update(T item); void Delete(long id); T FindByID(long id); List<T> FindAll(); bool Exists(long id); } }
18
56
0.662222
[ "Apache-2.0" ]
saulodacruz/RestWithASPNET5
02_RestWithASPNET_Calculator/RestWithASPNET/RestWithASPNET/Repository/Generic/IRepository.cs
452
C#
//********************************************************************* //Docify //Copyright(C) 2020 Xarial Pty Limited //Product URL: https://docify.net //License: https://docify.net/license/ //********************************************************************* using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Web; using Xarial.Docify.Base; using Xarial.Docify.Base.Data; using Xarial.Docify.Base.Exceptions; using Xarial.Docify.Base.Plugins; using Xarial.Docify.Lib.Plugins.CodeSnippet.Helpers; using Xarial.Docify.Lib.Plugins.CodeSnippet.Properties; using Xarial.Docify.Lib.Plugins.Common.Data; using Xarial.Docify.Lib.Plugins.Common.Exceptions; using Xarial.Docify.Lib.Plugins.Common.Helpers; namespace Xarial.Docify.Lib.Plugins.CodeSnippet { public class CodeSnippetPlugin : IPlugin<CodeSnippetSettings> { private CodeSnippetSettings m_Settings; private const string CSS_FILE_PATH = "/_assets/styles/code-snippet.css"; private const string JS_FILE_PATH = "/_assets/scripts/code-snippet.js"; private const char SNIPPETS_FOLDER_PATH = '~'; private IAssetsFolder m_SnippetsFolder; private List<string> m_SnippetFileIds; private Dictionary<IPage, List<string>> m_UsedTabIds; private Dictionary<IPage, List<string>> m_UsedSnippetIds; private ISite m_Site; private IDocifyApplication m_App; public void Init(IDocifyApplication app, CodeSnippetSettings setts) { m_App = app; m_Settings = setts; m_App.Compiler.PreCompile += OnPreCompile; m_App.Includes.RegisterCustomIncludeHandler("code-snippet", InsertCodeSnippet); m_App.Publisher.PrePublishFile += OnPrePublishFile; m_App.Compiler.WritePageContent += OnWritePageContent; } private Task OnPreCompile(ISite site) { m_Site = site; AssetsHelper.AddTextAsset(Resources.code_snippet_css, site.MainPage, CSS_FILE_PATH); AssetsHelper.AddTextAsset(Resources.code_snippet_js, site.MainPage, JS_FILE_PATH); m_SnippetFileIds = new List<string>(); m_UsedTabIds = new Dictionary<IPage, List<string>>(); m_UsedSnippetIds = new Dictionary<IPage, List<string>>(); if (!string.IsNullOrEmpty(m_Settings.SnippetsFolder)) { try { m_SnippetsFolder = site.MainPage.FindFolder(PluginLocation.FromPath(m_Settings.SnippetsFolder)); } catch (AssetNotFoundException) { throw new PluginUserMessageException($"Failed to find the folder for snippets: '{m_Settings.SnippetsFolder}'"); } foreach (var snipAsset in m_SnippetsFolder.GetAllAssets()) { m_SnippetFileIds.Add(snipAsset.Id); } } return Task.CompletedTask; } private async Task<string> InsertCodeSnippet(IMetadata data, IPage page) { var snipData = data.ToObject<CodeSnippetData>(); if (!string.IsNullOrEmpty(snipData.FileName) && snipData.Tabs?.Any() == true) { throw new PluginUserMessageException("Specify either file name or tabs"); } if (snipData.FileName?.EndsWith(".*") == true) { if (m_Settings.AutoTabs?.Any() != true) { throw new PluginUserMessageException($"{nameof(m_Settings.AutoTabs)} setting must be set to use automatic code snippet tabs"); } var fileName = snipData.FileName; var snipsFolder = FindSnippetFolder(m_Site, page, ref fileName); snipData.Tabs = new Dictionary<string, string>(); foreach (var asset in snipsFolder.Assets .Where(a => string.Equals(Path.GetFileNameWithoutExtension(a.FileName), Path.GetFileNameWithoutExtension(fileName), StringComparison.CurrentCultureIgnoreCase))) { string ext = Path.GetExtension(asset.FileName).TrimStart('.'); if (m_Settings.AutoTabs.TryGetValue(ext, out string tabName)) { snipData.Tabs.Add(tabName, Path.ChangeExtension(snipData.FileName, Path.GetExtension(asset.FileName))); } } } if (snipData.Tabs?.Any() == true) { var tabsHtml = new StringBuilder(); var tabsCode = new StringBuilder(); bool isFirst = true; var tabId = ConvertToId(snipData.Tabs.First().Value .Substring(0, snipData.Tabs.First().Value.LastIndexOf("."))); tabId = ResolveId(page, m_UsedTabIds, tabId); foreach (var tab in snipData.Tabs) { var tabName = tab.Key; var tabFile = tab.Value; var snipId = ConvertToId(tabFile); snipId = ResolveId(page, m_UsedSnippetIds, snipId); tabsHtml.AppendLine($"<button class=\"tablinks{(isFirst ? " active" : "")}\" onclick=\"openTab(event, '{tabId}', '{snipId}')\">{HttpUtility.HtmlEncode(tabName)}</button>"); tabsCode.AppendLine($"<div id=\"{snipId}\" class=\"tabcontent\" style=\"display: {(isFirst ? "block" : "none")}\">"); await WriteCodeSnippet(tabsCode, page, tabFile, snipData.Lang, snipData.ExclRegions, snipData.LeftAlign, snipData.Regions); tabsCode.AppendLine("</div>"); isFirst = false; } return string.Format(Resources.code_snippet_tab_container, tabId, tabsHtml.ToString(), tabsCode.ToString()); } else { var html = new StringBuilder(); await WriteCodeSnippet(html, page, snipData.FileName, snipData.Lang, snipData.ExclRegions, snipData.LeftAlign, snipData.Regions); return html.ToString(); } } private string ResolveId(IPage page, Dictionary<IPage, List<string>> usedPageIds, string idCandidate) { if (!usedPageIds.TryGetValue(page, out List<string> usedIds)) { usedIds = new List<string>(); usedPageIds.Add(page, usedIds); } int index = 0; var id = idCandidate; while (usedIds.Contains(id)) { id = idCandidate + (++index).ToString(); } usedIds.Add(id); return id; } private string ConvertToId(string val) => val .Replace(".", "-") .Replace("~", "-") .Replace("/", "-") .Replace("\\", "-") .Replace("::", "-") .Replace(" ", "-"); private async Task WriteCodeSnippet(StringBuilder html, IPage page, string filePath, string lang, string[] exclRegs, bool leftAlign, string[] regs) { IAsset snipAsset; try { var searchFolder = FindSnippetFolder(m_Site, page, ref filePath); var fileName = new PluginLocation("", Path.GetFileName(filePath), Enumerable.Empty<string>()); snipAsset = searchFolder.FindAsset(fileName); } catch (Exception ex) { throw new NullReferenceException($"Failed to find code snippet: '{filePath}'", ex); } if (snipAsset != null) { if (!m_SnippetFileIds.Contains(snipAsset.Id)) { m_SnippetFileIds.Add(snipAsset.Id); } var rawCode = snipAsset.AsTextContent(); if (string.IsNullOrEmpty(lang)) { lang = Path.GetExtension(snipAsset.FileName).TrimStart('.').ToLower(); } var snips = CodeSnippetHelper.Select(rawCode, lang, new CodeSelectorOptions() { ExcludeRegions = exclRegs, LeftAlign = leftAlign, Regions = regs }); foreach (var snip in snips) { var snipClass = ""; switch (snip.Location) { case SnippetLocation_e.Full: snipClass = ""; break; case SnippetLocation_e.Start: snipClass = "jagged-bottom"; break; case SnippetLocation_e.End: snipClass = "jagged-top"; break; case SnippetLocation_e.Middle: snipClass = "jagged"; break; } var code = $"~~~{lang} {snipClass}\r\n{snip.Code}\r\n~~~"; html.AppendLine(await m_App.Compiler.StaticContentTransformer.Transform(code)); } } else { throw new InvalidCastException($"Failed to find an asset at '{filePath}'"); } } private Task OnPrePublishFile(ILocation outLoc, PrePublishFileArgs args) { args.SkipFile = m_Settings.ExcludeSnippets && m_SnippetFileIds.Contains(args.File.Id); return Task.CompletedTask; } private Task OnWritePageContent(StringBuilder html, IMetadata data, string url) { if (html.Length > 0) { try { var writer = new HtmlHeadWriter(html); writer.AddStyleSheets(CSS_FILE_PATH); writer.AddScripts(JS_FILE_PATH); return Task.CompletedTask; } catch (Exception ex) { throw new HeadAssetLinkFailedException(CSS_FILE_PATH, url, ex); } } else { return Task.CompletedTask; } } private IAssetsFolder FindSnippetFolder(ISite site, IPage page, ref string snipLoc) { IAssetsFolder snippetsBaseFolder = null; if (snipLoc.StartsWith(SNIPPETS_FOLDER_PATH)) { if (m_SnippetsFolder == null) { throw new PluginUserMessageException("Snippets folder is not set"); } snipLoc = snipLoc.TrimStart(SNIPPETS_FOLDER_PATH); snippetsBaseFolder = m_SnippetsFolder; } else { snippetsBaseFolder = AssetsHelper.GetBaseFolder(site, page, PluginLocation.FromPath(snipLoc)); } return snippetsBaseFolder.FindFolder(PluginLocation.FromPath(snipLoc)); } } }
35.8625
192
0.525444
[ "MIT" ]
EddyAlleman/docify
lib/Plugins/Plugins.CodeSnippet/CodeSnippetPlugin.cs
11,478
C#
// <auto-generated> // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace FinnovationLabs.OpenBanking.Library.BankApiModels.UkObRw.V3p1p2.Pisp.Models { using Microsoft.Rest; using Newtonsoft.Json; using System.Linq; /// <summary> /// Unambiguous identification of the account of the debtor to which a /// debit entry will be made as a result of the transaction. /// </summary> public partial class OBWriteFileConsent3DataInitiationDebtorAccount { /// <summary> /// Initializes a new instance of the /// OBWriteFileConsent3DataInitiationDebtorAccount class. /// </summary> public OBWriteFileConsent3DataInitiationDebtorAccount() { CustomInit(); } /// <summary> /// Initializes a new instance of the /// OBWriteFileConsent3DataInitiationDebtorAccount class. /// </summary> /// <param name="name">The account name is the name or names of the /// account owner(s) represented at an account level, as displayed by /// the ASPSP's online channels. /// Note, the account name is not the product name or the nickname of /// the account.</param> public OBWriteFileConsent3DataInitiationDebtorAccount(string schemeName, string identification, string name = default(string), string secondaryIdentification = default(string)) { SchemeName = schemeName; Identification = identification; Name = name; SecondaryIdentification = secondaryIdentification; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// </summary> [JsonProperty(PropertyName = "SchemeName")] public string SchemeName { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "Identification")] public string Identification { get; set; } /// <summary> /// Gets or sets the account name is the name or names of the account /// owner(s) represented at an account level, as displayed by the /// ASPSP's online channels. /// Note, the account name is not the product name or the nickname of /// the account. /// </summary> [JsonProperty(PropertyName = "Name")] public string Name { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "SecondaryIdentification")] public string SecondaryIdentification { get; set; } /// <summary> /// Validate the object. /// </summary> /// <exception cref="ValidationException"> /// Thrown if validation fails /// </exception> public virtual void Validate() { if (SchemeName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "SchemeName"); } if (Identification == null) { throw new ValidationException(ValidationRules.CannotBeNull, "Identification"); } } } }
35.652632
184
0.605846
[ "MIT" ]
finlabsuk/open-banking-connector
src/OpenBanking.Library.BankApiModels/UkObRw/V3p1p2/Pisp/Models/OBWriteFileConsent3DataInitiationDebtorAccount.cs
3,387
C#
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public partial class TestControl : MonoBehaviour { #region manger Action<bool> m_curfunc; Action<bool> m_nextfunc; Action<bool> m_tempfunc; bool m_noWait; void _update() { while(true) { var bFirst = false; if (m_nextfunc!=null) { m_curfunc = m_nextfunc; m_nextfunc = null; bFirst = true; } m_noWait = false; if (m_curfunc!=null) { m_curfunc(bFirst); } if (!m_noWait) break; } } void Goto(Action<bool> func) { m_nextfunc = func; } bool CheckState(Action<bool> func) { return m_curfunc == func; } // for tempfunc void SetNextState(Action<bool> func) { m_tempfunc = func; } void GoNextState() { m_nextfunc = m_tempfunc; m_tempfunc = null; } bool HasNextState() { return m_tempfunc != null; } void NoWait() { m_noWait = true; } #endregion void _start() { Goto(S_START); } public bool IsEnd() { return CheckState(S_END); } #region // [SYN-G-GEN OUTPUT START] indent(8) $/./$ // psggConverterLib.dll converted from TestControl.xlsx. /* E_DEFOBJ */ GameObject m_obj; /* S_BRANCH 分岐する */ void S_BRANCH(bool bFirst) { int x = 0; if (bFirst) { x = UnityEngine.Random.Range(0,2); } // branch if (x==0) { SetNextState( S_CREATE_SPHERE ); } else { SetNextState( S_CREATE_CYLINDER ); } // if (HasNextState()) { GoNextState(); } } /* S_CHANGEPOS 位置変更 */ void S_CHANGEPOS(bool bFirst) { if (bFirst) { m_obj.transform.localPosition = Vector3.up; } // if (!HasNextState()) { SetNextState(S_MOVE); } // if (HasNextState()) { GoNextState(); } } /* S_CREATE_CUBE キューブ作成 */ void S_CREATE_CUBE(bool bFirst) { if (bFirst) { GameObject.CreatePrimitive(PrimitiveType.Cube); } // if (!HasNextState()) { SetNextState(S_BRANCH); } // if (HasNextState()) { GoNextState(); } } /* S_CREATE_CYLINDER シリンダー作成 */ void S_CREATE_CYLINDER(bool bFirst) { if (bFirst) { m_obj=GameObject.CreatePrimitive(PrimitiveType.Cylinder); } // if (!HasNextState()) { SetNextState(S_CHANGEPOS); } // if (HasNextState()) { GoNextState(); } } /* S_CREATE_SPHERE スフィア作成 */ void S_CREATE_SPHERE(bool bFirst) { if (bFirst) { m_obj = GameObject.CreatePrimitive(PrimitiveType.Sphere); } // if (!HasNextState()) { SetNextState(S_CHANGEPOS); } // if (HasNextState()) { GoNextState(); } } /* S_END */ void S_END(bool bFirst) { // if (HasNextState()) { GoNextState(); } } /* S_MOVE 移動 */ Vector3 m_start; Vector3 m_goal; float m_time; float m_elapsed; void S_MOVE(bool bFirst) { if (bFirst) { m_start = m_obj.transform.position; m_goal = new Vector3(5,5,5); m_time = 1; m_elapsed = 0; } m_elapsed += Time.deltaTime; var t = Mathf.Clamp01(m_elapsed / m_time); var pos = Vector3.Slerp(m_start,m_goal,t); m_obj.transform.position = pos; if (!(m_elapsed >= m_time)) return; // if (!HasNextState()) { SetNextState(S_END); } // if (HasNextState()) { GoNextState(); } } /* S_START */ void S_START(bool bFirst) { // if (!HasNextState()) { SetNextState(S_CREATE_CUBE); } // if (HasNextState()) { GoNextState(); } } #endregion // [SYN-G-GEN OUTPUT END] // write your code below bool m_bYesNo; void br_YES(Action<bool> st) { if (!HasNextState()) { if (m_bYesNo) { SetNextState(st); } } } void br_NO(Action<bool> st) { if (!HasNextState()) { if (!m_bYesNo) { SetNextState(st); } } } #region Monobehaviour framework void Start() { _start(); } void Update() { if (!IsEnd()) { _update(); } } #endregion }
20.496479
73
0.396324
[ "MIT" ]
NNNIC/psgg-unity-tutorial
_beta/Tutorial03/Assets/TestControl.cs
5,881
C#
/******************************************************************************* * Copyright 2012-2019 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. * ***************************************************************************** * * AWS Tools for Windows (TM) PowerShell (TM) * */ using System; using System.Collections.Generic; using System.Linq; using System.Management.Automation; using System.Text; using Amazon.PowerShell.Common; using Amazon.Runtime; using Amazon.Neptune; using Amazon.Neptune.Model; namespace Amazon.PowerShell.Cmdlets.NPT { /// <summary> /// Returns the default engine and system parameter information for the specified database /// engine. /// </summary> [Cmdlet("Get", "NPTEngineDefaultParameter")] [OutputType("Amazon.Neptune.Model.EngineDefaults")] [AWSCmdlet("Calls the Amazon Neptune DescribeEngineDefaultParameters API operation.", Operation = new[] {"DescribeEngineDefaultParameters"}, SelectReturnType = typeof(Amazon.Neptune.Model.DescribeEngineDefaultParametersResponse))] [AWSCmdletOutput("Amazon.Neptune.Model.EngineDefaults or Amazon.Neptune.Model.DescribeEngineDefaultParametersResponse", "This cmdlet returns an Amazon.Neptune.Model.EngineDefaults object.", "The service call response (type Amazon.Neptune.Model.DescribeEngineDefaultParametersResponse) can also be referenced from properties attached to the cmdlet entry in the $AWSHistory stack." )] public partial class GetNPTEngineDefaultParameterCmdlet : AmazonNeptuneClientCmdlet, IExecutor { #region Parameter DBParameterGroupFamily /// <summary> /// <para> /// <para>The name of the DB parameter group family.</para> /// </para> /// </summary> #if !MODULAR [System.Management.Automation.Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true)] #else [System.Management.Automation.Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true, Mandatory = true)] [System.Management.Automation.AllowEmptyString] [System.Management.Automation.AllowNull] #endif [Amazon.PowerShell.Common.AWSRequiredParameter] public System.String DBParameterGroupFamily { get; set; } #endregion #region Parameter Filter /// <summary> /// <para> /// <para>Not currently supported.</para> /// </para> /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] [Alias("Filters")] public Amazon.Neptune.Model.Filter[] Filter { get; set; } #endregion #region Parameter Marker /// <summary> /// <para> /// <para> An optional pagination token provided by a previous <code>DescribeEngineDefaultParameters</code> /// request. If this parameter is specified, the response includes only records beyond /// the marker, up to the value specified by <code>MaxRecords</code>.</para> /// </para> /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public System.String Marker { get; set; } #endregion #region Parameter MaxRecord /// <summary> /// <para> /// <para> The maximum number of records to include in the response. If more records exist than /// the specified <code>MaxRecords</code> value, a pagination token called a marker is /// included in the response so that the remaining results can be retrieved.</para><para>Default: 100</para><para>Constraints: Minimum 20, maximum 100.</para> /// </para> /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] [Alias("MaxRecords")] public System.Int32? MaxRecord { get; set; } #endregion #region Parameter Select /// <summary> /// Use the -Select parameter to control the cmdlet output. The default value is 'EngineDefaults'. /// Specifying -Select '*' will result in the cmdlet returning the whole service response (Amazon.Neptune.Model.DescribeEngineDefaultParametersResponse). /// Specifying the name of a property of type Amazon.Neptune.Model.DescribeEngineDefaultParametersResponse will result in that property being returned. /// Specifying -Select '^ParameterName' will result in the cmdlet returning the selected cmdlet parameter value. /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public string Select { get; set; } = "EngineDefaults"; #endregion #region Parameter PassThru /// <summary> /// Changes the cmdlet behavior to return the value passed to the DBParameterGroupFamily parameter. /// The -PassThru parameter is deprecated, use -Select '^DBParameterGroupFamily' instead. This parameter will be removed in a future version. /// </summary> [System.Obsolete("The -PassThru parameter is deprecated, use -Select '^DBParameterGroupFamily' instead. This parameter will be removed in a future version.")] [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public SwitchParameter PassThru { get; set; } #endregion protected override void ProcessRecord() { base.ProcessRecord(); var context = new CmdletContext(); // allow for manipulation of parameters prior to loading into context PreExecutionContextLoad(context); #pragma warning disable CS0618, CS0612 //A class member was marked with the Obsolete attribute if (ParameterWasBound(nameof(this.Select))) { context.Select = CreateSelectDelegate<Amazon.Neptune.Model.DescribeEngineDefaultParametersResponse, GetNPTEngineDefaultParameterCmdlet>(Select) ?? throw new System.ArgumentException("Invalid value for -Select parameter.", nameof(this.Select)); if (this.PassThru.IsPresent) { throw new System.ArgumentException("-PassThru cannot be used when -Select is specified.", nameof(this.Select)); } } else if (this.PassThru.IsPresent) { context.Select = (response, cmdlet) => this.DBParameterGroupFamily; } #pragma warning restore CS0618, CS0612 //A class member was marked with the Obsolete attribute context.DBParameterGroupFamily = this.DBParameterGroupFamily; #if MODULAR if (this.DBParameterGroupFamily == null && ParameterWasBound(nameof(this.DBParameterGroupFamily))) { WriteWarning("You are passing $null as a value for parameter DBParameterGroupFamily which is marked as required. In case you believe this parameter was incorrectly marked as required, report this by opening an issue at https://github.com/aws/aws-tools-for-powershell/issues."); } #endif if (this.Filter != null) { context.Filter = new List<Amazon.Neptune.Model.Filter>(this.Filter); } context.Marker = this.Marker; context.MaxRecord = this.MaxRecord; // allow further manipulation of loaded context prior to processing PostExecutionContextLoad(context); var output = Execute(context) as CmdletOutput; ProcessOutput(output); } #region IExecutor Members public object Execute(ExecutorContext context) { var cmdletContext = context as CmdletContext; // create request var request = new Amazon.Neptune.Model.DescribeEngineDefaultParametersRequest(); if (cmdletContext.DBParameterGroupFamily != null) { request.DBParameterGroupFamily = cmdletContext.DBParameterGroupFamily; } if (cmdletContext.Filter != null) { request.Filters = cmdletContext.Filter; } if (cmdletContext.Marker != null) { request.Marker = cmdletContext.Marker; } if (cmdletContext.MaxRecord != null) { request.MaxRecords = cmdletContext.MaxRecord.Value; } CmdletOutput output; // issue call var client = Client ?? CreateClient(_CurrentCredentials, _RegionEndpoint); try { var response = CallAWSServiceOperation(client, request); object pipelineOutput = null; pipelineOutput = cmdletContext.Select(response, this); output = new CmdletOutput { PipelineOutput = pipelineOutput, ServiceResponse = response }; } catch (Exception e) { output = new CmdletOutput { ErrorResponse = e }; } return output; } public ExecutorContext CreateContext() { return new CmdletContext(); } #endregion #region AWS Service Operation Call private Amazon.Neptune.Model.DescribeEngineDefaultParametersResponse CallAWSServiceOperation(IAmazonNeptune client, Amazon.Neptune.Model.DescribeEngineDefaultParametersRequest request) { Utils.Common.WriteVerboseEndpointMessage(this, client.Config, "Amazon Neptune", "DescribeEngineDefaultParameters"); try { #if DESKTOP return client.DescribeEngineDefaultParameters(request); #elif CORECLR return client.DescribeEngineDefaultParametersAsync(request).GetAwaiter().GetResult(); #else #error "Unknown build edition" #endif } catch (AmazonServiceException exc) { var webException = exc.InnerException as System.Net.WebException; if (webException != null) { throw new Exception(Utils.Common.FormatNameResolutionFailureMessage(client.Config, webException.Message), webException); } throw; } } #endregion internal partial class CmdletContext : ExecutorContext { public System.String DBParameterGroupFamily { get; set; } public List<Amazon.Neptune.Model.Filter> Filter { get; set; } public System.String Marker { get; set; } public System.Int32? MaxRecord { get; set; } public System.Func<Amazon.Neptune.Model.DescribeEngineDefaultParametersResponse, GetNPTEngineDefaultParameterCmdlet, object> Select { get; set; } = (response, cmdlet) => response.EngineDefaults; } } }
46.031008
293
0.617969
[ "Apache-2.0" ]
5u5hma/aws-tools-for-powershell
modules/AWSPowerShell/Cmdlets/Neptune/Basic/Get-NPTEngineDefaultParameter-Cmdlet.cs
11,876
C#
using AspNetCoreHero.Boilerplate.Application.Interfaces.Repositories; using AspNetCoreHero.Boilerplate.Infrastructure.DbContexts; using Microsoft.Extensions.Caching.Distributed; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AspNetCoreHero.Boilerplate.Infrastructure.Repositories { public class RepositoryWrapper : IRepositoryWrapper { private readonly ApplicationDbContext _repositoryContext; private readonly IDistributedCache _distributedCache; private IBrandRepository _brandRepository; private IProductRepository _productRepository; public IBrandRepository Brand { get { if (_brandRepository == null) { _brandRepository = new BrandRepository(_repositoryContext, _distributedCache); } return _brandRepository; } } public IProductRepository Product { get { if (_productRepository == null) { _productRepository = new ProductRepository(_repositoryContext, _distributedCache); } return _productRepository; } } public RepositoryWrapper(IDistributedCache distributedCache, ApplicationDbContext repositoryContext) { _distributedCache = distributedCache; _repositoryContext = repositoryContext; } } }
29.509434
108
0.641304
[ "MIT" ]
timsar2/Boilerplate
AspNetCoreHero.Boilerplate.Infrastructure/Repositories/RepositoryWrapper.cs
1,566
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using DotLiquid; using Newtonsoft.Json.Linq; namespace Tonk.DOM { internal static class Merger { private static readonly Regex ExtractCommandsRegex = new Regex(@"<Text.*?>(\{%.+?%\})<\/Text>"); public static string Merge(string json, string dom) { Template.RegisterFilter(typeof(ImageFilter)); Template.RegisterFilter(typeof(LinkFilter)); var template = Template.Parse(dom); // Compile the template var drop = Dropifier.Dropify(json); // Convert JSON => DotLiquid Hash return template.Render(drop); // Fill fields } } public static class ImageFilter { public static string Imagify(object input, string format, string wazoo) { if (input == null) return null; else if (string.IsNullOrWhiteSpace(format)) return input.ToString(); Console.WriteLine(format); Console.WriteLine(wazoo); return "image{" + input.ToString() + "}"; } } public static class LinkFilter { public static string Linkify(Context context, string input) { Console.WriteLine(context); Console.WriteLine(context["height"]); return "link{" + input + "}"; } } }
26.350877
104
0.593209
[ "MIT" ]
willgeorgetaylor/tonk
Tonk.DOM/Merger.cs
1,504
C#
#region License /* Copyright © 2014-2018 European Support Limited 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 using Amdocs.Ginger.Repository; using GingerWPF.WizardLib; using System.Windows.Controls; namespace GingerWPF.PluginsLib.AddPluginWizardLib { /// <summary> /// Interaction logic for AddPluginToSolutionPage.xaml /// </summary> public partial class AddPluginPackageToSolutionPage : Page, IWizardPage { PluginPackage mPluginPackage; public AddPluginPackageToSolutionPage() { InitializeComponent(); } public void WizardEvent(WizardEventArgs WizardEventArgs) { } } }
28
75
0.727041
[ "Apache-2.0" ]
DebasmitaGhosh/Ginger
Ginger/Ginger/PluginsLibNew/AddPluginWizardLib/AddPluginPackageToSolutionPage.xaml.cs
1,177
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.Devices.V20170821Preview { /// <summary> /// The description of the provisioning service. /// </summary> [AzureNativeResourceType("azure-native:devices/v20170821preview:IotDpsResource")] public partial class IotDpsResource : Pulumi.CustomResource { /// <summary> /// The Etag field is *not* required. If it is provided in the response body, it must also be provided as a header per the normal ETag convention. /// </summary> [Output("etag")] public Output<string?> Etag { get; private set; } = null!; /// <summary> /// The resource location. /// </summary> [Output("location")] public Output<string> Location { get; private set; } = null!; /// <summary> /// The resource name. /// </summary> [Output("name")] public Output<string> Name { get; private set; } = null!; [Output("properties")] public Output<Outputs.IotDpsPropertiesDescriptionResponse> Properties { get; private set; } = null!; /// <summary> /// List of possible provisioning service SKUs. /// </summary> [Output("sku")] public Output<Outputs.IotDpsSkuInfoResponse> Sku { get; private set; } = null!; /// <summary> /// The resource tags. /// </summary> [Output("tags")] public Output<ImmutableDictionary<string, string>?> Tags { get; private set; } = null!; /// <summary> /// The resource type. /// </summary> [Output("type")] public Output<string> Type { get; private set; } = null!; /// <summary> /// Create a IotDpsResource resource with the given unique name, arguments, and options. /// </summary> /// /// <param name="name">The unique name of the resource</param> /// <param name="args">The arguments used to populate this resource's properties</param> /// <param name="options">A bag of options that control this resource's behavior</param> public IotDpsResource(string name, IotDpsResourceArgs args, CustomResourceOptions? options = null) : base("azure-native:devices/v20170821preview:IotDpsResource", name, args ?? new IotDpsResourceArgs(), MakeResourceOptions(options, "")) { } private IotDpsResource(string name, Input<string> id, CustomResourceOptions? options = null) : base("azure-native:devices/v20170821preview:IotDpsResource", name, null, MakeResourceOptions(options, id)) { } private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id) { var defaultOptions = new CustomResourceOptions { Version = Utilities.Version, Aliases = { new Pulumi.Alias { Type = "azure-nextgen:devices/v20170821preview:IotDpsResource"}, new Pulumi.Alias { Type = "azure-native:devices:IotDpsResource"}, new Pulumi.Alias { Type = "azure-nextgen:devices:IotDpsResource"}, new Pulumi.Alias { Type = "azure-native:devices/v20171115:IotDpsResource"}, new Pulumi.Alias { Type = "azure-nextgen:devices/v20171115:IotDpsResource"}, new Pulumi.Alias { Type = "azure-native:devices/v20180122:IotDpsResource"}, new Pulumi.Alias { Type = "azure-nextgen:devices/v20180122:IotDpsResource"}, new Pulumi.Alias { Type = "azure-native:devices/v20200101:IotDpsResource"}, new Pulumi.Alias { Type = "azure-nextgen:devices/v20200101:IotDpsResource"}, new Pulumi.Alias { Type = "azure-native:devices/v20200301:IotDpsResource"}, new Pulumi.Alias { Type = "azure-nextgen:devices/v20200301:IotDpsResource"}, new Pulumi.Alias { Type = "azure-native:devices/v20200901preview:IotDpsResource"}, new Pulumi.Alias { Type = "azure-nextgen:devices/v20200901preview:IotDpsResource"}, }, }; var merged = CustomResourceOptions.Merge(defaultOptions, options); // Override the ID if one was specified for consistency with other language SDKs. merged.Id = id ?? merged.Id; return merged; } /// <summary> /// Get an existing IotDpsResource resource's state with the given name, ID, and optional extra /// properties used to qualify the lookup. /// </summary> /// /// <param name="name">The unique name of the resulting resource.</param> /// <param name="id">The unique provider ID of the resource to lookup.</param> /// <param name="options">A bag of options that control this resource's behavior</param> public static IotDpsResource Get(string name, Input<string> id, CustomResourceOptions? options = null) { return new IotDpsResource(name, id, options); } } public sealed class IotDpsResourceArgs : Pulumi.ResourceArgs { /// <summary> /// The Etag field is *not* required. If it is provided in the response body, it must also be provided as a header per the normal ETag convention. /// </summary> [Input("etag")] public Input<string>? Etag { get; set; } /// <summary> /// The resource location. /// </summary> [Input("location")] public Input<string>? Location { get; set; } [Input("properties", required: true)] public Input<Inputs.IotDpsPropertiesDescriptionArgs> Properties { get; set; } = null!; /// <summary> /// Name of provisioning service to create or update. /// </summary> [Input("provisioningServiceName")] public Input<string>? ProvisioningServiceName { get; set; } /// <summary> /// Resource group identifier. /// </summary> [Input("resourceGroupName", required: true)] public Input<string> ResourceGroupName { get; set; } = null!; /// <summary> /// List of possible provisioning service SKUs. /// </summary> [Input("sku", required: true)] public Input<Inputs.IotDpsSkuInfoArgs> Sku { get; set; } = null!; [Input("tags")] private InputMap<string>? _tags; /// <summary> /// The resource tags. /// </summary> public InputMap<string> Tags { get => _tags ?? (_tags = new InputMap<string>()); set => _tags = value; } public IotDpsResourceArgs() { } } }
42.005952
154
0.597563
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/Devices/V20170821Preview/IotDpsResource.cs
7,057
C#
using System; using System.Linq; using UnityEngine; using UnityEditor; using System.Collections.Generic; namespace Assets { [CustomEditor(typeof(Road))] class RoadEditor : Editor { public static void RefreshRoadPoints(Road road) { road.roadPoints = new List<Transform>(); for (int i = 0; i < road.transform.childCount; ++i) { road.roadPoints.Add(road.transform.GetChild(i)); } } public override void OnInspectorGUI() { DrawDefaultInspector(); if (GUILayout.Button("Refresh Segment List")) { RefreshRoadPoints((Road)target); } } } }
22.454545
64
0.54251
[ "CC0-1.0" ]
zak-reynolds/phoenix-overdrive
Assets/Editor/RoadEditor.cs
743
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using TMPro; namespace GUI { public class Item : MovieClip { public TextMeshPro field; public Container container; public float width; /*------------------------------------------------------------------------ CONSTRUCTEUR ------------------------------------------------------------------------*/ protected Item(string reference) : base(reference) { } /*------------------------------------------------------------------------ D�FINI LE LABEL ------------------------------------------------------------------------*/ public virtual void SetLabel(string l) { FindTextfield("field").text = l ; field.rectTransform.sizeDelta += new Vector2(5, 0); // TODO check actionscript textfield width } /*------------------------------------------------------------------------ RESIZE ------------------------------------------------------------------------*/ public void Scale(float ratio) { _xscale = ratio; _yscale = ratio; } /*------------------------------------------------------------------------ INITIALISATION ------------------------------------------------------------------------*/ protected void Init(Container c, string l) { container = c ; SetLabel(l) ; var p = container.Insert(this) ; _x = p.x ; _y = p.y ; } public virtual void HammerUpdate() { } } }
25.722222
96
0.396688
[ "CC0-1.0" ]
Schnips12/Hammerfest-united
Assets/Scripts/GUI/Item.cs
1,391
C#
using System.IO; using System.Runtime.Serialization; using WolvenKit.CR2W.Reflection; using FastMember; using static WolvenKit.CR2W.Types.Enums; namespace WolvenKit.CR2W.Types { [DataContract(Namespace = "")] [REDMeta] public class CStorySceneEventAnimation : CStorySceneEventAnimClip { [Ordinal(1)] [RED("animationName")] public CName AnimationName { get; set;} [Ordinal(2)] [RED("useMotionExtraction")] public CBool UseMotionExtraction { get; set;} [Ordinal(3)] [RED("useFakeMotion")] public CBool UseFakeMotion { get; set;} [Ordinal(4)] [RED("gatherSyncTokens")] public CBool GatherSyncTokens { get; set;} [Ordinal(5)] [RED("muteSoundEvents")] public CBool MuteSoundEvents { get; set;} [Ordinal(6)] [RED("disableLookAt")] public CBool DisableLookAt { get; set;} [Ordinal(7)] [RED("disableLookAtSpeed")] public CFloat DisableLookAtSpeed { get; set;} [Ordinal(8)] [RED("useLowerBodyPartsForLookAt")] public CBool UseLowerBodyPartsForLookAt { get; set;} [Ordinal(9)] [RED("bonesGroupName")] public CString BonesGroupName { get; set;} [Ordinal(10)] [RED("bones", 2,0)] public CArray<SBehaviorGraphBoneInfo> Bones { get; set;} [Ordinal(11)] [RED("bonesIdx", 2,0)] public CArray<CInt32> BonesIdx { get; set;} [Ordinal(12)] [RED("bonesWeight", 2,0)] public CArray<CFloat> BonesWeight { get; set;} [Ordinal(13)] [RED("status")] public CName Status { get; set;} [Ordinal(14)] [RED("emotionalState")] public CName EmotionalState { get; set;} [Ordinal(15)] [RED("poseName")] public CName PoseName { get; set;} [Ordinal(16)] [RED("typeName")] public CName TypeName { get; set;} [Ordinal(17)] [RED("friendlyName")] public CString FriendlyName { get; set;} [Ordinal(18)] [RED("animationType")] public CEnum<EStorySceneAnimationType> AnimationType { get; set;} [Ordinal(19)] [RED("addConvertToAdditive")] public CBool AddConvertToAdditive { get; set;} [Ordinal(20)] [RED("addAdditiveType")] public CEnum<EAdditiveType> AddAdditiveType { get; set;} [Ordinal(21)] [RED("recacheWeightCurve")] public CBool RecacheWeightCurve { get; set;} [Ordinal(22)] [RED("useWeightCurve")] public CBool UseWeightCurve { get; set;} [Ordinal(23)] [RED("weightCurve")] public SCurveData WeightCurve { get; set;} [Ordinal(24)] [RED("weightCurveChanged")] public CBool WeightCurveChanged { get; set;} [Ordinal(25)] [RED("supportsMotionExClipFront")] public CBool SupportsMotionExClipFront { get; set;} public CStorySceneEventAnimation(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name){ } public static new CVariable Create(CR2WFile cr2w, CVariable parent, string name) => new CStorySceneEventAnimation(cr2w, parent, name); public override void Read(BinaryReader file, uint size) => base.Read(file, size); public override void Write(BinaryWriter file) => base.Write(file); } }
40.821918
137
0.690268
[ "MIT" ]
DerinHalil/CP77Tools
CP77.CR2W/Types/W3/RTTIConvert/CStorySceneEventAnimation.cs
2,908
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Locust.Compression { public interface ICompression { byte[] Compress(byte[] data); byte[] Decompress(byte[] data); Stream Compress(Stream data); Stream Decompress(Stream data); Task<byte[]> CompressAsync(byte[] data); Task<byte[]> DecompressAsync(byte[] data); Task<Stream> CompressAsync(Stream data); Task<Stream> DecompressAsync(Stream data); } }
25.909091
50
0.668421
[ "MIT" ]
mansoor-omrani/Locust.NET
Library/Locust.Compression/ICompression.cs
572
C#
using System; using System.Collections.Generic; using System.IdentityModel.Tokens.Jwt; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Abp.Authorization; using Abp.Authorization.Users; using Abp.MultiTenancy; using Abp.Runtime.Security; using Abp.UI; using TodoList.Authentication.External; using TodoList.Authentication.JwtBearer; using TodoList.Authorization; using TodoList.Authorization.Users; using TodoList.Models.TokenAuth; using TodoList.MultiTenancy; namespace TodoList.Controllers { [Route("api/[controller]/[action]")] public class TokenAuthController : TodoListControllerBase { private readonly LogInManager _logInManager; private readonly ITenantCache _tenantCache; private readonly AbpLoginResultTypeHelper _abpLoginResultTypeHelper; private readonly TokenAuthConfiguration _configuration; private readonly IExternalAuthConfiguration _externalAuthConfiguration; private readonly IExternalAuthManager _externalAuthManager; private readonly UserRegistrationManager _userRegistrationManager; public TokenAuthController( LogInManager logInManager, ITenantCache tenantCache, AbpLoginResultTypeHelper abpLoginResultTypeHelper, TokenAuthConfiguration configuration, IExternalAuthConfiguration externalAuthConfiguration, IExternalAuthManager externalAuthManager, UserRegistrationManager userRegistrationManager) { _logInManager = logInManager; _tenantCache = tenantCache; _abpLoginResultTypeHelper = abpLoginResultTypeHelper; _configuration = configuration; _externalAuthConfiguration = externalAuthConfiguration; _externalAuthManager = externalAuthManager; _userRegistrationManager = userRegistrationManager; } [HttpPost] public async Task<AuthenticateResultModel> Authenticate([FromBody] AuthenticateModel model) { var loginResult = await GetLoginResultAsync( model.UserNameOrEmailAddress, model.Password, GetTenancyNameOrNull() ); var accessToken = CreateAccessToken(CreateJwtClaims(loginResult.Identity)); return new AuthenticateResultModel { AccessToken = accessToken, EncryptedAccessToken = GetEncryptedAccessToken(accessToken), ExpireInSeconds = (int)_configuration.Expiration.TotalSeconds, UserId = loginResult.User.Id }; } [HttpGet] public List<ExternalLoginProviderInfoModel> GetExternalAuthenticationProviders() { return ObjectMapper.Map<List<ExternalLoginProviderInfoModel>>(_externalAuthConfiguration.Providers); } [HttpPost] public async Task<ExternalAuthenticateResultModel> ExternalAuthenticate([FromBody] ExternalAuthenticateModel model) { var externalUser = await GetExternalUserInfo(model); var loginResult = await _logInManager.LoginAsync(new UserLoginInfo(model.AuthProvider, model.ProviderKey, model.AuthProvider), GetTenancyNameOrNull()); switch (loginResult.Result) { case AbpLoginResultType.Success: { var accessToken = CreateAccessToken(CreateJwtClaims(loginResult.Identity)); return new ExternalAuthenticateResultModel { AccessToken = accessToken, EncryptedAccessToken = GetEncryptedAccessToken(accessToken), ExpireInSeconds = (int)_configuration.Expiration.TotalSeconds }; } case AbpLoginResultType.UnknownExternalLogin: { var newUser = await RegisterExternalUserAsync(externalUser); if (!newUser.IsActive) { return new ExternalAuthenticateResultModel { WaitingForActivation = true }; } // Try to login again with newly registered user! loginResult = await _logInManager.LoginAsync(new UserLoginInfo(model.AuthProvider, model.ProviderKey, model.AuthProvider), GetTenancyNameOrNull()); if (loginResult.Result != AbpLoginResultType.Success) { throw _abpLoginResultTypeHelper.CreateExceptionForFailedLoginAttempt( loginResult.Result, model.ProviderKey, GetTenancyNameOrNull() ); } return new ExternalAuthenticateResultModel { AccessToken = CreateAccessToken(CreateJwtClaims(loginResult.Identity)), ExpireInSeconds = (int)_configuration.Expiration.TotalSeconds }; } default: { throw _abpLoginResultTypeHelper.CreateExceptionForFailedLoginAttempt( loginResult.Result, model.ProviderKey, GetTenancyNameOrNull() ); } } } private async Task<User> RegisterExternalUserAsync(ExternalAuthUserInfo externalUser) { var user = await _userRegistrationManager.RegisterAsync( externalUser.Name, externalUser.Surname, externalUser.EmailAddress, externalUser.EmailAddress, Authorization.Users.User.CreateRandomPassword(), true ); user.Logins = new List<UserLogin> { new UserLogin { LoginProvider = externalUser.Provider, ProviderKey = externalUser.ProviderKey, TenantId = user.TenantId } }; await CurrentUnitOfWork.SaveChangesAsync(); return user; } private async Task<ExternalAuthUserInfo> GetExternalUserInfo(ExternalAuthenticateModel model) { var userInfo = await _externalAuthManager.GetUserInfo(model.AuthProvider, model.ProviderAccessCode); if (userInfo.ProviderKey != model.ProviderKey) { throw new UserFriendlyException(L("CouldNotValidateExternalUser")); } return userInfo; } private string GetTenancyNameOrNull() { if (!AbpSession.TenantId.HasValue) { return null; } return _tenantCache.GetOrNull(AbpSession.TenantId.Value)?.TenancyName; } private async Task<AbpLoginResult<Tenant, User>> GetLoginResultAsync(string usernameOrEmailAddress, string password, string tenancyName) { var loginResult = await _logInManager.LoginAsync(usernameOrEmailAddress, password, tenancyName); switch (loginResult.Result) { case AbpLoginResultType.Success: return loginResult; default: throw _abpLoginResultTypeHelper.CreateExceptionForFailedLoginAttempt(loginResult.Result, usernameOrEmailAddress, tenancyName); } } private string CreateAccessToken(IEnumerable<Claim> claims, TimeSpan? expiration = null) { var now = DateTime.UtcNow; var jwtSecurityToken = new JwtSecurityToken( issuer: _configuration.Issuer, audience: _configuration.Audience, claims: claims, notBefore: now, expires: now.Add(expiration ?? _configuration.Expiration), signingCredentials: _configuration.SigningCredentials ); return new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken); } private static List<Claim> CreateJwtClaims(ClaimsIdentity identity) { var claims = identity.Claims.ToList(); var nameIdClaim = claims.First(c => c.Type == ClaimTypes.NameIdentifier); // Specifically add the jti (random nonce), iat (issued timestamp), and sub (subject/user) claims. claims.AddRange(new[] { new Claim(JwtRegisteredClaimNames.Sub, nameIdClaim.Value), new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), new Claim(JwtRegisteredClaimNames.Iat, DateTimeOffset.Now.ToUnixTimeSeconds().ToString(), ClaimValueTypes.Integer64) }); return claims; } private string GetEncryptedAccessToken(string accessToken) { return SimpleStringCipher.Instance.Encrypt(accessToken, AppConsts.DefaultPassPhrase); } } }
40.34188
171
0.598623
[ "MIT" ]
KhalilMohammad/DemoTodoList
aspnet-core/src/TodoList.Web.Core/Controllers/TokenAuthController.cs
9,442
C#
using System; using System.Collections.Generic; using System.Text; using System.Linq; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using HuaweiCloud.SDK.Core; namespace HuaweiCloud.SDK.Dns.V2.Model { /// <summary> /// Request Object /// </summary> public class DeleteTagRequest { /// <summary> /// 资源的类型:DNS-public_zone,DNS-private_zone,DNS-public_recordset,DNS-private_recordset,DNS-ptr_record。 /// </summary> [SDKProperty("resource_type", IsPath = true)] [JsonProperty("resource_type", NullValueHandling = NullValueHandling.Ignore)] public string ResourceType { get; set; } /// <summary> /// 资源id。 /// </summary> [SDKProperty("resource_id", IsPath = true)] [JsonProperty("resource_id", NullValueHandling = NullValueHandling.Ignore)] public string ResourceId { get; set; } /// <summary> /// 标签key。 标签key不能为空或者空字符串。 /// </summary> [SDKProperty("key", IsPath = true)] [JsonProperty("key", NullValueHandling = NullValueHandling.Ignore)] public string Key { get; set; } /// <summary> /// Get the string /// </summary> public override string ToString() { var sb = new StringBuilder(); sb.Append("class DeleteTagRequest {\n"); sb.Append(" resourceType: ").Append(ResourceType).Append("\n"); sb.Append(" resourceId: ").Append(ResourceId).Append("\n"); sb.Append(" key: ").Append(Key).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns true if objects are equal /// </summary> public override bool Equals(object input) { return this.Equals(input as DeleteTagRequest); } /// <summary> /// Returns true if objects are equal /// </summary> public bool Equals(DeleteTagRequest input) { if (input == null) return false; return ( this.ResourceType == input.ResourceType || (this.ResourceType != null && this.ResourceType.Equals(input.ResourceType)) ) && ( this.ResourceId == input.ResourceId || (this.ResourceId != null && this.ResourceId.Equals(input.ResourceId)) ) && ( this.Key == input.Key || (this.Key != null && this.Key.Equals(input.Key)) ); } /// <summary> /// Get hash code /// </summary> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.ResourceType != null) hashCode = hashCode * 59 + this.ResourceType.GetHashCode(); if (this.ResourceId != null) hashCode = hashCode * 59 + this.ResourceId.GetHashCode(); if (this.Key != null) hashCode = hashCode * 59 + this.Key.GetHashCode(); return hashCode; } } } }
31.850467
111
0.510563
[ "Apache-2.0" ]
cnblogs/huaweicloud-sdk-net-v3
Services/Dns/V2/Model/DeleteTagRequest.cs
3,468
C#
namespace DynamicLinqWithExpressionTree.Database { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.Spatial; [Table("Person.BusinessEntity")] public partial class BusinessEntity { public BusinessEntity() { BusinessEntityAddresses = new HashSet<BusinessEntityAddress>(); BusinessEntityContacts = new HashSet<BusinessEntityContact>(); } public int BusinessEntityID { get; set; } public Guid rowguid { get; set; } public DateTime ModifiedDate { get; set; } public virtual ICollection<BusinessEntityAddress> BusinessEntityAddresses { get; set; } public virtual ICollection<BusinessEntityContact> BusinessEntityContacts { get; set; } public virtual Person Person { get; set; } public virtual Store Store { get; set; } public virtual Vendor Vendor { get; set; } } }
29.657143
95
0.682081
[ "Apache-2.0" ]
anbinhtrong/DynamicLinQWithExpressionTree
DynamicLinqWithExpressionTree/Database/BusinessEntity.cs
1,038
C#
using System; using FluentAssertions.Extensions; using Xunit; using Xunit.Sdk; namespace FluentAssertions.Specs.Primitives { public class SimpleTimeSpanAssertionSpecs { [Fact] public void When_asserting_positive_value_to_be_positive_it_should_succeed() { // Arrange TimeSpan timeSpan = 1.Seconds(); // Act / Assert timeSpan.Should().BePositive(); } [Fact] public void When_asserting_negative_value_to_be_positive_it_should_fail() { // Arrange TimeSpan negatedTimeSpan = 1.Seconds().Negate(); // Act Action act = () => negatedTimeSpan.Should().BePositive(); // Assert act.Should().Throw<XunitException>(); } [Fact] public void When_asserting_zero_value_to_be_positive_it_should_fail() { // Arrange TimeSpan negatedTimeSpan = 0.Seconds(); // Act Action act = () => negatedTimeSpan.Should().BePositive(); // Assert act.Should().Throw<XunitException>(); } [Fact] public void When_asserting_null_value_to_be_positive_it_should_fail() { // Arrange TimeSpan? nullTimeSpan = null; // Act Action act = () => nullTimeSpan.Should().BePositive("because we want to test the failure {0}", "message"); // Assert act.Should().Throw<XunitException>().WithMessage( "Expected nullTimeSpan to be positive because we want to test the failure message, but found <null>."); } [Fact] public void When_asserting_negative_value_to_be_positive_it_should_fail_with_descriptive_message() { // Arrange TimeSpan timeSpan = 1.Seconds().Negate(); // Act Action act = () => timeSpan.Should().BePositive("because we want to test the failure {0}", "message"); // Assert act.Should().Throw<XunitException>().WithMessage( "Expected timeSpan to be positive because we want to test the failure message, but found -1s."); } [Fact] public void When_asserting_negative_value_to_be_negative_it_should_succeed() { // Arrange TimeSpan timeSpan = 1.Seconds().Negate(); // Act / Assert timeSpan.Should().BeNegative(); } [Fact] public void When_asserting_positive_value_to_be_negative_it_should_fail() { // Arrange TimeSpan actual = 1.Seconds(); // Act Action act = () => actual.Should().BeNegative(); // Assert act.Should().Throw<XunitException>(); } [Fact] public void When_asserting_zero_value_to_be_negative_it_should_fail() { // Arrange TimeSpan actual = 0.Seconds(); // Act Action act = () => actual.Should().BeNegative(); // Assert act.Should().Throw<XunitException>(); } [Fact] public void When_asserting_null_value_to_be_negative_it_should_fail() { // Arrange TimeSpan? nullTimeSpan = null; // Act Action act = () => nullTimeSpan.Should().BeNegative("because we want to test the failure {0}", "message"); // Assert act.Should().Throw<XunitException>().WithMessage( "Expected nullTimeSpan to be negative because we want to test the failure message, but found <null>."); } [Fact] public void When_asserting_positive_value_to_be_negative_it_should_fail_with_descriptive_message() { // Arrange TimeSpan timeSpan = 1.Seconds(); // Act Action act = () => timeSpan.Should().BeNegative("because we want to test the failure {0}", "message"); // Assert act.Should().Throw<XunitException>().WithMessage( "Expected timeSpan to be negative because we want to test the failure message, but found 1s."); } [Fact] public void When_asserting_value_to_be_equal_to_same_value_it_should_succeed() { // Arrange TimeSpan actual = 1.Seconds(); var expected = TimeSpan.FromSeconds(1); // Act / Assert actual.Should().Be(expected); } [Fact] public void When_asserting_value_to_be_equal_to_different_value_it_should_fail() { // Arrange TimeSpan actual = 1.Seconds(); TimeSpan expected = 2.Seconds(); // Act Action act = () => actual.Should().Be(expected); // Assert act.Should().Throw<XunitException>(); } [Fact] public void When_asserting_null_value_to_be_equal_to_different_value_it_should_fail() { // Arrange TimeSpan? nullTimeSpan = null; TimeSpan expected = 1.Seconds(); // Act Action act = () => nullTimeSpan.Should().Be(expected, "because we want to test the failure {0}", "message"); // Assert act.Should().Throw<XunitException>() .WithMessage("Expected 1s because we want to test the failure message, but found <null>."); } [Fact] public void When_asserting_value_to_be_equal_to_different_value_it_should_fail_with_descriptive_message() { // Arrange TimeSpan timeSpan = 1.Seconds(); // Act Action act = () => timeSpan.Should().Be(2.Seconds(), "because we want to test the failure {0}", "message"); // Assert act.Should().Throw<XunitException>() .WithMessage("Expected 2s because we want to test the failure message, but found 1s."); } [Fact] public void When_asserting_value_to_be_not_equal_to_different_value_it_should_succeed() { // Arrange TimeSpan actual = 1.Seconds(); TimeSpan unexpected = 2.Seconds(); // Act / Assert actual.Should().NotBe(unexpected); } [Fact] public void When_asserting_null_value_to_be_not_equal_to_different_value_it_should_succeed() { // Arrange TimeSpan? nullTimeSpan = null; TimeSpan expected = 1.Seconds(); // Act / Assert nullTimeSpan.Should().NotBe(expected); } [Fact] public void When_asserting_value_to_be_not_equal_to_the_same_value_it_should_fail() { // Arrange var oneSecond = 1.Seconds(); // Act Action act = () => oneSecond.Should().NotBe(oneSecond); // Assert act.Should().Throw<XunitException>(); } [Fact] public void When_asserting_value_to_be_not_equal_to_the_same_value_it_should_fail_with_descriptive_message() { // Arrange var oneSecond = 1.Seconds(); // Act Action act = () => oneSecond.Should().NotBe(oneSecond, "because we want to test the failure {0}", "message"); // Assert act.Should().Throw<XunitException>() .WithMessage("Did not expect 1s because we want to test the failure message."); } [Fact] public void When_asserting_value_to_be_greater_than_smaller_value_it_should_succeed() { // Arrange TimeSpan actual = 2.Seconds(); TimeSpan smaller = 1.Seconds(); // Act / Assert actual.Should().BeGreaterThan(smaller); } [Fact] public void When_asserting_value_to_be_greater_than_greater_value_it_should_fail() { // Arrange TimeSpan actual = 1.Seconds(); TimeSpan expected = 2.Seconds(); // Act Action act = () => actual.Should().BeGreaterThan(expected); // Assert act.Should().Throw<XunitException>(); } [Fact] public void When_asserting_null_value_to_be_greater_than_other_value_it_should_fail() { // Arrange TimeSpan? nullTimeSpan = null; TimeSpan expected = 1.Seconds(); // Act Action act = () => nullTimeSpan.Should().BeGreaterThan(expected, "because we want to test the failure {0}", "message"); // Assert act.Should().Throw<XunitException>().WithMessage( "Expected nullTimeSpan to be greater than 1s because we want to test the failure message, but found <null>."); } [Fact] public void When_asserting_value_to_be_greater_than_same_value_it_should_fail() { // Arrange var twoSeconds = 2.Seconds(); // Act Action act = () => twoSeconds.Should().BeGreaterThan(twoSeconds); // Assert act.Should().Throw<XunitException>(); } [Fact] public void When_asserting_value_to_be_greater_than_greater_value_it_should_fail_with_descriptive_message() { // Arrange TimeSpan actual = 1.Seconds(); // Act Action act = () => actual.Should().BeGreaterThan(2.Seconds(), "because we want to test the failure {0}", "message"); // Assert act.Should().Throw<XunitException>().WithMessage( "Expected actual to be greater than 2s because we want to test the failure message, but found 1s."); } [Fact] public void When_asserting_value_to_be_greater_than_or_equal_to_smaller_value_it_should_succeed() { // Arrange TimeSpan actual = 2.Seconds(); TimeSpan smaller = 1.Seconds(); // Act / Assert actual.Should().BeGreaterThanOrEqualTo(smaller); } [Fact] public void When_asserting_null_value_to_be_greater_than_or_equal_to_other_value_it_should_fail() { // Arrange TimeSpan? nullTimeSpan = null; TimeSpan expected = 1.Seconds(); // Act Action act = () => nullTimeSpan.Should().BeGreaterThanOrEqualTo(expected, "because we want to test the failure {0}", "message"); // Assert act.Should().Throw<XunitException>().WithMessage( "Expected nullTimeSpan to be greater than or equal to 1s because we want to test the failure message, but found <null>."); } [Fact] public void When_asserting_value_to_be_greater_than_or_equal_to_same_value_it_should_succeed() { // Arrange var twoSeconds = 2.Seconds(); // Act / Assert twoSeconds.Should().BeGreaterThanOrEqualTo(twoSeconds); } [Fact] public void When_asserting_value_to_be_greater_than_or_equal_to_greater_value_it_should_fail() { // Arrange TimeSpan actual = 1.Seconds(); TimeSpan expected = 2.Seconds(); // Act Action act = () => actual.Should().BeGreaterThanOrEqualTo(expected); // Assert act.Should().Throw<XunitException>(); } [Fact] public void When_asserting_value_to_be_greater_than_or_equal_to_greater_value_it_should_fail_with_descriptive_message() { // Arrange TimeSpan actual = 1.Seconds(); // Act Action act = () => actual.Should().BeGreaterThanOrEqualTo(2.Seconds(), "because we want to test the failure {0}", "message"); // Assert act.Should().Throw<XunitException>().WithMessage( "Expected actual to be greater than or equal to 2s because we want to test the failure message, but found 1s."); } [Fact] public void When_asserting_value_to_be_less_than_greater_value_it_should_succeed() { // Arrange TimeSpan actual = 1.Seconds(); TimeSpan greater = 2.Seconds(); // Act / Assert actual.Should().BeLessThan(greater); } [Fact] public void When_asserting_value_to_be_less_than_smaller_value_it_should_fail() { // Arrange TimeSpan actual = 2.Seconds(); TimeSpan expected = 1.Seconds(); // Act Action act = () => actual.Should().BeLessThan(expected); // Assert act.Should().Throw<XunitException>(); } [Fact] public void When_asserting_null_value_to_be_less_than_other_value_it_should_fail() { // Arrange TimeSpan? nullTimeSpan = null; TimeSpan expected = 1.Seconds(); // Act Action act = () => nullTimeSpan.Should().BeLessThan(expected, "because we want to test the failure {0}", "message"); // Assert act.Should().Throw<XunitException>().WithMessage( "Expected nullTimeSpan to be less than 1s because we want to test the failure message, but found <null>."); } [Fact] public void When_asserting_value_to_be_less_than_same_value_it_should_fail() { // Arrange var twoSeconds = 2.Seconds(); // Act Action act = () => twoSeconds.Should().BeLessThan(twoSeconds); // Assert act.Should().Throw<XunitException>(); } [Fact] public void When_asserting_value_to_be_less_than_smaller_value_it_should_fail_with_descriptive_message() { // Arrange TimeSpan actual = 2.Seconds(); // Act Action act = () => actual.Should().BeLessThan(1.Seconds(), "because we want to test the failure {0}", "message"); // Assert act.Should().Throw<XunitException>().WithMessage( "Expected actual to be less than 1s because we want to test the failure message, but found 2s."); } [Fact] public void When_asserting_value_to_be_less_than_or_equal_to_greater_value_it_should_succeed() { // Arrange TimeSpan actual = 1.Seconds(); TimeSpan greater = 2.Seconds(); // Act / Assert actual.Should().BeLessThanOrEqualTo(greater); } [Fact] public void When_asserting_null_value_to_be_less_than_or_equal_to_other_value_it_should_fail() { // Arrange TimeSpan? nullTimeSpan = null; TimeSpan expected = 1.Seconds(); // Act Action act = () => nullTimeSpan.Should().BeLessThanOrEqualTo(expected, "because we want to test the failure {0}", "message"); // Assert act.Should().Throw<XunitException>().WithMessage( "Expected nullTimeSpan to be less than or equal to 1s because we want to test the failure message, but found <null>."); } [Fact] public void When_asserting_value_to_be_less_than_or_equal_to_same_value_it_should_succeed() { // Arrange var twoSeconds = 2.Seconds(); // Act / Assert twoSeconds.Should().BeLessThanOrEqualTo(twoSeconds); } [Fact] public void When_asserting_value_to_be_less_than_or_equal_to_smaller_value_it_should_fail() { // Arrange TimeSpan actual = 2.Seconds(); TimeSpan expected = 1.Seconds(); // Act Action act = () => actual.Should().BeLessThanOrEqualTo(expected); // Assert act.Should().Throw<XunitException>(); } [Fact] public void When_asserting_value_to_be_less_than_or_equal_to_smaller_value_it_should_fail_with_descriptive_message() { // Arrange TimeSpan actual = 2.Seconds(); // Act Action act = () => actual.Should().BeLessThanOrEqualTo(1.Seconds(), "because we want to test the failure {0}", "message"); // Assert act.Should().Throw<XunitException>().WithMessage( "Expected actual to be less than or equal to 1s because we want to test the failure message, but found 2s."); } #region Be Close To [Fact] public void When_asserting_that_time_is_close_to_a_negative_precision_it_should_throw() { // Arrange var time = new TimeSpan(1, 12, 15, 30, 980); var nearbyTime = new TimeSpan(1, 12, 15, 31, 000); // Act Action act = () => time.Should().BeCloseTo(nearbyTime, -1.Ticks()); // Assert act.Should().Throw<ArgumentOutOfRangeException>() .WithMessage("* value of precision must be non-negative*"); } [Fact] public void When_time_is_less_then_but_close_to_another_value_it_should_succeed() { // Arrange var time = new TimeSpan(1, 12, 15, 30, 980); var nearbyTime = new TimeSpan(1, 12, 15, 31, 000); // Act Action act = () => time.Should().BeCloseTo(nearbyTime, 20.Milliseconds()); // Assert act.Should().NotThrow(); } [Fact] public void When_time_is_greater_then_but_close_to_another_value_it_should_succeed() { // Arrange var time = new TimeSpan(1, 12, 15, 31, 020); var nearbyTime = new TimeSpan(1, 12, 15, 31, 000); // Act Action act = () => time.Should().BeCloseTo(nearbyTime, 20.Milliseconds()); // Assert act.Should().NotThrow(); } [Fact] public void When_time_is_less_then_and_not_close_to_another_value_it_should_throw_with_descriptive_message() { // Arrange var time = new TimeSpan(1, 12, 15, 30, 979); var nearbyTime = new TimeSpan(1, 12, 15, 31, 000); // Act Action act = () => time.Should().BeCloseTo(nearbyTime, 20.Milliseconds(), "we want to test the error message"); // Assert act.Should().Throw<XunitException>() .WithMessage( "Expected time to be within 20ms from 1d, 12h, 15m and 31s because we want to test the error message, but found 1d, 12h, 15m, 30s and 979ms."); } [Fact] public void When_time_is_greater_then_and_not_close_to_another_value_it_should_throw_with_descriptive_message() { // Arrange var time = new TimeSpan(1, 12, 15, 31, 021); var nearbyTime = new TimeSpan(1, 12, 15, 31, 000); // Act Action act = () => time.Should().BeCloseTo(nearbyTime, 20.Milliseconds(), "we want to test the error message"); // Assert act.Should().Throw<XunitException>() .WithMessage( "Expected time to be within 20ms from 1d, 12h, 15m and 31s because we want to test the error message, but found 1d, 12h, 15m, 31s and 21ms."); } [Fact] public void When_time_is_within_specified_number_of_milliseconds_from_another_value_it_should_succeed() { // Arrange var time = new TimeSpan(1, 12, 15, 31, 035); var nearbyTime = new TimeSpan(1, 12, 15, 31, 000); // Act Action act = () => time.Should().BeCloseTo(nearbyTime, 35.Milliseconds()); // Assert act.Should().NotThrow(); } [Fact] public void When_a_null_time_is_asserted_to_be_close_to_another_it_should_throw() { // Arrange TimeSpan? time = null; var nearbyTime = new TimeSpan(1, 12, 15, 31, 000); // Act Action act = () => time.Should().BeCloseTo(nearbyTime, 35.Milliseconds()); // Assert act.Should().Throw<XunitException>() .WithMessage("Expected*, but found <null>."); } [Fact] public void When_time_away_from_another_value_it_should_throw_with_descriptive_message() { // Arrange var time = new TimeSpan(1, 12, 15, 30, 979); var nearbyTime = new TimeSpan(1, 12, 15, 31, 000); // Act Action act = () => time.Should().BeCloseTo(nearbyTime, TimeSpan.FromMilliseconds(20), "we want to test the error message"); // Assert act.Should().Throw<XunitException>() .WithMessage( "Expected time to be within 20ms from 1d, 12h, 15m and 31s because we want to test the error message, but found 1d, 12h, 15m, 30s and 979ms."); } #endregion #region Not Be Close To [Fact] public void When_asserting_that_time_is_not_close_to_a_negative_precision_it_should_throw() { // Arrange var time = new TimeSpan(1, 12, 15, 30, 980); var nearbyTime = new TimeSpan(1, 12, 15, 31, 000); // Act Action act = () => time.Should().NotBeCloseTo(nearbyTime, -1.Ticks()); // Assert act.Should().Throw<ArgumentOutOfRangeException>() .WithMessage("* value of precision must be non-negative*"); } [Fact] public void When_asserting_subject_time_is_not_close_to_a_later_time_it_should_throw() { // Arrange var time = new TimeSpan(1, 12, 15, 30, 980); var nearbyTime = new TimeSpan(1, 12, 15, 31, 000); // Act Action act = () => time.Should().NotBeCloseTo(nearbyTime, 20.Milliseconds()); // Assert act.Should().Throw<XunitException>().WithMessage("Expected time to not be within 20ms from 1d, 12h, 15m and 31s, but found 1d, 12h, 15m, 30s and 980ms."); } [Fact] public void When_asserting_subject_time_is_not_close_to_an_earlier_time_it_should_throw() { // Arrange var time = new TimeSpan(1, 12, 15, 31, 020); var nearbyTime = new TimeSpan(1, 12, 15, 31, 000); // Act Action act = () => time.Should().NotBeCloseTo(nearbyTime, 20.Milliseconds()); // Assert act.Should().Throw<XunitException>().WithMessage("Expected time to not be within 20ms from 1d, 12h, 15m and 31s, but found 1d, 12h, 15m, 31s and 20ms."); } [Fact] public void When_asserting_subject_time_is_not_close_to_an_earlier_time_by_a_20ms_timespan_it_should_throw() { // Arrange var time = new TimeSpan(1, 12, 15, 31, 020); var nearbyTime = new TimeSpan(1, 12, 15, 31, 000); // Act Action act = () => time.Should().NotBeCloseTo(nearbyTime, TimeSpan.FromMilliseconds(20)); // Assert act.Should().Throw<XunitException>().WithMessage("Expected time to not be within 20ms from 1d, 12h, 15m and 31s, but found 1d, 12h, 15m, 31s and 20ms."); } [Fact] public void When_asserting_subject_time_is_not_close_to_another_value_that_is_later_by_more_than_20ms_it_should_succeed() { // Arrange var time = new TimeSpan(1, 12, 15, 30, 979); var nearbyTime = new TimeSpan(1, 12, 15, 31, 000); // Act Action act = () => time.Should().NotBeCloseTo(nearbyTime, 20.Milliseconds()); // Assert act.Should().NotThrow(); } [Fact] public void When_asserting_subject_time_is_not_close_to_another_value_that_is_earlier_by_more_than_20ms_it_should_succeed() { // Arrange var time = new TimeSpan(1, 12, 15, 31, 021); var nearbyTime = new TimeSpan(1, 12, 15, 31, 000); // Act Action act = () => time.Should().NotBeCloseTo(nearbyTime, 20.Milliseconds()); // Assert act.Should().NotThrow(); } [Fact] public void When_asserting_subject_time_is_not_close_to_an_earlier_time_by_35ms_it_should_throw() { // Arrange var time = new TimeSpan(1, 12, 15, 31, 035); var nearbyTime = new TimeSpan(1, 12, 15, 31, 000); // Act Action act = () => time.Should().NotBeCloseTo(nearbyTime, 35.Milliseconds()); // Assert act.Should().Throw<XunitException>().WithMessage("Expected time to not be within 35ms from 1d, 12h, 15m and 31s, but found 1d, 12h, 15m, 31s and 35ms."); } [Fact] public void When_asserting_subject_null_time_is_not_close_to_another_it_should_throw() { // Arrange TimeSpan? time = null; TimeSpan nearbyTime = TimeSpan.FromHours(1); // Act Action act = () => time.Should().NotBeCloseTo(nearbyTime, 35.Milliseconds()); // Assert act.Should().Throw<XunitException>() .WithMessage("Expected*, but found <null>."); } #endregion } }
34.238606
166
0.567966
[ "Apache-2.0" ]
ABergBN/fluentassertions
Tests/FluentAssertions.Specs/Primitives/SimpleTimeSpanAssertionSpecs.cs
25,544
C#
#region copyright // ****************************************************************** // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the MIT License (MIT). // THE CODE 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 CODE OR THE USE OR OTHER DEALINGS IN THE CODE. // ****************************************************************** #endregion using System; using System.Linq; using Windows.UI.Xaml; using Windows.UI.Xaml.Hosting; using Windows.UI.Xaml.Controls; using Windows.UI.Composition; namespace Inventory { partial class ElementSet<T> { public ElementSet<T> SetIsTranslationEnabled(bool value) => ForEach(e => ElementCompositionPreview.SetIsTranslationEnabled(e, value)); public ElementSet<T> SetImplicitShowAnimation(ICompositionAnimationBase animation) => ForEach(e => ElementCompositionPreview.SetImplicitShowAnimation(e, animation)); public ElementSet<T> SetImplicitHideAnimation(ICompositionAnimationBase animation) => ForEach(e => ElementCompositionPreview.SetImplicitHideAnimation(e, animation)); public ElementSet<T> Show() => ForEach(e => e.Visibility = Visibility.Visible); public ElementSet<T> Hide() => ForEach(e => e.Visibility = Visibility.Collapsed); public void Focus(FocusState value) => FirstOrDefault<Control>()?.Focus(value); } }
46.540541
173
0.692218
[ "MIT" ]
AgneLukoseviciute/react-native-windows-samples
samples/TodosFeed/InventorySample/Inventory.App/Tools/ElementSet/ElementSet.Methods.cs
1,724
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace InventarioAPI.Entities { public class Factura { public int NumeroFactura { get; set; } [Required] public string Nit { get; set; } public DateTime Fecha { get; set; } public decimal Total { get; set; } public List<DetalleFactura> DetalleFacturas { get; set; } } }
25.105263
65
0.668763
[ "Apache-2.0" ]
johnsvill/almacen-api
Entities/Factura.cs
479
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Text; namespace Lib { public class Flatten { public Flatten(Store srcStore) { this.srcStore = srcStore; populateSrcTags(); } // newline seperated bufffer of tags to keep public void setKeep(void* ptr, size_t size) { var a = (char)ptr; var b = a + size; while (true) { while (a < b && (a == '\n' || a == '\r')) a++; var c = a; while (a < b && (a != '\n' && a != '\r')) a++; if (c < a) { var d = a - 1; while (c < d && (d[-1] != '\t')) --d; var str = srcStore.strings.intern(d, a); ulong val; if (srcTags.get(val, (ulong)str)) { tags.insert((ulong)str, (ulong)currentIndex); activeTags++; } currentIndex++; } else { break; } } } // insert a single tag into keep set public void keepTag(char tag) { var str = srcStore.strings.intern(tag); ulong val = default; if (srcTags.get(val, (ulong)str)) { tags.insert((ulong)str, (ulong)currentIndex); ((Group)val).group.id = (int)currentIndex; activeTags++; } currentIndex++; } // Tags submitted as selected, may be way more than actual number of tags. But consistent between different stores. public uint selectedTagsCount() { return currentIndex; } public uint activeTagsCount() { return activeTags; } public Store run() { dstStore = new Store(); // populateSrcTags was run by the constructor, and setKeep and keepTags has changed some group.index from ~0u. // set group.index of parents of selected nodes to ~1u so we can retain them in the culling pass. for (var srcRoot = srcStore.getFirstRoot(); srcRoot != null; srcRoot = srcRoot.next) { Debug.Assert(srcRoot.kind == Group.Kind.File); for (var srcModel = srcRoot.groups.first; srcModel != null; srcModel = srcModel.next) { Debug.Assert(srcModel.kind == Group.Kind.Model); for (var srcGroup = srcModel.groups.first; srcGroup != null; srcGroup = srcGroup.next) { anyChildrenSelectedAndTagRecurse(srcGroup); } } } // Create a fresh copy for (var srcRoot = srcStore.getFirstRoot(); srcRoot != null; srcRoot = srcRoot.next) { Debug.Assert(srcRoot.kind == Group.Kind.File); var dstRoot = dstStore.cloneGroup(null, srcRoot); for (var srcModel = srcRoot.groups.first; srcModel != null; srcModel = srcModel.next) { Debug.Assert(srcModel.kind == Group.Kind.Model); var dstModel = dstStore.cloneGroup(dstRoot, srcModel); for (var srcGroup = srcModel.groups.first; srcGroup != null; srcGroup = srcGroup.next) { buildPrunedCopyRecurse(dstModel, srcGroup, 0); } } } dstStore.updateCounts(); var rv = dstStore; dstStore = null; return rv; } private Map srcTags; // All tags in source store private Map tags; private uint pass = 0; private uint currentIndex = 0; private uint activeTags = 0; private Store srcStore = null; private Store dstStore = null; private Group[] stack = null; private uint stack_p = 0; private uint ignore_n = 0; private void populateSrcTagsRecurse(Group srcGroup) { srcGroup.group.id = -1; srcTags.insert((ulong)srcGroup.group.name, (ulong)srcGroup); for (var srcChild = srcGroup.groups.first; srcChild != null; srcChild = srcChild.next) { populateSrcTagsRecurse(srcChild); } } private void populateSrcTags() { // Sets all group.index to ~0u, and records the tag-names in srcTags. Nothing is selected yet. // name of groups are already interned in srcGroup for (var srcRoot = srcStore.getFirstRoot(); srcRoot != null; srcRoot = srcRoot.next) { for (var srcModel = srcRoot.groups.first; srcModel != null; srcModel = srcModel.next) { for (var srcGroup = srcModel.groups.first; srcGroup != null; srcGroup = srcGroup.next) { populateSrcTagsRecurse(srcGroup); } } } } private bool anyChildrenSelectedAndTagRecurse(Group srcGroup, int id = -1) { ulong val = default; if (tags.get(val, (ulong)srcGroup.group.name)) { srcGroup.group.id = (int)val; } else { srcGroup.group.id = id; } bool anyChildrenSelected = false; for (var srcChild = srcGroup.groups.first; srcChild != null; srcChild = srcChild.next) { anyChildrenSelected = anyChildrenSelectedAndTagRecurse(srcChild, srcGroup.group.id) || anyChildrenSelected; } return srcGroup.group.id != -1; } private void buildPrunedCopyRecurse(Group dstParent, Group srcGroup, uint level) { Debug.Assert(srcGroup.kind == Group.Kind.Group); // Only groups can contain geometry, so we must make sure that we have at least one group even when none is selected. // Also, some subsequent stages require that we do not have geometry in the first level of groups. if (srcGroup.group.id == -1 && level < 2) { srcGroup.group.id = -2; } if (srcGroup.group.id != -1) { dstParent = dstStore.cloneGroup(dstParent, srcGroup); dstParent.group.id = srcGroup.group.id; } for (var srcGeo = srcGroup.group.geometries.first; srcGeo != null; srcGeo = srcGeo.next) { dstStore.cloneGeometry(dstParent, srcGeo); } for (var srcChild = srcGroup.groups.first; srcChild != null; srcChild = srcChild.next) { buildPrunedCopyRecurse(dstParent, srcChild, level + 1); } } } }
34.44878
129
0.501133
[ "MIT" ]
zablej/rvmparser
Source/Lib/Flatten.cs
7,064
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.Composition; using System.Globalization; using System.Linq; using System.Reactive; using System.Reactive.Linq; using System.Threading.Tasks; using System.Windows.Data; using GitHub.Exports; using GitHub.Extensions; using GitHub.Logging; using GitHub.Models; using GitHub.Primitives; using GitHub.Services; using ReactiveUI; using Serilog; namespace GitHub.ViewModels.Dialog.Clone { [Export(typeof(IRepositorySelectViewModel))] [PartCreationPolicy(CreationPolicy.NonShared)] public class RepositorySelectViewModel : ViewModelBase, IRepositorySelectViewModel { static readonly ILogger log = LogManager.ForContext<RepositorySelectViewModel>(); readonly IRepositoryCloneService service; readonly IGitHubContextService gitHubContextService; IConnection connection; Exception error; string filter; bool isEnabled; bool isLoading; IReadOnlyList<IRepositoryItemViewModel> items; ICollectionView itemsView; ObservableAsPropertyHelper<RepositoryModel> repository; IRepositoryItemViewModel selectedItem; [ImportingConstructor] public RepositorySelectViewModel(IRepositoryCloneService service, IGitHubContextService gitHubContextService) { Guard.ArgumentNotNull(service, nameof(service)); Guard.ArgumentNotNull(service, nameof(gitHubContextService)); this.service = service; this.gitHubContextService = gitHubContextService; var selectedRepository = this.WhenAnyValue(x => x.SelectedItem) .Select(CreateRepository); var filterRepository = this.WhenAnyValue(x => x.Filter) .Select(f => gitHubContextService.FindContextFromUrl(f)) .Select(CreateRepository); repository = selectedRepository .Merge(filterRepository) .ToProperty(this, x => x.Repository); this.WhenAnyValue(x => x.Filter).Subscribe(_ => ItemsView?.Refresh()); } public Exception Error { get => error; private set => this.RaiseAndSetIfChanged(ref error, value); } public string Filter { get => filter; set => this.RaiseAndSetIfChanged(ref filter, value); } public bool IsEnabled { get => isEnabled; private set => this.RaiseAndSetIfChanged(ref isEnabled, value); } public bool IsLoading { get => isLoading; private set => this.RaiseAndSetIfChanged(ref isLoading, value); } public IReadOnlyList<IRepositoryItemViewModel> Items { get => items; private set => this.RaiseAndSetIfChanged(ref items, value); } public ICollectionView ItemsView { get => itemsView; private set => this.RaiseAndSetIfChanged(ref itemsView, value); } public IRepositoryItemViewModel SelectedItem { get => selectedItem; set => this.RaiseAndSetIfChanged(ref selectedItem, value); } public RepositoryModel Repository => repository.Value; public void Initialize(IConnection connection) { Guard.ArgumentNotNull(connection, nameof(connection)); this.connection = connection; IsEnabled = true; } public async Task Activate() { await this.LoadItems(true); } static string GroupName(KeyValuePair<string, IReadOnlyList<RepositoryListItemModel>> group, int max) { var name = group.Key; if (group.Value.Count == max) { name += $" ({string.Format(CultureInfo.InvariantCulture, Resources.MostRecentlyPushed, max)})"; } return name; } async Task LoadItems(bool refresh) { if (connection == null && !IsLoading) return; Error = null; IsLoading = true; try { if (refresh) { Items = new List<IRepositoryItemViewModel>(); ItemsView = CollectionViewSource.GetDefaultView(Items); } var results = await log.TimeAsync(nameof(service.ReadViewerRepositories), () => service.ReadViewerRepositories(connection.HostAddress, refresh)); var yourRepositories = results.Repositories .Where(r => r.Owner == results.Owner) .Select(x => new RepositoryItemViewModel(x, Resources.RepositorySelectYourRepositories)); var collaboratorRepositories = results.Repositories .Where(r => r.Owner != results.Owner) .OrderBy(r => r.Owner) .Select(x => new RepositoryItemViewModel(x, Resources.RepositorySelectCollaboratorRepositories)); var repositoriesContributedTo = results.ContributedToRepositories .Select(x => new RepositoryItemViewModel(x, Resources.RepositorySelectContributedRepositories)); var orgRepositories = results.Organizations .OrderBy(x => x.Key) .SelectMany(x => x.Value.Select(y => new RepositoryItemViewModel(y, GroupName(x, 100)))); Items = yourRepositories .Concat(collaboratorRepositories) .Concat(repositoriesContributedTo) .Concat(orgRepositories) .ToList(); log.Information("Read {Total} viewer repositories", Items.Count); ItemsView = CollectionViewSource.GetDefaultView(Items); ItemsView.GroupDescriptions.Add(new PropertyGroupDescription(nameof(RepositoryItemViewModel.Group))); ItemsView.Filter = FilterItem; } catch (Exception ex) { log.Error(ex, "Error reading repository list from {Address}", connection.HostAddress); if (ex is AggregateException aggregate) { ex = aggregate.InnerExceptions[0]; } Error = ex; } finally { IsLoading = false; } } bool FilterItem(object obj) { if (obj is IRepositoryItemViewModel item && !string.IsNullOrWhiteSpace(Filter)) { if (new UriString(Filter).IsHypertextTransferProtocol) { var urlString = item.Url.ToString(); var urlStringWithGit = urlString + ".git"; var urlStringWithSlash = urlString + "/"; return urlString.Contains(Filter, StringComparison.OrdinalIgnoreCase) || urlStringWithGit.Contains(Filter, StringComparison.OrdinalIgnoreCase) || urlStringWithSlash.Contains(Filter, StringComparison.OrdinalIgnoreCase); } else { return item.Caption.Contains(Filter, StringComparison.CurrentCultureIgnoreCase); } } return true; } RepositoryModel CreateRepository(IRepositoryItemViewModel item) { return item != null ? new RepositoryModel(item.Name, UriString.ToUriString(item.Url)) : null; } RepositoryModel CreateRepository(GitHubContext context) { switch (context?.LinkType) { case LinkType.Repository: case LinkType.Blob: return new RepositoryModel(context.RepositoryName, context.Url); } return null; } } }
35.069264
117
0.581286
[ "MIT" ]
cxj16888/VisualStudio
src/GitHub.App/ViewModels/Dialog/Clone/RepositorySelectViewModel.cs
8,103
C#
using Arc4u.Diagnostics.Serilog.Sinks.RealmDb; using Realms; using Serilog.Configuration; using System; namespace Serilog { public static class RealmDBExtension { public static LoggerConfiguration RealmDB(this LoggerSinkConfiguration loggerConfiguration) { return loggerConfiguration.Sink(new RealmDBSink(DefaultConfig())); } public static Func<RealmConfiguration> DefaultConfig = () => new RealmConfiguration("loggingDB.realm") { SchemaVersion = 1, }; } }
23.73913
110
0.681319
[ "Apache-2.0" ]
GFlisch/Arc4u
src/Arc4u.Standard.Diagnostics.Serilog.Sinks.RealmDb/Realm/RealmDBExtension.cs
548
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Carnet_Adresse { internal class ListeDeContact:ListBox { public List<Contact> Carnet { get; set; } public ListeDeContact() { Carnet = new List<Contact>(); } internal void AjouterContact(Contact c1) { Carnet.Add(c1); } } }
16.551724
49
0.604167
[ "MIT" ]
CMGeorges/Carnet_Adresse
ListeDeContact.cs
482
C#
/* Copyed from Caliburn.Micro * Original source file: * https://github.com/Caliburn-Micro/Caliburn.Micro/blob/master/src/Caliburn.Micro.Core/IoC.cs **/ using System; using System.Collections.Generic; using System.Linq; namespace WpfSample { /// <summary> /// Used by the framework to pull instances from an IoC container and to inject dependencies into certain existing classes. /// </summary> public static class SimpleIoC { /// <summary> /// Gets an instance by type and key. /// </summary> public static Func<Type, string, object> GetInstance = (service, key) => { throw new InvalidOperationException("IoC is not initialized."); }; /// <summary> /// Gets all instances of a particular type. /// </summary> /// public static Func<Type, IEnumerable<object>> GetAllInstances = service => { throw new InvalidOperationException("IoC is not initialized."); }; public static Func<Type, string, IEnumerable<object>> GetAllInstances = (service, key) => { throw new InvalidOperationException("IoC is not initialized."); }; /// <summary> /// Passes an existing instance to the IoC container to enable dependencies to be injected. /// </summary> public static Action<object> BuildUp = instance => { throw new InvalidOperationException("IoC is not initialized."); }; /// <summary> /// Gets an instance from the container. /// </summary> /// <typeparam name="T">The type to resolve.</typeparam> /// <param name="key">The key to look up.</param> /// <returns>The resolved instance.</returns> public static T Get<T>(string key = null) { return (T)GetInstance(typeof(T), key); } /// <summary> /// Gets all instances of a particular type. /// </summary> /// <typeparam name="T">The type to resolve.</typeparam> /// <returns>The resolved instances.</returns> public static IEnumerable<T> GetAll<T>(string key = null) { return GetAllInstances(typeof(T), key).Cast<T>(); } } }
39.236364
166
0.618628
[ "MIT" ]
kira-96/Stylet-Sample
SimpleIoC.cs
2,160
C#
namespace _11.Geometry_Calculator___Exercises { using System; public class GeometryCalculator { public static void Main() { string typeOfFugure = Console.ReadLine(); if (typeOfFugure == "triangle") { double a = double.Parse(Console.ReadLine()); double b = double.Parse(Console.ReadLine()); Console.WriteLine(PrintAreaOfTriangle(a,b)); } else if (typeOfFugure == "square") { double a = double.Parse(Console.ReadLine()); Console.WriteLine(PrintAreaOfSquare(a)); } else if (typeOfFugure == "rectangle") { double a = double.Parse(Console.ReadLine()); double b = double.Parse(Console.ReadLine()); Console.WriteLine(PrintAreaOfRectangle(a, b)); } else if (typeOfFugure == "circle") { double a = double.Parse(Console.ReadLine()); Console.WriteLine(PrintAreaOfCircle(a)); } } public static double PrintAreaOfTriangle(double a, double b) { var result = (a * b) / 2.0; return Math.Round(result, 2); } public static double PrintAreaOfSquare(double a) { var result = a * a; return Math.Round(result, 2); } public static double PrintAreaOfRectangle(double a, double b) { var result = a * b; return Math.Round(result, 2); } public static double PrintAreaOfCircle(double a) { var result = Math.PI * a * a; return Math.Round(result, 2); } } }
28.83871
69
0.503915
[ "MIT" ]
alexandrateneva/Programming-Fundamentals-SoftUni
Method, debugging, troubleshooting code/11. Geometry Calculator - Exercises/GeometryCalculator.cs
1,790
C#
namespace _03.EnduranceRally { public class Driver { public string Name { get; set; } public double Fuel { get; set; } public int ZoneReached { get; set; } } }
16.583333
44
0.567839
[ "MIT" ]
Pazzobg/02.01.Programming-Fundamentals-Class
00.Exam-Preparation/01. Exam Preparation I/ExamPreparationI/03.EnduranceRally/Driver.cs
201
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.Media.Outputs { [OutputType] public sealed class CencDrmConfigurationResponse { /// <summary> /// PlayReady configurations /// </summary> public readonly Outputs.StreamingPolicyPlayReadyConfigurationResponse? PlayReady; /// <summary> /// Widevine configurations /// </summary> public readonly Outputs.StreamingPolicyWidevineConfigurationResponse? Widevine; [OutputConstructor] private CencDrmConfigurationResponse( Outputs.StreamingPolicyPlayReadyConfigurationResponse? playReady, Outputs.StreamingPolicyWidevineConfigurationResponse? widevine) { PlayReady = playReady; Widevine = widevine; } } }
30.222222
89
0.684743
[ "Apache-2.0" ]
pulumi-bot/pulumi-azure-native
sdk/dotnet/Media/Outputs/CencDrmConfigurationResponse.cs
1,088
C#
using NUnit.Framework; using System.IO; using System.Collections.Generic; using System.Linq; using System.Xml; using System.Xml.Serialization; using Newtonsoft.Json; using Excel = Microsoft.Office.Interop.Excel; using System; namespace WebAddressbookTests { [TestFixture] public class AddNewContact : ContactTestBase { public static IEnumerable<ContactData> RandomContactDataProvider() { List<ContactData> contacts = new List<ContactData>(); for (int i = 0; i < 5; i++) { contacts.Add(new ContactData(GenerateRandomString(30), GenerateRandomString(30)) { Firstname = GenerateRandomString(100), Lastname = GenerateRandomString(100) }); } return contacts; } // public static IEnumerable<ContactData> ContactDataFromCsvFile() // { // List<ContactData> contacts = new List<ContactData>(); // string[] lines = File.ReadAllLines(@"contacts.csv"); // foreach (string l in lines) // { // string[] parts = l.Split(','); // contacts.Add(new ContactData(parts[0], parts[1]) // { // Firstname = parts[2], // Lastname = parts[3] // // }); // } // return contacts; // } public static IEnumerable<ContactData> ContactDataFromXmlFile() { return (List<ContactData>)new XmlSerializer(typeof(List<ContactData>)).Deserialize(new StreamReader(@"contacts.xml")); } public static IEnumerable<ContactData> ContactDataFromJsonFile() { return JsonConvert.DeserializeObject<List<ContactData>>( File.ReadAllText(@"contacts.json")); } public static IEnumerable<ContactData> ContactDataFromExcelFile() { List<ContactData> contacts = new List<ContactData>(); Excel.Application app = new Excel.Application(); Excel.Workbook wb = app.Workbooks.Open(Path.Combine(Directory.GetCurrentDirectory(), @"groups.xlsx")); Excel.Worksheet sheet = wb.ActiveSheet; Excel.Range range = sheet.UsedRange; for (int i = 1; i <= range.Rows.Count; i++) { contacts.Add(new ContactData() { Firstname = range.Cells[i, 1].Value, Lastname = range.Cells[i, 2].Value, }); } wb.Close(); app.Visible = false; app.Quit(); return contacts; } [Test, TestCaseSource("ContactDataFromCsvFile")] public void ContactCreationTest(ContactData contact) { List<ContactData> oldContacts = ContactData.GetAll(); ContactData oldContactData = oldContacts[0]; applicationManager.Contacts.CreateContact(contact); Assert.AreEqual(oldContacts.Count + 1, applicationManager.Contacts.GetContactCount()); List<ContactData> newContacts = ContactData.GetAll(); oldContacts.Add(contact); oldContacts.Sort(); newContacts.Sort(); Assert.AreEqual(oldContacts.Count + 1, newContacts.Count); } [Test, TestCaseSource("ContactDataFromCsvFile")] public void BadNameContactCreationTest(ContactData contact) { List<ContactData> oldContacts = applicationManager.Contacts.GetContactList(); ContactData oldContactData = oldContacts[0]; applicationManager.Contacts.CreateContact(contact); Assert.AreEqual(oldContacts.Count + 1, applicationManager.Contacts.GetContactCount()); List<ContactData> newContacts = applicationManager.Contacts.GetContactList(); oldContacts.Add(contact); oldContacts.Sort(); newContacts.Sort(); Assert.AreEqual(oldContacts.Count + 1, newContacts.Count); } public void TestDBConnectivity() { DateTime start = DateTime.Now; List<ContactData> fromUi = applicationManager.Contacts.GetContactList(); DateTime end = DateTime.Now; Console.Out.WriteLine(end.Subtract(start)); start = DateTime.Now; List<ContactData> fromDB = ContactData.GetAll(); end = DateTime.Now; Console.Out.WriteLine(end.Subtract(start)); } } }
35.090909
130
0.573187
[ "Apache-2.0" ]
DamsYaYa/bug-free-spoon
addressbook-web-tests/addressbook-web-tests/Tests/ContactCreationTests.cs
4,634
C#