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
// The MIT License (MIT) // Copyright (c) 1994-2019 The Sage Group plc or its licensors. All rights reserved. // // 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. #region Imports using System; using System.Diagnostics; using System.Globalization; using System.Runtime.InteropServices; using System.ComponentModel.Design; using EnvDTE; using EnvDTE80; using Microsoft.VisualStudio.Shell; using Sage.CA.SBS.ERP.Sage300.UpgradeWizard; #endregion namespace Sage300UpgradeWizardMenuExtension { /// <summary> /// This is the class that implements the package exposed by this assembly. /// /// The minimum requirement for a class to be considered a valid package for Visual Studio /// is to implement the IVsPackage interface and register itself with the shell. /// This package uses the helper classes defined inside the Managed Package Framework (MPF) /// to do it: it derives from the Package class that provides the implementation of the /// IVsPackage interface and uses the registration attributes defined in the framework to /// register itself and its components with the shell. /// </summary> // This attribute tells the PkgDef creation utility (CreatePkgDef.exe) that this class is // a package. [PackageRegistration(UseManagedResourcesOnly = true)] // This attribute is used to register the information needed to show this package // in the Help/About dialog of Visual Studio. [InstalledProductRegistration("#310", "#312", "1.0", IconResourceID = 400)] // This attribute is needed to let the shell know that this package exposes some menus. [ProvideMenuResource("Menus.ctmenu", 1)] [Guid(GuidList.guidSage300UpgradeMenuExtensionPkgString)] public sealed class Sage300UpgradeMenuExtensionPackage : Package { /// <summary> /// Default constructor of the package. /// Inside this method you can place any initialization code that does not require /// any Visual Studio service because at this point the package object is created but /// not sited yet inside Visual Studio environment. The place to do all the other /// initialization is the Initialize method. /// </summary> public Sage300UpgradeMenuExtensionPackage() { Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "Entering constructor for: {0}", this.ToString())); } ///////////////////////////////////////////////////////////////////////////// // Overridden Package Implementation #region Package Members /// <summary> /// Initialization of the package; this method is called right after the package is sited, so this is the place /// where you can put all the initialization code that rely on services provided by VisualStudio. /// </summary> protected override void Initialize() { Debug.WriteLine (string.Format(CultureInfo.CurrentCulture, "Entering Initialize() of: {0}", this.ToString())); base.Initialize(); // Add our command handlers for menu (commands must exist in the .vsct file) var mcs = GetService(typeof(IMenuCommandService)) as OleMenuCommandService; if ( null != mcs ) { // Create the command for the menu item. var menuCommandId = new CommandID(GuidList.guidSage300UpgradeMenuExtensionCmdSet, (int)PkgCmdIDList.cmdidSage300UpgradeWizard); var menuItem = new MenuCommand(MenuItemCallback, menuCommandId ); mcs.AddCommand( menuItem ); } } #endregion /// <summary> /// This function is the callback used to execute a command when the a menu item is clicked. /// See the Initialize method to see how the menu item is associated to this function using /// the OleMenuCommandService service and the MenuCommand class. /// </summary> private void MenuItemCallback(object sender, EventArgs e) { var dte = (DTE2)GetService(typeof(DTE)); // New wizard var wizard = new Sage300Upgrade(); wizard.Execute(dte.Solution); } } }
49.280374
143
0.683482
[ "MIT" ]
Mon-Lay/Sage300-SDK
src/wizards/Sage300UpgradeWizard/Sage300UpgradeWizardMenuExtension/Sage300UpgradeMenuExtensionPackage.cs
5,275
C#
using O10.Core.Architecture; using O10.Transactions.Core.Enums; using System; using System.Collections.Generic; using System.Linq; namespace O10.Transactions.Core.Accessors { [RegisterDefaultImplementation(typeof(IAccessorProvider), Lifetime = LifetimeManagement.Singleton)] public class AccessorProvider : IAccessorProvider { private readonly IEnumerable<IAccessor> _accessors; public AccessorProvider(IEnumerable<IAccessor> accessors) { _accessors = accessors; } public IAccessor GetInstance(LedgerType key) { var accessor = _accessors.FirstOrDefault(a => a.LedgerType == key); if (accessor == null) { throw new ArgumentOutOfRangeException($"No Accessor found for the key {key}"); } return accessor; } } }
27.3125
103
0.652174
[ "Apache-2.0" ]
muaddibco/O10city
Common/O10.Transactions.Core/Accessors/AccessorProvider.cs
876
C#
using System; namespace KSoft.T4 { enum TextTransformationCodeBlockType { NoBrackets, Brackets, /// <summary>Mainly for a class definition statement</summary> BracketsStatement, }; struct TextTransformationCodeBlockBookmark : IDisposable { internal const string kIndent = "\t"; readonly Microsoft.VisualStudio.TextTemplating.TextTransformation mFile; readonly TextTransformationCodeBlockType mType; readonly int mIndentCount; public TextTransformationCodeBlockBookmark(Microsoft.VisualStudio.TextTemplating.TextTransformation file, TextTransformationCodeBlockType type, int indentCount = 1) { mFile = file; mType = type; mIndentCount = indentCount; } internal void Enter() { if (mType == TextTransformationCodeBlockType.Brackets || mType == TextTransformationCodeBlockType.BracketsStatement) mFile.WriteLine("{"); for (int x = 0; x < mIndentCount; x++) mFile.PushIndent(kIndent); } public void Dispose() { for (int x = 0; x < mIndentCount; x++) mFile.PopIndent(); if (mType == TextTransformationCodeBlockType.Brackets) mFile.WriteLine("}"); else if (mType == TextTransformationCodeBlockType.BracketsStatement) mFile.WriteLine("};"); } }; }
25.78
108
0.70287
[ "MIT" ]
KornnerStudios/KSoft
KSoft.T4/TextTransformationCodeBlockBookmark.cs
1,291
C#
#if THUNDERKIT_CONFIGURED using global::RoR2; namespace PassivePicasso.ThunderKit.Proxy.RoR2 { public partial class PickupDropletController : global::RoR2.PickupDropletController {} } #endif
27.714286
90
0.819588
[ "MIT" ]
Jarlyk/Rain-of-Stages
Assets/RainOfStages/RoR2/GeneratedProxies/RoR2/PickupDropletController.cs
194
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Data.Common; namespace Microsoft.Data.Sqlite.Utilities { internal static class DbConnectionExtensions { public static int ExecuteNonQuery( this DbConnection connection, string commandText, int timeout = SqliteCommand.DefaultCommandTimeout) { var command = connection.CreateCommand(); command.CommandTimeout = timeout; command.CommandText = commandText; return command.ExecuteNonQuery(); } public static T ExecuteScalar<T>( this DbConnection connection, string commandText, int timeout = SqliteCommand.DefaultCommandTimeout) => (T)connection.ExecuteScalar(commandText, timeout); private static object ExecuteScalar(this DbConnection connection, string commandText, int timeout) { var command = connection.CreateCommand(); command.CommandTimeout = timeout; command.CommandText = commandText; return command.ExecuteScalar(); } } }
33.210526
111
0.64897
[ "Apache-2.0", "MIT" ]
TheBlueSky/Microsoft.Data.Sqlite.WinRT
src/Microsoft.Data.Sqlite/Utilities/DbConnectionExtensions.cs
1,262
C#
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using Telerik.Web.UI; using bd = BankProject.DataProvider; using bc = BankProject.Controls; namespace BankProject.TellerApplication.SignatureManagement { public partial class Preview : DotNetNuke.Entities.Modules.PortalModuleBase { protected void Page_Load(object sender, EventArgs e) { if (IsPostBack) return; txtCustomerId.Text = Request.QueryString["tid"]; if (String.IsNullOrEmpty(txtCustomerId.Text)) return; // lblCustomerName.Text = ""; imgSignature.ImageUrl = ""; lnkSignature.NavigateUrl = "#"; // DataTable tDetail = bd.Customer.SignatureDetail(txtCustomerId.Text); if (tDetail == null || tDetail.Rows.Count <= 0) { lblCustomerName.Text = "This Customer does not exist."; return; } // DataRow dr = tDetail.Rows[0]; lblCustomerName.Text = dr["CustomerName"].ToString(); imgSignature.ImageUrl = "~/" + bd.Customer.SignaturePath + "/" + dr["Signatures"]; lnkSignature.NavigateUrl = imgSignature.ImageUrl; } } }
35.564103
95
0.594809
[ "Apache-2.0", "BSD-3-Clause" ]
nguyenppt/biscorebanksys
DesktopModules/TrainingCoreBanking/BankProject/TellerApplication/SignatureManagement/Preview.ascx.cs
1,389
C#
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // 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.Text; using System.Collections.Generic; using System.Diagnostics; using Microsoft.Win32; using System.Diagnostics.Contracts; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Tests { [TestClass] public class StructTests : DisableAssertUI { #region Test Management [ClassInitialize] public static void ClassInitialize(TestContext context) { } [ClassCleanup] public static void ClassCleanup() { } [TestInitialize] public void TestInitialize() { } [TestCleanup] public void TestCleanup() { } #endregion Test Management #region Tests [ContractClass(typeof(IIndexableContract<>))] public partial interface IIndexable<T> { int Count { get; } T this[int index] { get; } } [ContractClassFor(typeof(IIndexable<>))] public class IIndexableContract<T> : IIndexable<T> { #region IIndexable<T> Members public int Count { get { Contract.Ensures(Contract.Result<int>() >= 0); throw new NotImplementedException(); } } public T this[int index] { get { Contract.Requires(index >= 0); Contract.Requires(index < this.Count); throw new NotImplementedException(); } } #endregion } public struct EmptyIndexable<T> : IIndexable<T> { #region IIndexable<T> Members public int Count { get { return 0; } } public T this[int index] { get { throw new IndexOutOfRangeException(); } } #endregion } public struct EmptyIntIndexable : IIndexable<int> { #region IIndexable<T> Members public int Count { get { return 0; } } public int this[int index] { get { return -1; } } #endregion } [TestMethod] public void StructInheritingFromInterfacePositive1() { EmptyIndexable<int> empty = new EmptyIndexable<int>(); int x = empty.Count; Assert.AreEqual(0, x); } [TestMethod] public void StructInheritingFromInterfaceNegative1() { EmptyIndexable<int> empty = new EmptyIndexable<int>(); try { int x = empty[0]; throw new Exception(); } catch (TestRewriterMethods.PreconditionException p) { Assert.AreEqual("index < this.Count", p.Condition); } } [TestMethod] public void StructInheritingFromInterfacePositive2() { var empty = new EmptyIntIndexable(); int x = empty.Count; Assert.AreEqual(0, x); } [TestMethod] public void StructInheritingFromInterfaceNegative2() { var empty = new EmptyIntIndexable(); try { int x = empty[0]; throw new Exception(); } catch (TestRewriterMethods.PreconditionException p) { Assert.AreEqual("index < this.Count", p.Condition); } } #endregion } }
24.201149
463
0.639753
[ "MIT" ]
Acidburn0zzz/CodeContracts
Foxtrot/Tests/Structs.cs
4,211
C#
using System; using System.Collections; using System.Collections.Generic; using System.Windows.Forms; namespace SupremeFiction.UI.SupremeRulerModdingTool.WinForm.HotKey { //A class to keep share procedures public static class HotKeyShared { /// <summary> /// Checks if a string is a valid Hotkey name. /// </summary> /// <param name="text">The string to check</param> /// <returns>true if the name is valid.</returns> public static bool IsValidHotkeyName(string text) { //If the name starts with a number, contains space or is null, return false. if (string.IsNullOrEmpty(text)) return false; if (text.Contains(" ") || char.IsDigit((char) text.ToCharArray().GetValue(0))) return false; return true; } /// <summary> /// Parses a shortcut string like 'Control + Alt + Shift + V' and returns the key and modifiers. /// </summary> /// <param name="text">The shortcut string to parse.</param> /// <returns>The Modifier in the lower bound and the key in the upper bound.</returns> public static object[] ParseShortcut(string text) { bool HasAlt = false; bool HasControl = false; bool HasShift = false; bool HasWin = false; var Modifier = Modifiers.None; //Variable to contain modifier. Keys key = 0; //The key to register. int current = 0; string[] result; string[] separators = {" + "}; result = text.Split(separators, StringSplitOptions.RemoveEmptyEntries); //Iterate through the keys and find the modifier. foreach (string entry in result) { //Find the Control Key. if (entry.Trim() == Keys.Control.ToString()) { HasControl = true; } //Find the Alt key. if (entry.Trim() == Keys.Alt.ToString()) { HasAlt = true; } //Find the Shift key. if (entry.Trim() == Keys.Shift.ToString()) { HasShift = true; } //Find the Window key. if (entry.Trim() == Keys.LWin.ToString() && current != result.Length - 1) { HasWin = true; } current++; } if (HasControl) { Modifier |= Modifiers.Control; } if (HasAlt) { Modifier |= Modifiers.Alt; } if (HasShift) { Modifier |= Modifiers.Shift; } if (HasWin) { Modifier |= Modifiers.Win; } var keyconverter = new KeysConverter(); key = (Keys) keyconverter.ConvertFrom(result.GetValue(result.Length - 1)); return new object[] {Modifier, key}; } /// <summary> /// Parses a shortcut string like 'Control + Alt + Shift + V' and returns the key and modifiers. /// </summary> /// <param name="text">The shortcut string to parse.</param> /// <param name="separator">The delimiter for the shortcut.</param> /// <returns>The Modifier in the lower bound and the key in the upper bound.</returns> public static object[] ParseShortcut(string text, string separator) { bool HasAlt = false; bool HasControl = false; bool HasShift = false; bool HasWin = false; var Modifier = Modifiers.None; //Variable to contain modifier. Keys key = 0; //The key to register. int current = 0; string[] result; string[] separators = {separator}; result = text.Split(separators, StringSplitOptions.RemoveEmptyEntries); //Iterate through the keys and find the modifier. foreach (string entry in result) { //Find the Control Key. if (entry.Trim() == Keys.Control.ToString()) { HasControl = true; } //Find the Alt key. if (entry.Trim() == Keys.Alt.ToString()) { HasAlt = true; } //Find the Shift key. if (entry.Trim() == Keys.Shift.ToString()) { HasShift = true; } //Find the Window key. if (entry.Trim() == Keys.LWin.ToString() && current != result.Length - 1) { HasWin = true; } current++; } if (HasControl) { Modifier |= Modifiers.Control; } if (HasAlt) { Modifier |= Modifiers.Alt; } if (HasShift) { Modifier |= Modifiers.Shift; } if (HasWin) { Modifier |= Modifiers.Win; } var keyconverter = new KeysConverter(); key = (Keys) keyconverter.ConvertFrom(result.GetValue(result.Length - 1)); return new object[] {Modifier, key}; } /// <summary> /// Combines the modifier and key to a shortcut. /// Changes Control;Shift;Alt;T to Control + Shift + Alt + T /// </summary> /// <param name="mod">The modifier.</param> /// <param name="key">The key.</param> /// <returns>A string representation of the modifier and key.</returns> public static string CombineShortcut(Modifiers mod, Keys key) { string hotkey = ""; foreach (Modifiers a in new ParseModifier((int) mod)) { hotkey += a + " + "; } if (hotkey.Contains(Modifiers.None.ToString())) hotkey = ""; hotkey += key.ToString(); return hotkey; } /// <summary> /// Combines the modifier and key to a shortcut. /// Changes Control;Shift;Alt; to Control + Shift + Alt /// </summary> /// <param name="mod">The modifier.</param> /// <returns>A string representation of the modifier</returns> public static string CombineShortcut(Modifiers mod) { string hotkey = ""; foreach (Modifiers a in new ParseModifier((int) mod)) { hotkey += a + " + "; } if (hotkey.Contains(Modifiers.None.ToString())) hotkey = ""; if (hotkey.Trim().EndsWith("+")) hotkey = hotkey.Trim().Substring(0, hotkey.Length - 1); return hotkey; } /// <summary> /// Allows the conversion of an integer to its modifier representation. /// </summary> public struct ParseModifier : IEnumerable { private readonly List<Modifiers> Enumeration; public bool HasAlt; public bool HasControl; public bool HasShift; public bool HasWin; /// <summary> /// Initializes this class. /// </summary> /// <param name="Modifier">The integer representation of the modifier to parse.</param> public ParseModifier(int Modifier) { Enumeration = new List<Modifiers>(); HasAlt = false; HasWin = false; HasShift = false; HasControl = false; switch (Modifier) { case 0: Enumeration.Add(Modifiers.None); break; case 1: HasAlt = true; Enumeration.Add(Modifiers.Alt); break; case 2: HasControl = true; Enumeration.Add(Modifiers.Control); break; case 3: HasAlt = true; HasControl = true; Enumeration.Add(Modifiers.Control); Enumeration.Add(Modifiers.Alt); break; case 4: HasShift = true; Enumeration.Add(Modifiers.Shift); break; case 5: HasShift = true; HasAlt = true; Enumeration.Add(Modifiers.Shift); Enumeration.Add(Modifiers.Alt); break; case 6: HasShift = true; HasControl = true; Enumeration.Add(Modifiers.Shift); Enumeration.Add(Modifiers.Control); break; case 7: HasControl = true; HasShift = true; HasAlt = true; Enumeration.Add(Modifiers.Shift); Enumeration.Add(Modifiers.Control); Enumeration.Add(Modifiers.Alt); break; case 8: HasWin = true; Enumeration.Add(Modifiers.Win); break; case 9: HasAlt = true; HasWin = true; Enumeration.Add(Modifiers.Alt); Enumeration.Add(Modifiers.Win); break; case 10: HasControl = true; HasWin = true; Enumeration.Add(Modifiers.Control); Enumeration.Add(Modifiers.Win); break; case 11: HasControl = true; HasAlt = true; HasWin = true; Enumeration.Add(Modifiers.Control); Enumeration.Add(Modifiers.Alt); Enumeration.Add(Modifiers.Win); break; case 12: HasShift = true; HasWin = true; Enumeration.Add(Modifiers.Shift); Enumeration.Add(Modifiers.Win); break; case 13: HasShift = true; HasAlt = true; HasWin = true; Enumeration.Add(Modifiers.Shift); Enumeration.Add(Modifiers.Alt); Enumeration.Add(Modifiers.Win); break; case 14: HasShift = true; HasControl = true; HasWin = true; Enumeration.Add(Modifiers.Shift); Enumeration.Add(Modifiers.Control); Enumeration.Add(Modifiers.Win); break; case 15: HasShift = true; HasControl = true; HasAlt = true; HasWin = true; Enumeration.Add(Modifiers.Shift); Enumeration.Add(Modifiers.Control); Enumeration.Add(Modifiers.Alt); Enumeration.Add(Modifiers.Win); break; default: throw new ArgumentOutOfRangeException("The argument is parsed is more than the expected range", "Modifier"); } } /// <summary> /// Initializes this class. /// </summary> /// <param name="mod">the modifier to parse.</param> public ParseModifier(Modifiers mod) : this((int) mod) { } IEnumerator IEnumerable.GetEnumerator() { return Enumeration.GetEnumerator(); } } } }
36.288571
119
0.436737
[ "Apache-2.0" ]
Blind-Striker/supremefiction
SupremeRulerModdingTool/UI/SupremeRulerModdingTool.WinForm/HotKey/Helpers.cs
12,703
C#
using System; namespace Blueprint.Application.Interfaces.Shared { public interface IDateTimeService { DateTime NowUtc { get; } } }
16.888889
49
0.684211
[ "MIT" ]
voidNK/blueprint
Blueprint.Application/Interfaces/Shared/IDateTimeService.cs
154
C#
using System.Collections.Generic; namespace ordercloud.integrations.freightpop { public class GetRatesData { public List<ShippingRate> Rates { get; set; } public List<string> ErrorMessages { get; set; } } }
21.545455
55
0.679325
[ "MIT" ]
Harish-pa/headstart
src/Middleware/integrations/ordercloud.integrations.freightpop/Models/GetRatesData.cs
239
C#
using System.Collections.Generic; using Castle.MicroKernel.Registration; using Castle.Windsor; using Moq; using NUnit.Framework; using Ve.Metrics.StatsDClient.Abstract; using Ve.Metrics.StatsDClient.CastleWindsor; using Ve.Metrics.StatsDClient.Tests.TestClasses; namespace Ve.Metrics.StatsDClient.Tests.CastleWindsor { [TestFixture] public class CastleWindsorInterfaceGenericsShould { protected WindsorContainer Container; protected Mock<IVeStatsDClient> StatsdMock; protected ITestGeneric<Foo> FooService; protected ITestGeneric<Bar> BarService; [SetUp] protected void Setup() { StatsdMock = new Mock<IVeStatsDClient>(); Container = new WindsorContainer(); Container.Register(Component.For<IVeStatsDClient>().Instance(StatsdMock.Object)); Container.Register(Component.For<StatsDTimingInterceptor>()); Container.Register(Component.For<ITestGeneric<Foo>, ITestGeneric<Bar>>() .ImplementedBy<TestGenerics>() .Interceptors<StatsDTimingInterceptor>()); FooService = Container.Resolve<ITestGeneric<Foo>>(); BarService = Container.Resolve<ITestGeneric<Bar>>(); } [Test] public void It_should_time_the_generic_foo_method() { FooService.Do(new Foo()); StatsdMock.Verify(x => x.LogTiming("dependencies.foo.test", It.IsAny<long>(), It.IsAny<Dictionary<string, string>>()), Times.Once); } [Test] public void It_should_time_the_generic_bar_method() { BarService.Do(new Bar()); StatsdMock.Verify(x => x.LogTiming("dependencies.bar.test", It.IsAny<long>(), It.IsAny<Dictionary<string, string>>()), Times.Once); } } }
35.882353
143
0.656284
[ "MIT" ]
mihaicrisanbodea/ve-metrics-statsdclient-csharp
Ve.Metrics.StatsDClient.Tests/CastleWindsor/CastleWindsorInterfaceGenericsShould.cs
1,832
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("p02WorldSwimmingRecord")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("HP Inc.")] [assembly: AssemblyProduct("p02WorldSwimmingRecord")] [assembly: AssemblyCopyright("Copyright © HP Inc. 2018")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("c2431151-aa4b-4c62-925e-d0fee50b7cd0")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.540541
84
0.751052
[ "MIT" ]
vesy53/SoftUni
Programming Basics - C#/Exams/Programming Basics Exam - 25 June 2017/p02WorldSwimmingRecord/Properties/AssemblyInfo.cs
1,429
C#
using System.Collections.Generic; namespace UnityChess { /// Non-board, non-move-record game state public struct GameConditions { public static GameConditions NormalStartingConditions = new GameConditions(true, true, true, true, true, Square.Invalid, 0, 1); public readonly bool WhiteToMove; public readonly bool WhiteCanCastleKingside; public readonly bool WhiteCanCastleQueenside; public readonly bool BlackCanCastleKingside; public readonly bool BlackCanCastleQueenside; public readonly Square EnPassantSquare; public readonly int HalfMoveClock; public readonly int TurnNumber; public GameConditions(bool whiteToMove, bool whiteCanCastleKingside, bool whiteCanCastleQueenside, bool blackCanCastleKingside, bool blackCanCastleQueenside, Square enPassantSquare, int halfMoveClock, int turnNumber) { WhiteToMove = whiteToMove; WhiteCanCastleKingside = whiteCanCastleKingside; WhiteCanCastleQueenside = whiteCanCastleQueenside; BlackCanCastleKingside = blackCanCastleKingside; BlackCanCastleQueenside = blackCanCastleQueenside; EnPassantSquare = enPassantSquare; HalfMoveClock = halfMoveClock; TurnNumber = turnNumber; } public GameConditions CalculateEndingGameConditions(Board endingBoard, List<HalfMove> halfMovesFromStart) { if (halfMovesFromStart.Count == 0) return this; bool whiteEligibleForCastling = endingBoard.WhiteKing.Position.Equals(5, 1) && !endingBoard.WhiteKing.HasMoved; bool blackEligibleForCastling = endingBoard.BlackKing.Position.Equals(5, 8) && !endingBoard.BlackKing.HasMoved; return new GameConditions( whiteToMove: halfMovesFromStart.Count % 2 == 0 ? WhiteToMove : !WhiteToMove, whiteCanCastleKingside: whiteEligibleForCastling && endingBoard[8, 1] is Rook whiteKingsideRook && !whiteKingsideRook.HasMoved, whiteCanCastleQueenside: whiteEligibleForCastling && endingBoard[1, 1] is Rook whiteQueensideRook && !whiteQueensideRook.HasMoved, blackCanCastleKingside: blackEligibleForCastling && endingBoard[8, 8] is Rook blackKingsideRook && !blackKingsideRook.HasMoved, blackCanCastleQueenside: blackEligibleForCastling && endingBoard[1, 8] is Rook blackQueensideRook && !blackQueensideRook.HasMoved, enPassantSquare: GetEndingEnPassantSquare(halfMovesFromStart[halfMovesFromStart.Count - 1]), halfMoveClock: GetEndingHalfMoveClock(halfMovesFromStart), turnNumber: TurnNumber + (WhiteToMove ? halfMovesFromStart.Count / 2 : (halfMovesFromStart.Count + 1) / 2) ); } private int GetEndingHalfMoveClock(List<HalfMove> movesFromStart) { int endingHalfMoveClock = HalfMoveClock; foreach (HalfMove halfMove in movesFromStart) { if (!(halfMove.Piece is Pawn) && !halfMove.CapturedPiece) endingHalfMoveClock++; else endingHalfMoveClock = 0; } return endingHalfMoveClock; } // NOTE ending en passant square can be determined from simply the last half move made. private static Square GetEndingEnPassantSquare(HalfMove lastHalfMove) { Side lastTurnPieceColor = lastHalfMove.Piece.Color; int pawnStartingRank = lastTurnPieceColor == Side.White ? 2 : 7; int pawnEndingRank = lastTurnPieceColor == Side.White ? 4 : 5; Square enPassantSquare = Square.Invalid; if (lastHalfMove.Piece is Pawn && lastHalfMove.Move.Start.Rank == pawnStartingRank && lastHalfMove.Move.End.Rank == pawnEndingRank) { int rankOffset = lastTurnPieceColor == Side.White ? -1 : 1; enPassantSquare = new Square(lastHalfMove.Move.End, 0, rankOffset); } return enPassantSquare; } } }
49.859155
220
0.781921
[ "MIT" ]
ErkrodC/UnityChessLib
GameStringInterchange/GameConditions.cs
3,542
C#
using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using VideoApi.Contract.Requests; namespace VideoWeb.EventHub.Services { public interface IHearingLayoutService { Task UpdateLayout(Guid conferenceId, Guid changedById, HearingLayout newLayout); Task<HearingLayout?> GetCurrentLayout(Guid conferenceId); } }
24
88
0.770833
[ "MIT" ]
hmcts/vh-video-web
VideoWeb/VideoWeb.EventHub/Services/IHearingLayoutService.cs
384
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using BuildStudio.Data; using BuildStudio.Data.Model; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.EntityFrameworkCore; namespace BuildStudio.Controllers { public class ExpectedResultsController : Controller { private readonly ApplicationDbContext _context; public ExpectedResultsController(ApplicationDbContext context) { _context = context; } // GET: conditions/Details/5 public async Task<IActionResult> Details(int? id) { if (id == null) { return NotFound(); } var expectedResult = await _context .ExpectedResults .Include(er => er.Condition) .Include(er => er.Results) .SingleOrDefaultAsync(er => er.Id == id); if (expectedResult == null) { return NotFound(); } return View(expectedResult); } // GET: conditions/Create/1 public IActionResult Create(int? id) { var expectedResult = new ExpectedResult { ConditionId = id.GetValueOrDefault() }; ViewData["ConditionId"] = new SelectList(_context.AcceptanceCriterias, "Id", "Name", expectedResult.ConditionId); return View(expectedResult); } // POST: conditions/Create // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Create([Bind(ExpectedResult.BindableProperties)] ExpectedResult expectedResult) { if (ModelState.IsValid) { _context.Add(expectedResult); await _context.SaveChangesAsync(); return RedirectToAction("Details", "AcceptanceCriterias", new { Id = expectedResult.ConditionId }); } ViewData["ConditionId"] = new SelectList(_context.AcceptanceCriterias, "Id", "Name", expectedResult.ConditionId); return View(expectedResult); } // GET: conditions/Edit/5 public async Task<IActionResult> Edit(int? id) { if (id == null) { return NotFound(); } var expectedResult = await _context .ExpectedResults .SingleOrDefaultAsync(er => er.Id == id); if (expectedResult == null) { return NotFound(); } ViewData["ConditionId"] = new SelectList(_context.AcceptanceCriterias, "Id", "Name", expectedResult.ConditionId); return View(expectedResult); } // POST: conditions/Edit/5 // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Edit(int id, [Bind(ExpectedResult.BindablePropertiesForEdition)] ExpectedResult expectedResult) { if (id != expectedResult.Id) { return NotFound(); } if (ModelState.IsValid) { try { _context.Update(expectedResult); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!ExpectedResultExists(expectedResult.Id)) { return NotFound(); } else { throw; } } return RedirectToAction("Details", "AcceptanceCriterias", new { Id = expectedResult.ConditionId }); } ViewData["ConditionId"] = new SelectList(_context.AcceptanceCriterias, "Id", "Name", expectedResult.ConditionId); return View(expectedResult); } // GET: conditions/Delete/5 public async Task<IActionResult> Delete(int? id) { if (id == null) { return NotFound(); } var expectedResult = await _context .ExpectedResults .Include(er => er.Condition) .SingleOrDefaultAsync(er => er.Id == id); if (expectedResult == null) { return NotFound(); } return View(expectedResult); } // POST: conditions/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public async Task<IActionResult> DeleteConfirmed(int id) { var expectedResult = await _context .ExpectedResults .SingleOrDefaultAsync(er => er.Id == id); _context.ExpectedResults.Remove(expectedResult); await _context.SaveChangesAsync(); return RedirectToAction("Details", "AcceptanceCriterias", new { Id = expectedResult.ConditionId }); } private bool ExpectedResultExists(int id) { return _context.Results.Any(e => e.Id == id); } } }
32.527778
136
0.524338
[ "MIT" ]
eduardomessias/build-studio
BuildStudio/Controllers/ExpectedResultsController.cs
5,857
C#
using System.Text.Json.Serialization; using Horse.Messaging.Client.Direct.Annotations; using Newtonsoft.Json; namespace Sample.Consumer { [DirectContentType(1000)] [DirectTarget(FindTargetBy.Type, "direct-handler")] public class RequestModel { [JsonProperty("id")] [JsonPropertyName("id")] public int Id { get; set; } } public class ResponseModel { [JsonProperty("no")] [JsonPropertyName("no")] public int No { get; set; } [JsonProperty("foo")] [JsonPropertyName("foo")] public string Foo { get; set; } } }
20.576923
52
0.706542
[ "Apache-2.0" ]
horse-framework/horse-messaging
src/Samples/Sample.Consumer/RequestModel.cs
535
C#
using System; using System.Collections.Generic; using System.Text; public class LeutenantGeneral : Private { private List<Private> privates; public LeutenantGeneral(string firstName, string lastName, string id, double salary, List<Private> privates) : base(firstName, lastName, id, salary) { this.Privates = privates; } public List<Private> Privates { get { return privates; } private set { privates = value; } } public override string ToString() { StringBuilder builder = new StringBuilder(base.ToString() + Environment.NewLine); builder.Append("Privates:" + Environment.NewLine); foreach (var privateSoldier in this.Privates) { builder.AppendLine($"Name: {privateSoldier.FirstName} {privateSoldier.LastName} Id: {privateSoldier.Id} Salary: {privateSoldier.Salary:f2}"); } string result = builder.ToString().TrimEnd(); return result; } }
28.171429
153
0.657201
[ "MIT" ]
valkin88/CSharp-Fundamentals
CSharp OOP Basics/Interfaces and Abstraction - Exercises/MilitaryElite/MilitaryElite/LeutenantGeneral.cs
988
C#
using UnityEngine; using UnityEngine.UI; namespace Michsky.UI.ModernUIPack { [ExecuteInEditMode] public class UIManagerContextMenu : MonoBehaviour { [Header("SETTINGS")] public UIManager UIManagerAsset; [Header("RESOURCES")] public Image backgroundImage; bool dynamicUpdateEnabled; void OnEnable() { if (UIManagerAsset == null) { try { UIManagerAsset = Resources.Load<UIManager>("MUIP Manager"); } catch { Debug.Log("No UI Manager found. Assign it manually, otherwise you'll get errors about it.", this); } } } void Awake() { if (dynamicUpdateEnabled == false) { this.enabled = true; UpdateContextMenu(); } } void LateUpdate() { if (Application.isEditor == true && UIManagerAsset != null) { if (UIManagerAsset.enableDynamicUpdate == true) { dynamicUpdateEnabled = true; UpdateContextMenu(); } else dynamicUpdateEnabled = false; } } void UpdateContextMenu() { backgroundImage.color = UIManagerAsset.contextBackgroundColor; } } }
24.209677
118
0.469687
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
ArcticCloudStudios/Project-X
Assets/Modern UI Pack/Scripts/UI Manager/UIManagerContextMenu.cs
1,503
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("Qiniu (Cloud) C# SDK Test - UnitTest")] [assembly: AssemblyDescription("Qiniu (Cloud) C# SDK Test - UnitTest")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("QINIU")] [assembly: AssemblyProduct("Qiniu.UnitTest")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("536c8b17-af56-42db-b48e-241fc09ce6d2")] // 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("7.2.15")] [assembly: AssemblyFileVersion("7.2.15")]
39.513514
84
0.743502
[ "MIT" ]
pengweiqhca/Qiniu
src/Qiniu.UnitTest/Properties/AssemblyInfo.cs
1,465
C#
using NUnit.Framework; using FluentAssertions; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Nest.Tests.MockData.Domain; namespace Nest.Tests.Integration.Reproduce { [TestFixture] public class Reproduce1474Tests : IntegrationTests { [Test] public void GeoBoundsAggregationNotReadToCompletion() { var response = this.Client.Search<ElasticsearchProject>(s => s .Aggregations(aggs => aggs .Terms("names", ct => ct .Field(p => p.Name) .Size(0) ) .Terms("countries", at => at .Field(p => p.Country) .Size(0) ) .GeoHash("locations", l => l .Field(f => f.Origin) .GeoHashPrecision(GeoHashPrecision.Precision6) ) .GeoBounds("bounds", b => b .Field(f => f.Origin) ) ) ); response.IsValid.Should().BeTrue(); var names = response.Aggs.Terms("names"); names.Should().NotBeNull(); var countries = response.Aggs.Terms("countries"); countries.Should().NotBeNull(); var locations = response.Aggs.GeoHash("locations"); locations.Should().NotBeNull(); var bounds = response.Aggs.GeoBounds("bounds"); bounds.Should().NotBeNull(); } } }
25.102041
65
0.657724
[ "Apache-2.0" ]
Entroper/elasticsearch-net
src/Tests/Nest.Tests.Integration/Reproduce/Reproduce1474Tests.cs
1,232
C#
//-------------------------------------------------------------------------------------------------- // Copyright © Nezaboodka™ Software LLC. All rights reserved. // Licensed under the Apache License, Version 2.0. //-------------------------------------------------------------------------------------------------- using System; using System.IO; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; namespace Nezaboodka.Nevod { internal abstract class RootCandidate : RejectionTargetCandidate { private List<WaitingToken> fWaitingTokens; private List<AnySpanCandidate> fCompletedPendingAnySpanCandidates; public List<ExtractionCandidate> Extractions { get; private set; } public int PatternId; public bool IsRegistered; public bool IsWaiting { get; private set; } public bool IsCompletedOrWaiting => (IsCompleted || IsWaiting); public bool HasPendingAnySpanCandidates => (fCompletedPendingAnySpanCandidates != null); public bool IsFinalMatch => (IsCompleted && !IsRejected && !MayBeRejected && !HasPendingAnySpanCandidates); public RootCandidate(CompoundExpression expression) : base(expression) { } public override CompoundCandidate Clone() { var result = (RootCandidate)base.Clone(); result.IsRegistered = false; if (Extractions != null) Extractions = new List<ExtractionCandidate>(Extractions); if (fCompletedPendingAnySpanCandidates != null) { fCompletedPendingAnySpanCandidates = new List<AnySpanCandidate>(fCompletedPendingAnySpanCandidates); for (int i = 0, n = fCompletedPendingAnySpanCandidates.Count; i < n; i++) fCompletedPendingAnySpanCandidates[i].AddRelatedRootCandidate(result); } return result; } public void StartWaiting() { fWaitingTokens = new List<WaitingToken>(); IsWaiting = true; } public void AddWaitingToken(WaitingToken waitingToken) { fWaitingTokens.Add(waitingToken); } public void FinishWaiting() { IsWaiting = false; fWaitingTokens = null; } public override void RemoveException(ExceptionCandidate candidate) { base.RemoveException(candidate); if (IsFinalMatch) OnFinalMatch(); } public override void RemovePendingHavingCandidate(HavingCandidate candidate) { base.RemovePendingHavingCandidate(candidate); if (IsFinalMatch) OnFinalMatch(); } public override void RemovePendingInsideCandidate(InsideCandidate candidate) { base.RemovePendingInsideCandidate(candidate); if (IsFinalMatch) OnFinalMatch(); } public override void RemovePendingOutsideCandidate(OutsideCandidate candidate) { base.RemovePendingOutsideCandidate(candidate); if (IsFinalMatch) OnFinalMatch(); } public void AddCompletedPendingAnySpanCandidate(AnySpanCandidate candidate) { if (fCompletedPendingAnySpanCandidates == null) fCompletedPendingAnySpanCandidates = new List<AnySpanCandidate>(); fCompletedPendingAnySpanCandidates.Add(candidate); candidate.AddRelatedRootCandidate(this); } public void RemoveCompletedPendingAnySpanCandidate(AnySpanCandidate candidate) { fCompletedPendingAnySpanCandidates.Remove(candidate); if (fCompletedPendingAnySpanCandidates.Count == 0) fCompletedPendingAnySpanCandidates = null; if (IsFinalMatch) OnFinalMatch(); } public void AddExtraction(ExtractionCandidate candidate) { if (Extractions == null) Extractions = new List<ExtractionCandidate>(); Extractions.Add(candidate); } public virtual ExtractionCandidate GetFieldLatestValue(int fieldNumber) { bool found = false; ExtractionCandidate value = null; if (Extractions != null) { int i = Extractions.Count - 1; while (!found && i >= 0) { value = Extractions[i]; var extractionExpression = (ExtractionExpression)value.Expression; found = (extractionExpression.FieldNumber == fieldNumber); i--; } } ExtractionCandidate result = found ? value : null; return result; } public override void Reject() { if (!IsRejected) { base.Reject(); DisposeWaitingTokens(); RemoveCompletedPendingAnySpanCandidates(); // Отмена цепочки кандидатов начинается с поиска кандидата, который сейчас совпадает. // Вызов OnCompleted производится на подъёме от совпадающего кандидата к корню. Candidate current = this; while (!current.IsCompleted && current.CurrentEventObserver != null) current = current.CurrentEventObserver; while (current != null) { current.OnCompleted(); if (current is AnySpanCandidate currentAnySpan) { if (currentAnySpan.IsPending) currentAnySpan.RemoveFromPendingCandidates(); } if (current.ParentCandidate != null) current = current.ParentCandidate; else current = current.TargetParentCandidate; } } } public sealed override void OnCompleted() { if (!IsCompleted) { SearchContext.CandidateFactory.UnregisterRootCandidate(this); SearchContext.Telemetry.TrackEnd(this); base.OnCompleted(); } } // Internal protected abstract void OnFinalMatch(); private void DisposeWaitingTokens() { if (fWaitingTokens != null) { fWaitingTokens.ForEach(x => x.Dispose()); fWaitingTokens = null; } } private void RemoveCompletedPendingAnySpanCandidates() { if (fCompletedPendingAnySpanCandidates != null) { fCompletedPendingAnySpanCandidates.ForEach(x => x.RemoveRelatedRootCandidate(this)); fCompletedPendingAnySpanCandidates = null; } } } }
35.20603
116
0.559378
[ "Apache-2.0" ]
Ilyat1337/nevod
Source/Engine/Candidates/RootCandidate.cs
7,137
C#
namespace BoardCraft.Input { using Models; /// <summary> /// Provide abstraction for component repository /// </summary> public interface IComponentRepository { Package GetPackage(string name); } }
19.916667
56
0.631799
[ "MIT" ]
niyoko/BoardCraft
BoardCraft/Models/Input/IComponentRepository.cs
241
C#
using PokemonUnity.Character; using PokemonUnity.Monster; using System; using System.Linq; using UnityEngine; namespace PokemonUnity.Overworld.Entity.Environment { public class RockClimbEntity : Entity { private ScriptBlock TempScriptEntity = null;// TODO Change to default(_) if this is not a reference type private bool TempClicked = false; // If true, walk up. public override void ClickFunction() { if (Badge.CanUseHMMove(Badge.HMMoves.RockClimb) | Game.IS_DEBUG_ACTIVE | Game.Player.SandBoxMode) { TempClicked = true; if (GetRockClimbPokemon() == null) Game.TextBox.Show("A Pokémon could~climb this rock...", new Entity[] { this }, true, true); else Game.TextBox.Show("A Pokémon could~climb this rock.*Do you want to~use Rock Climb?%Yes|No%", new Entity[] { this }, true, true); } } public override void WalkOntoFunction() { if (Badge.CanUseHMMove(Badge.HMMoves.RockClimb) | Game.IS_DEBUG_ACTIVE | Game.Player.SandBoxMode) { TempClicked = false; if (GetRockClimbPokemon() == null) Game.TextBox.Show("A Pokémon could~climb this rock...", new Entity[] { this }, true, true); else Game.TextBox.Show("A Pokémon could~climb this rock.*Do you want to~use Rock Climb?%Yes|No%", new Entity[] { this }, true, true); SoundManager.PlaySound("select"); } else Game.TextBox.Show("A path is engraved~into this rock...", new Entity[] { this }, true, true); } public override void ResultFunction(int Result) { if (Result == 0) { if (this.TempClicked) this.WalkUp(); else this.WalkDown(); } } private Monster.Pokemon GetRockClimbPokemon() { foreach (Monster.Pokemon teamPokemon in Game.Player.Party) { if (!teamPokemon.isEgg) { foreach (Attack.Move a in teamPokemon.moves) { if (a.MoveId == Moves.ROCK_CLIMB) return teamPokemon; } } } // No rock climb in team: if (Game.IS_DEBUG_ACTIVE | Game.Player.SandBoxMode) { if (Game.Player.Party.GetCount() > 0) return Game.Player.Party[0]; else { Monster.Pokemon p = new Monster.Pokemon((Pokemons)10, false);//Pokemon.GetPokemonByID(10); //p.Generate(10, true); return p; } } else return null;// TODO Change to default(_) if this is not a reference type } private void WalkUp() { int facing = System.Convert.ToInt32(this.Rotation.y / (double)MathHelper.PiOver2); facing -= 2; if (facing < 0) facing += 4; Game.Camera.PlannedMovement = Vector3.zero; if (Game.Camera.GetPlayerFacingDirection() == facing & !Game.Camera.IsMoving) { int Steps = 0; Vector3 checkPosition = Game.Camera.GetForwardMovedPosition(); checkPosition.y = checkPosition.y.ToInteger(); bool foundSteps = true; while (foundSteps) { Entity e = GetEntity(Game.Level.Entities, checkPosition, true, new System.Type[] { typeof(RockClimbEntity), typeof(ScriptBlock), typeof(WarpBlock) }); if (e != null) { if (e.EntityID == Entities.RockClimbEntity) { Steps += 1; checkPosition.x += Game.Camera.GetMoveDirection().x; checkPosition.z += Game.Camera.GetMoveDirection().z; checkPosition.y += 1; } else { if (e.EntityID == Entities.ScriptBlock) TempScriptEntity = (ScriptBlock)e; else if (e.EntityID == Entities.WarpBlock) ((WarpBlock)e).WalkAgainstFunction(); foundSteps = false; } } else foundSteps = false; } Game.Level.OverworldPokemon.Visible = false; Game.Level.OverworldPokemon.warped = true; string tempSkin = "";//Game.Player.Skin; Monster.Pokemon RockClimbPokemon = GetRockClimbPokemon(); //Game.Level.OwnPlayer.Texture = RockClimbPokemon.GetOverworldTexture(); Game.Level.OwnPlayer.ChangeTexture(); string s = "version=2" + System.Environment.NewLine + "@pokemon.cry(" + (int)RockClimbPokemon.Species + ")" + System.Environment.NewLine + "@player.setmovement(" + Game.Camera.GetMoveDirection().x + ",1," + Game.Camera.GetMoveDirection().z + ")" + System.Environment.NewLine + "@sound.play(destroy)" + System.Environment.NewLine + "@player.move(" + Steps + ")" + System.Environment.NewLine + "@player.setmovement(" + Game.Camera.GetMoveDirection().x + ",0," + Game.Camera.GetMoveDirection().z + ")" + System.Environment.NewLine + "@pokemon.hide" + System.Environment.NewLine + "@player.move(1)" + System.Environment.NewLine + "@pokemon.hide" + System.Environment.NewLine + "@player.wearskin(" + tempSkin + ")" + System.Environment.NewLine; if (this.TempScriptEntity != null) { s += GetScriptStartLine(this.TempScriptEntity) + System.Environment.NewLine; this.TempScriptEntity = null; } s += ":end"; // Reset the player's transparency: Game.Level.OwnPlayer.Opacity = 1.0f; //((OverworldScreen)Core.CurrentScreen).ActionScript.StartScript(s, 2, false); } facing = System.Convert.ToInt32(this.Rotation.y / (double)MathHelper.PiOver2); if (facing < 0) facing += 4; } private void WalkDown() { int facing = System.Convert.ToInt32(this.Rotation.y / (double)MathHelper.PiOver2); Game.Camera.PlannedMovement = Vector3.zero; if (Game.Camera.GetPlayerFacingDirection() == facing) { int Steps = 0; Vector3 checkPosition = Game.Camera.GetForwardMovedPosition(); checkPosition.y = checkPosition.y.ToInteger() - 1; bool foundSteps = true; while (foundSteps) { Entity e = GetEntity(Game.Level.Entities, checkPosition, true, new System.Type[] { typeof(RockClimbEntity), typeof(ScriptBlock), typeof(WarpBlock) }); if (e != null) { if (e.EntityID == Entities.RockClimbEntity) { Steps += 1; checkPosition.x += Game.Camera.GetMoveDirection().x; checkPosition.z += Game.Camera.GetMoveDirection().z; checkPosition.y -= 1; } else { if (e.EntityID == Entities.ScriptBlock) this.TempScriptEntity = (ScriptBlock)e; else if (e.EntityID == Entities.WarpBlock) ((WarpBlock)e).WalkAgainstFunction(); foundSteps = false; } } else foundSteps = false; } Game.Level.OverworldPokemon.Visible = false; Game.Level.OverworldPokemon.warped = true; string tempSkin = "";//Game.Player.Skin; Monster.Pokemon RockClimbPokemon = GetRockClimbPokemon(); //Game.Level.OwnPlayer.Texture = RockClimbPokemon.GetOverworldTexture(); Game.Level.OwnPlayer.ChangeTexture(); string s = "version=2" + System.Environment.NewLine + "@pokemon.cry(" + (int)RockClimbPokemon.Species + ")" + System.Environment.NewLine + "@player.move(1)" + System.Environment.NewLine + "@player.setmovement(" + Game.Camera.GetMoveDirection().x + ",-1," + Game.Camera.GetMoveDirection().z + ")" + System.Environment.NewLine + "@sound.play(destroy)" + System.Environment.NewLine + "@player.move(" + Steps + ")" + System.Environment.NewLine + "@pokemon.hide" + System.Environment.NewLine + "@player.wearskin(" + tempSkin + ")" + System.Environment.NewLine; if (this.TempScriptEntity != null) { s += GetScriptStartLine(this.TempScriptEntity) + System.Environment.NewLine; this.TempScriptEntity = null; } s += ":end"; // Reset the player's transparency: Game.Level.OwnPlayer.Opacity = 1.0f; //((OverworldScreen)Core.CurrentScreen).ActionScript.StartScript(s, 2, false); } } private string GetScriptStartLine(ScriptBlock ScriptEntity) { if (ScriptEntity != null) { if (ScriptEntity.CorrectRotation()) { switch (ScriptEntity.GetActivationID()) { case 0: { return "@script.start(" + ScriptEntity.ScriptID + ")"; } case 1: { return "@script.text(" + ScriptEntity.ScriptID + ")"; } case 2: { return "@script.run(" + ScriptEntity.ScriptID + ")"; } } } } return ""; } public override void Render() { //this.Draw(this.Model, Textures, false); } } }
30.977186
743
0.646127
[ "BSD-3-Clause" ]
AriesPlaysNation/PokemonUnity
Pokemon Unity/Assets/Scripts2/Overworld/Entites/Enviroment/RockClimbEntity.cs
8,153
C#
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using QFramework; namespace QFramework.GraphDesigner { public class GenericNodeChildItem : DiagramNodeItem { public override string FullLabel { get { return Name; } } public override string Label { get { return Name; } } public override void Remove(IDiagramNode diagramNode) { } public override void OnConnectedToInput(IConnectable input) { base.OnConnectedToInput(input); } //private List<string> _connectedGraphItemIds = new List<string>(); //public IEnumerable<IGraphItem> ConnectedGraphItems //{ // get // { // foreach (var item in Node.Project.NodeItems) // { // if (ConnectedGraphItemIds.Contains(item.Identifier)) // yield return item; // foreach (var child in item.ContainedItems) // { // if (ConnectedGraphItemIds.Contains(child.Identifier)) // { // yield return child; // } // } // } // } //} //public List<string> ConnectedGraphItemIds //{ // get { return _connectedGraphItemIds; } // set { _connectedGraphItemIds = value; } //} } }
24.606061
80
0.472906
[ "MIT" ]
DiazGames/oneGame
Assets/QFramework/Framework/0.Core/Editor/0.EditorKit/uFrame.Editor/Systems/Graphs/Data/GenericNodeChildItem.cs
1,626
C#
// // AzureFunctionForSplunkVS // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // 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 Microsoft.Azure.WebJobs; using Microsoft.Azure.WebJobs.Host; using Microsoft.Azure.WebJobs.ServiceBus; using System.Threading.Tasks; namespace AzureFunctionForSplunk { public static class EhDiagnosticLogsExt { [FunctionName("EhDiagnosticLogsExt")] public static async Task Run( [EventHubTrigger("%input-hub-name-diagnostics-logs%", Connection = "hubConnection")]string[] messages, IBinder blobFaultBinder, Binder queueFaultBinder, TraceWriter log) { var runner = new Runner(); await runner.Run<DiagnosticLogMessages, DiagnosticLogsSplunkEventMessages>(messages, blobFaultBinder, queueFaultBinder, log); } } }
40.354167
137
0.728446
[ "MIT" ]
bennbatt8112/AzureFunctionforSplunkVS
AzureFunctionForSplunk/EhDiagnosticLogsExt.cs
1,937
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Threading.Tasks; namespace Microsoft.AspNet.Mvc.ModelBinding { public class SimpleTypeModelBinder : IModelBinder { public Task<ModelBindingResult> BindModelAsync(ModelBindingContext bindingContext) { // This method is optimized to use cached tasks when possible and avoid allocating // using Task.FromResult. If you need to make changes of this nature, profile // allocations afterwards and look for Task<ModelBindingResult>. if (bindingContext.ModelMetadata.IsComplexType) { // this type cannot be converted return ModelBindingResult.NoResultAsync; } var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName); if (valueProviderResult == ValueProviderResult.None) { // no entry return ModelBindingResult.NoResultAsync; } bindingContext.ModelState.SetModelValue(bindingContext.ModelName, valueProviderResult); try { var model = valueProviderResult.ConvertTo(bindingContext.ModelType); if (bindingContext.ModelType == typeof(string)) { var modelAsString = model as string; if (bindingContext.ModelMetadata.ConvertEmptyStringToNull && string.IsNullOrWhiteSpace(modelAsString)) { model = null; } } // When converting newModel a null value may indicate a failed conversion for an otherwise required // model (can't set a ValueType to null). This detects if a null model value is acceptable given the // current bindingContext. If not, an error is logged. if (model == null && !bindingContext.ModelMetadata.IsReferenceOrNullableType) { bindingContext.ModelState.TryAddModelError( bindingContext.ModelName, bindingContext.ModelMetadata.ModelBindingMessageProvider.ValueMustNotBeNullAccessor( valueProviderResult.ToString())); return ModelBindingResult.FailedAsync(bindingContext.ModelName); } else { return ModelBindingResult.SuccessAsync(bindingContext.ModelName, model); } } catch (Exception exception) { bindingContext.ModelState.TryAddModelError( bindingContext.ModelName, exception, bindingContext.ModelMetadata); // Were able to find a converter for the type but conversion failed. // Tell the model binding system to skip other model binders. return ModelBindingResult.FailedAsync(bindingContext.ModelName); } } } }
42.233766
116
0.590098
[ "Apache-2.0" ]
VGGeorgiev/Mvc
src/Microsoft.AspNet.Mvc.Core/ModelBinding/SimpleTypeModelBinder.cs
3,252
C#
using Amazon.JSII.Runtime.Deputy; #pragma warning disable CS0672,CS0809,CS1591 namespace aws { [JsiiInterface(nativeType: typeof(ICodedeployDeploymentGroupEc2TagFilter), fullyQualifiedName: "aws.CodedeployDeploymentGroupEc2TagFilter")] public interface ICodedeployDeploymentGroupEc2TagFilter { [JsiiProperty(name: "key", typeJson: "{\"primitive\":\"string\"}", isOptional: true)] [Amazon.JSII.Runtime.Deputy.JsiiOptional] string? Key { get { return null; } } [JsiiProperty(name: "type", typeJson: "{\"primitive\":\"string\"}", isOptional: true)] [Amazon.JSII.Runtime.Deputy.JsiiOptional] string? Type { get { return null; } } [JsiiProperty(name: "value", typeJson: "{\"primitive\":\"string\"}", isOptional: true)] [Amazon.JSII.Runtime.Deputy.JsiiOptional] string? Value { get { return null; } } [JsiiTypeProxy(nativeType: typeof(ICodedeployDeploymentGroupEc2TagFilter), fullyQualifiedName: "aws.CodedeployDeploymentGroupEc2TagFilter")] internal sealed class _Proxy : DeputyBase, aws.ICodedeployDeploymentGroupEc2TagFilter { private _Proxy(ByRefValue reference): base(reference) { } [JsiiOptional] [JsiiProperty(name: "key", typeJson: "{\"primitive\":\"string\"}", isOptional: true)] public string? Key { get => GetInstanceProperty<string?>(); } [JsiiOptional] [JsiiProperty(name: "type", typeJson: "{\"primitive\":\"string\"}", isOptional: true)] public string? Type { get => GetInstanceProperty<string?>(); } [JsiiOptional] [JsiiProperty(name: "value", typeJson: "{\"primitive\":\"string\"}", isOptional: true)] public string? Value { get => GetInstanceProperty<string?>(); } } } }
31.128571
148
0.544286
[ "MIT" ]
scottenriquez/cdktf-alpha-csharp-testing
resources/.gen/aws/aws/ICodedeployDeploymentGroupEc2TagFilter.cs
2,179
C#
/************************************************************************************************ The MIT License (MIT) Copyright (c) 2015 Microsoft Corporation 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 Microsoft.Identity.Client; using System; using System.Runtime.Caching; using System.Security.Claims; namespace WebApp.Utils { /// <summary> /// An implementation of token cache for both Confidential and Public clients backed by MemoryCache. /// MemoryCache is useful in Api scenarios where there is no HttpContext to cache data. /// </summary> /// <seealso cref="https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/wiki/token-cache-serialization"/> public class MSALPerUserMemoryTokenCache { /// <summary> /// The backing MemoryCache instance /// </summary> internal readonly MemoryCache memoryCache = MemoryCache.Default; /// <summary> /// The duration till the tokens are kept in memory cache. In production, a higher value, upto 90 days is recommended. /// </summary> private readonly DateTimeOffset cacheDuration = DateTimeOffset.Now.AddHours(48); /// <summary> /// Once the user signes in, this will not be null and can be obtained via a call to Thread.CurrentPrincipal /// </summary> internal ClaimsPrincipal SignedInUser; /// <summary> /// Initializes a new instance of the <see cref="MSALPerUserMemoryTokenCache"/> class. /// </summary> /// <param name="tokenCache">The client's instance of the token cache.</param> public MSALPerUserMemoryTokenCache(ITokenCache tokenCache) { Initialize(tokenCache, ClaimsPrincipal.Current); } /// <summary> /// Initializes a new instance of the <see cref="MSALPerUserMemoryTokenCache"/> class. /// </summary> /// <param name="tokenCache">The client's instance of the token cache.</param> /// <param name="user">The signed-in user for whom the cache needs to be established.</param> public MSALPerUserMemoryTokenCache(ITokenCache tokenCache, ClaimsPrincipal user) { Initialize(tokenCache, user); } /// <summary>Initializes the cache instance</summary> /// <param name="tokenCache">The ITokenCache passed through the constructor</param> /// <param name="user">The signed-in user for whom the cache needs to be established..</param> private void Initialize(ITokenCache tokenCache, ClaimsPrincipal user) { SignedInUser = user; tokenCache.SetBeforeAccess(UserTokenCacheBeforeAccessNotification); tokenCache.SetAfterAccess(UserTokenCacheAfterAccessNotification); tokenCache.SetBeforeWrite(UserTokenCacheBeforeWriteNotification); if (SignedInUser == null) { // No users signed in yet, so we return return; } } /// <summary> /// Explores the Claims of a signed-in user (if available) to populate the unique Id of this cache's instance. /// </summary> /// <returns>The signed in user's object.tenant Id , if available in the ClaimsPrincipal.Current instance</returns> internal string GetMsalAccountId() { if (SignedInUser != null) { return SignedInUser.GetMsalAccountId(); } return null; } /// <summary> /// Clears the TokenCache's copy of this user's cache. /// </summary> public void Clear() { memoryCache.Remove(GetMsalAccountId()); } /// <summary> /// Triggered right after MSAL accessed the cache. /// </summary> /// <param name="args">Contains parameters used by the MSAL call accessing the cache.</param> private void UserTokenCacheAfterAccessNotification(TokenCacheNotificationArgs args) { SetSignedInUserFromNotificationArgs(args); // if the access operation resulted in a cache update if (args.HasStateChanged) { string cacheKey = GetMsalAccountId(); if (string.IsNullOrWhiteSpace(cacheKey)) return; // Ideally, methods that load and persist should be thread safe.MemoryCache.Get() is thread safe. this.memoryCache.Set(cacheKey, args.TokenCache.SerializeMsalV3(), cacheDuration); } } /// <summary> /// Triggered right before MSAL needs to access the cache. Reload the cache from the persistence store in case it changed since the last access. /// </summary> /// <param name="args">Contains parameters used by the MSAL call accessing the cache.</param> private void UserTokenCacheBeforeAccessNotification(TokenCacheNotificationArgs args) { string cacheKey = GetMsalAccountId(); if (string.IsNullOrWhiteSpace(cacheKey)) return; byte[] tokenCacheBytes = (byte[])this.memoryCache.Get(cacheKey); args.TokenCache.DeserializeMsalV3(tokenCacheBytes, shouldClearExistingCache: true); } /// <summary> /// if you want to ensure that no concurrent write take place, use this notification to place a lock on the entry /// </summary> /// <param name="args">Contains parameters used by the MSAL call accessing the cache.</param> private void UserTokenCacheBeforeWriteNotification(TokenCacheNotificationArgs args) { // Since we are using a MemoryCache ,whose methods are threads safe, we need not to do anything in this handler. } /// <summary> /// To keep the cache, ClaimsPrincipal and Sql in sync, we ensure that the user's object Id we obtained by MSAL after /// successful sign-in is set as the key for the cache. /// </summary> /// <param name="args">Contains parameters used by the MSAL call accessing the cache.</param> private void SetSignedInUserFromNotificationArgs(TokenCacheNotificationArgs args) { if (SignedInUser == null && args.Account != null) { SignedInUser = args.Account.ToClaimsPrincipal(); } } } }
44.1
152
0.638522
[ "MIT" ]
madansr7/ms-identity-aspnet-webapp-openidconnect
WebApp/Utils/MSALPerUserMemoryTokenCache.cs
7,499
C#
using System; using CPUx86 = XSharp.Assembler.x86; using CPU = XSharp.Assembler.x86; using XSharp.Assembler.x86; using XSharp.Assembler; using XSharp.Assembler.x86.SSE; using XSharp.Assembler.x86.x87; using XSharp; using static XSharp.XSRegisters; using static XSharp.Assembler.x86.SSE.ComparePseudoOpcodes; namespace Cosmos.IL2CPU.X86.IL { [Cosmos.IL2CPU.OpCode( ILOpCode.Code.Cgt )] public class Cgt : ILOp { public Cgt( XSharp.Assembler.Assembler aAsmblr ) : base( aAsmblr ) { } public override void Execute(_MethodInfo aMethod, ILOpCode aOpCode ) { var xStackItem = aOpCode.StackPopTypes[0]; var xStackItemSize = SizeOfType(xStackItem); var xStackItemIsFloat = TypeIsFloat(xStackItem); if( xStackItemSize > 8 ) { //EmitNotImplementedException( Assembler, GetServiceProvider(), "Cgt: StackSizes>8 not supported", CurInstructionLabel, mMethodInfo, mCurrentOffset, NextInstructionLabel ); throw new NotImplementedException("Cosmos.IL2CPU.x86->IL->Cgt.cs->Error: StackSizes > 8 not supported"); //return; } string BaseLabel = GetLabel( aMethod, aOpCode ) + "."; string LabelTrue = BaseLabel + "True"; string LabelFalse = BaseLabel + "False"; var xNextLabel = GetLabel(aMethod, aOpCode.NextPosition); if( xStackItemSize > 4 ) { // Using SSE registers (that do NOT branch!) This is needed only for long now #if false XS.Set(XSRegisters.ESI, 1); // esi = 1 XS.Xor(XSRegisters.EDI, XSRegisters.EDI); // edi = 0 #endif if (xStackItemIsFloat) { // Please note that SSE supports double operations only from version 2 XS.SSE2.MoveSD(XMM0, ESP, sourceIsIndirect: true); // Increment ESP to get the value of the next double XS.Add(ESP, 8); XS.SSE2.MoveSD(XMM1, ESP, sourceIsIndirect: true); XS.SSE2.CompareSD(XMM1, XMM0, comparision: NotLessThanOrEqualTo); XS.MoveD(EBX, XMM1); XS.And(EBX, 1); // We need to move the stack pointer of 4 Byte to "eat" the second double that is yet in the stack or we get a corrupted stack! XS.Add(ESP, 4); XS.Set(ESP, EBX, destinationIsIndirect: true); } else { XS.Set(ESI, 1); // esi = 1 XS.Xor(EDI, EDI); // edi = 0 XS.Pop(EAX); XS.Pop(EDX); //value2: EDX:EAX XS.Pop(EBX); XS.Pop(ECX); //value1: ECX:EBX XS.Compare(ECX, EDX); XS.Jump(ConditionalTestEnum.GreaterThan, LabelTrue); XS.Jump(ConditionalTestEnum.LessThan, LabelFalse); XS.Compare(EBX, EAX); XS.Label(LabelTrue); new ConditionalMove { Condition = ConditionalTestEnum.GreaterThan, DestinationReg = RegistersEnum.EDI, SourceReg = RegistersEnum.ESI }; XS.Label(LabelFalse); XS.Push(EDI); } /* XS.Jump(ConditionalTestEnum.GreaterThan, LabelTrue); XS.Label(LabelFalse); XS.Push(0); XS.Jump(xNextLabel); XS.Label(LabelTrue ); XS.Push(1);*/ } else { if (xStackItemIsFloat){ XS.SSE.MoveSS(XMM0, ESP, sourceIsIndirect: true); XS.Add(XSRegisters.ESP, 4); XS.SSE.MoveSS(XMM1, ESP, sourceIsIndirect: true); XS.SSE.CompareSS(XMM1, XMM0, comparision: NotLessThanOrEqualTo); XS.MoveD(EBX, XMM1); XS.And(XSRegisters.EBX, 1); XS.Set(ESP, EBX, destinationIsIndirect: true); } else{ XS.Pop(EAX); XS.Compare(EAX, ESP, sourceIsIndirect: true); XS.Jump(ConditionalTestEnum.LessThan, LabelTrue); XS.Jump(LabelFalse); XS.Label(LabelTrue ); XS.Add(XSRegisters.ESP, 4); XS.Push(1); XS.Jump(xNextLabel); XS.Label(LabelFalse ); XS.Add(XSRegisters.ESP, 4); XS.Push(0); } } } } }
33.366667
176
0.605894
[ "BSD-3-Clause" ]
Dark-Tater/IL2CPU
source/Cosmos.IL2CPU/IL/Cgt.cs
4,004
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("Tables")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Tables")] [assembly: AssemblyCopyright("Copyright © 2015")] [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("661d57d6-3470-4f4a-8068-f9026d5e4853")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.361111
84
0.746468
[ "MIT" ]
NayaIT/TelerikAcademyOnline
HTML-CSS/HTML/Tables/Tables/Properties/AssemblyInfo.cs
1,348
C#
using System; using System.Globalization; using System.Linq; using System.Reflection; namespace Capstone_Project_VITBU_Server.Areas.HelpPage.ModelDescriptions { internal static class ModelNameHelper { // Modify this to provide custom model name mapping. public static string GetModelName(Type type) { ModelNameAttribute modelNameAttribute = type.GetCustomAttribute<ModelNameAttribute>(); if (modelNameAttribute != null && !String.IsNullOrEmpty(modelNameAttribute.Name)) { return modelNameAttribute.Name; } string modelName = type.Name; if (type.IsGenericType) { // Format the generic type name to something like: GenericOfAgurment1AndArgument2 Type genericType = type.GetGenericTypeDefinition(); Type[] genericArguments = type.GetGenericArguments(); string genericTypeName = genericType.Name; // Trim the generic parameter counts from the name genericTypeName = genericTypeName.Substring(0, genericTypeName.IndexOf('`')); string[] argumentTypeNames = genericArguments.Select(t => GetModelName(t)).ToArray(); modelName = String.Format(CultureInfo.InvariantCulture, "{0}Of{1}", genericTypeName, String.Join("And", argumentTypeNames)); } return modelName; } } }
40.5
140
0.640604
[ "MIT" ]
sanskar-singh-rajput/VitBU-IPPS
Capstone Project VITBU Server/Capstone Project VITBU Server/Areas/HelpPage/ModelDescriptions/ModelNameHelper.cs
1,458
C#
using System; using DNX.Helpers.Linq; using NUnit.Framework; namespace Test.DNX.Helpers.Linq { [TestFixture] public class EnumerableExtensionsTests { [TestCase("a,b,c,d,e", ExpectedResult = 5)] [TestCase("", ExpectedResult = 0)] [TestCase(null, ExpectedResult = 0)] public int ToConcreteListTest(string commaSeparatedList) { var list = commaSeparatedList == null ? null : commaSeparatedList.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); return list.ToConcreteList().Count; } [TestCase("a,b,c,d,e", ExpectedResult = 5)] [TestCase("", ExpectedResult = 0)] [TestCase(null, ExpectedResult = -1)] public int ToListOrNullTest(string commaSeparatedList) { var list = commaSeparatedList == null ? null : commaSeparatedList.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); return list == null ? -1 : list.ToListOrNull().Count; } } }
31.085714
101
0.597426
[ "MIT" ]
martinsmith1968/DNX.Helpers
Test.DNX.Helpers/Linq/EnumerableExtensionsTests.cs
1,090
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // 有关程序集的一般信息由以下 // 控制。更改这些特性值可修改 // 与程序集关联的信息。 [assembly: AssemblyTitle("TemplateMethodPattern")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("TemplateMethodPattern")] [assembly: AssemblyCopyright("Copyright © Microsoft 2018")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // 将 ComVisible 设置为 false 会使此程序集中的类型 //对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型 //请将此类型的 ComVisible 特性设置为 true。 [assembly: ComVisible(false)] // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID [assembly: Guid("1c9efd7e-6dd1-4f18-bc1e-578c8dd9b108")] // 程序集的版本信息由下列四个值组成: // // 主版本 // 次版本 // 生成号 // 修订号 // // 可以指定所有值,也可以使用以下所示的 "*" 预置版本号和修订号 // 方法是按如下所示使用“*”: : // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
26.513514
59
0.72579
[ "Apache-2.0" ]
flyingfive/DesignPattern
TemplateMethodPattern/Properties/AssemblyInfo.cs
1,322
C#
using Amazon.S3; using Amazon.S3.Model; using ImageProcessor; using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; //using System.Drawing.Imaging; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Web; namespace Slk.Common { public class AwsBucket { //private static CloudBlobContainer container; private static string _hostName = "https://s3-us-west-2.amazonaws.com"; private static string _bucketName = "bucket4slk"; private static string accessKey = "x"; private static string secretKey = "y"; static AwsBucket() { } public static string StoreImage(byte[] imageBytes, string fileName) { var newFileName = getUniqueName(fileName); using (var stream = new MemoryStream(imageBytes)) //System.Convert.FromBase64String(image64String) { using (var client = Amazon.AWSClientFactory.CreateAmazonS3Client(accessKey, secretKey, Amazon.RegionEndpoint.USWest2)) { var request = new PutObjectRequest(); request.BucketName = _bucketName; request.CannedACL = S3CannedACL.PublicRead; request.Key = newFileName; request.InputStream = stream; var resp = client.PutObject(request); if (resp.HttpStatusCode == System.Net.HttpStatusCode.OK) return getFullName(newFileName); return null; } } } public static string StoreImage(HttpPostedFileBase image) { // Read a file and resize it. //byte[] photoBytes = File.ReadAllBytes(file); int quality = 70; var format = new ImageProcessor.Imaging.Formats.JpegFormat(); Size size = new Size(300, 0); using (var imageStream = new MemoryStream()) { image.InputStream.CopyTo(imageStream); imageStream.Position = 0; using (var resizeImageStream = new MemoryStream()) { using (ImageFactory imageFactory = new ImageFactory()) { // Load, resize, set the format and quality and save an image. imageFactory.Load(imageStream) .Resize(size) .Format(format) .Quality(quality) .Save(resizeImageStream); } using (var client = Amazon.AWSClientFactory.CreateAmazonS3Client(accessKey, secretKey, Amazon.RegionEndpoint.USWest2)) { var newFileName = getUniqueName(image.FileName); var request = new PutObjectRequest(); request.BucketName = _bucketName; request.CannedACL = S3CannedACL.PublicRead; // Save Resize version to folder "thumb" request.Key = $"thumb/{newFileName}"; request.InputStream = resizeImageStream; var resp = client.PutObject(request); // Save Original version to root folder request.Key = newFileName; request.InputStream = imageStream; client.PutObject(request); if (resp.HttpStatusCode == System.Net.HttpStatusCode.OK) return getFullName(newFileName); return null; } } } } public static void RemoveImage(string fileName) { using (var client = Amazon.AWSClientFactory.CreateAmazonS3Client(accessKey, secretKey, Amazon.RegionEndpoint.USWest2)) { client.DeleteObject(_bucketName, fileName); try { client.DeleteObject($"thumb/{_bucketName}", fileName); } catch { } } } private static string getUniqueName(string fileName) { var ext = Path.GetExtension(fileName).ToLower(); var guid = Guid.NewGuid().ToString(); return string.Format("{0}{1}", guid, ext).ToLowerInvariant(); } public static string getFullName(string fileName) { return $"{_hostName}/{_bucketName}/{fileName}"; } public static IEnumerable<string> GetImages() { var lbFiles = new List<string>(); using (var client = Amazon.AWSClientFactory.CreateAmazonS3Client(accessKey, secretKey, Amazon.RegionEndpoint.USWest2)) { var list = client.ListObjects(new ListObjectsRequest { BucketName = _bucketName }); foreach (var file in list.S3Objects.Where(w => !w.Key.Contains("thumb"))) lbFiles.Add(getFullName(file.Key)); return lbFiles; } } } }
35.864865
138
0.53052
[ "Apache-2.0" ]
DmitriyVetrov/SLK
Slk.Common/AwsBucket.cs
5,310
C#
using System; using UnityEngine; using UnityEngine.Playables; using UnityEngine.Timeline; namespace UTJ { [Serializable] public class VRFaderClip : PlayableAsset, ITimelineClipAsset { public VRFaderBehaviour template = new VRFaderBehaviour(); #if UNITY_EDITOR [NonSerialized] private TimelineClip clipBind; public void SetTimelineClip(TimelineClip clip) { clipBind = clip; ApplyClipDisplayName(); } public void ApplyClipDisplayName() { string displayName = ""; if (template.FadeType == VRFaderBehaviour.EFadeInOut.FadeIn) { displayName = "FadeIn"; } else { displayName = "FadeOut"; } if (clipBind != null) { clipBind.displayName = displayName; } } #endif public ClipCaps clipCaps { get { return ClipCaps.None; } } public override Playable CreatePlayable(PlayableGraph graph, GameObject owner) { var playable = ScriptPlayable<VRFaderBehaviour>.Create(graph, template); return playable; } } }
24.773585
87
0.53313
[ "MIT" ]
wotakuro/VRTeleportationTourTemplate
Assets/VRFade/Script/VRFaderClip.cs
1,313
C#
// <auto-generated> This file has been auto generated by EF Core Power Tools. </auto-generated> using System; using System.Collections.Generic; #nullable disable namespace T0001 { public partial class VBaseCargospacelistQuery { public string Id { get; set; } public string Cpositioncode { get; set; } public string Cposition { get; set; } public decimal? Imaxcapacity { get; set; } public string Cmemo { get; set; } public string Cdefine1 { get; set; } public string Cdefine2 { get; set; } public DateTime? Ddefine3 { get; set; } public DateTime? Ddefine4 { get; set; } public decimal? Idefine5 { get; set; } public string Cstatus { get; set; } public string Ctype { get; set; } public string Warehouseid { get; set; } public decimal? Ipriority { get; set; } public decimal? Ilength { get; set; } public decimal? Iwidth { get; set; } public decimal? Iheight { get; set; } public decimal? Ivolume { get; set; } public string Cusetype { get; set; } public string Cx { get; set; } public string Cy { get; set; } public string Cz { get; set; } public DateTime? Dexpiredate { get; set; } public string Calias { get; set; } public string Cerpcode { get; set; } public decimal? Ipermitmix { get; set; } public string Lineid { get; set; } public DateTime? Createtime { get; set; } public decimal? Ioccupyqty { get; set; } public decimal? IsAllo { get; set; } public string Lastcstatus { get; set; } public string Createowner { get; set; } public DateTime? Lastupdatetime { get; set; } public string Lastupdateowner { get; set; } public string PalletCode { get; set; } public string Productcode { get; set; } public decimal? Volume { get; set; } public decimal? Volumeunit { get; set; } public decimal? Occupyweight { get; set; } public decimal? Occupyvolume { get; set; } public decimal? Weight { get; set; } public decimal? Weightunit { get; set; } public string Cwareid { get; set; } public string WId { get; set; } public string WName { get; set; } } }
41.719298
97
0.581581
[ "MIT" ]
twoutlook/BlazorServerDbContextExample
BlazorServerEFCoreSample/T0001/VBaseCargospacelistQuery.cs
2,380
C#
using Snowflake.Configuration; namespace Snowflake.Plugin.Emulators.RetroArch.Configuration { [ConfigurationSection("config", "Configuration Options")] public partial interface ConfigConfiguration { [ConfigurationOption("config_save_on_exit", false, DisplayName = "Save Config on exit", Private = true)] bool ConfigSaveOnExit { get; set; } [ConfigurationOption("auto_overrides_enable", false, DisplayName = "Automatically load config overrides", Private = true)] bool AutoOverridesEnable { get; set; } } }
35.5625
113
0.710018
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
SnowflakePowered/snowflake
src/Snowflake.Plugin.Emulators.RetroArch/Configuration/ConfigConfiguration.cs
571
C#
/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * 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; namespace Alphaleonis.Win32.Security { /// <summary>The SECURITY_INFORMATION data type identifies the object-related security information being set or queried. /// This security information includes: /// The owner of an object; /// The primary group of an object; /// The discretionary access control list (DACL) of an object; /// The system access control list (SACL) of an object; /// </summary> /// <remarks> /// An unsigned 32-bit integer specifies portions of a SECURITY_DESCRIPTOR by means of bit flags. /// Individual bit values (combinable with the bitwise OR operation) are as shown in the following table. /// </remarks> [Flags] internal enum SECURITY_INFORMATION : uint { /// <summary>None</summary> None = 0, /// <summary>OWNER_SECURITY_INFORMATION (0x00000001) - The owner identifier of the object is being referenced.</summary> OWNER_SECURITY_INFORMATION = 1, /// <summary>GROUP_SECURITY_INFORMATION (0x00000002) - The primary group identifier of the object is being referenced.</summary> GROUP_SECURITY_INFORMATION = 2, /// <summary>DACL_SECURITY_INFORMATION (0x00000004) - The DACL of the object is being referenced.</summary> DACL_SECURITY_INFORMATION = 4, /// <summary>SACL_SECURITY_INFORMATION (0x00000008) - The SACL of the object is being referenced.</summary> SACL_SECURITY_INFORMATION = 8, /// <summary>LABEL_SECURITY_INFORMATION (0x00000010) - The mandatory integrity label is being referenced. The mandatory integrity label is an ACE in the SACL of the object.</summary> /// <remarks>Windows Server 2003 and Windows XP: This bit flag is not available.</remarks> LABEL_SECURITY_INFORMATION = 16, /// <summary>ATTRIBUTE_SECURITY_INFORMATION (0x00000020) - The resource properties of the object being referenced. /// The resource properties are stored in SYSTEM_RESOURCE_ATTRIBUTE_ACE types in the SACL of the security descriptor. /// </summary> /// <remarks>Windows Server 2008 R2, Windows 7, Windows Server 2008, Windows Vista, Windows Server 2003, and Windows XP: This bit flag is not available.</remarks> ATTRIBUTE_SECURITY_INFORMATION = 32, /// <summary>SCOPE_SECURITY_INFORMATION (0x00000040) - The Central Access Policy (CAP) identifier applicable on the object that is being referenced. /// Each CAP identifier is stored in a SYSTEM_SCOPED_POLICY_ID_ACE type in the SACL of the SD. /// </summary> /// <remarks>Windows Server 2008 R2, Windows 7, Windows Server 2008, Windows Vista, Windows Server 2003, and Windows XP: This bit flag is not available.</remarks> SCOPE_SECURITY_INFORMATION = 64, /// <summary>BACKUP_SECURITY_INFORMATION (0x00010000) - All parts of the security descriptor. This is useful for backup and restore software that needs to preserve the entire security descriptor.</summary> /// <remarks>Windows Server 2008 R2, Windows 7, Windows Server 2008, Windows Vista, Windows Server 2003, and Windows XP: This bit flag is not available.</remarks> BACKUP_SECURITY_INFORMATION = 65536, /// <summary>UNPROTECTED_SACL_SECURITY_INFORMATION (0x10000000) - The SACL inherits ACEs from the parent object.</summary> UNPROTECTED_SACL_SECURITY_INFORMATION = 268435456, /// <summary>UNPROTECTED_DACL_SECURITY_INFORMATION (0x20000000) - The DACL inherits ACEs from the parent object.</summary> UNPROTECTED_DACL_SECURITY_INFORMATION = 536870912, /// <summary>PROTECTED_SACL_SECURITY_INFORMATION (0x40000000) - The SACL cannot inherit ACEs.</summary> PROTECTED_SACL_SECURITY_INFORMATION = 1073741824, /// <summary>PROTECTED_DACL_SECURITY_INFORMATION (0x80000000) - The DACL cannot inherit access control entries (ACEs).</summary> PROTECTED_DACL_SECURITY_INFORMATION = 2147483648 } }
57.840909
211
0.736935
[ "MIT" ]
DamirAinullin/AlphaFS
src/AlphaFS/Security/Native Other/SECURITY_INFORMATION.cs
5,090
C#
/* * Domain Public API * * See https://developer.domain.com.au for more information * * The version of the OpenAPI document: v2 * Contact: api@domain.com.au * Generated by: https://github.com/openapitools/openapi-generator.git */ using Xunit; using System; using System.Linq; using System.IO; using System.Collections.Generic; using Domain.Api.V2.Api; using Domain.Api.V2.Model; using Domain.Api.V2.Client; using System.Reflection; using Newtonsoft.Json; namespace Domain.Api.V2.Test.Model { /// <summary> /// Class for testing PreMarketV1PropertyMedia /// </summary> /// <remarks> /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). /// Please update the test case below to test the model. /// </remarks> public class PreMarketV1PropertyMediaTests : IDisposable { // TODO uncomment below to declare an instance variable for PreMarketV1PropertyMedia //private PreMarketV1PropertyMedia instance; public PreMarketV1PropertyMediaTests() { // TODO uncomment below to create an instance of PreMarketV1PropertyMedia //instance = new PreMarketV1PropertyMedia(); } public void Dispose() { // Cleanup when everything is done. } /// <summary> /// Test an instance of PreMarketV1PropertyMedia /// </summary> [Fact] public void PreMarketV1PropertyMediaInstanceTest() { // TODO uncomment below to test "IsType" PreMarketV1PropertyMedia //Assert.IsType<PreMarketV1PropertyMedia>(instance); } /// <summary> /// Test the property 'ResourceType' /// </summary> [Fact] public void ResourceTypeTest() { // TODO unit test for the property 'ResourceType' } /// <summary> /// Test the property 'Url' /// </summary> [Fact] public void UrlTest() { // TODO unit test for the property 'Url' } } }
26.1375
99
0.618843
[ "MIT" ]
neildobson-au/InvestOz
src/Integrations/Domain/Domain.Api.V2/src/Domain.Api.V2.Test/Model/PreMarketV1PropertyMediaTests.cs
2,091
C#
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Routing; using Microsoft.VisualStudio.TestTools.UnitTesting; using Prometheus.HttpMetrics; using System; using System.Linq; using System.Threading.Tasks; namespace Prometheus.Tests.HttpExporter { /// <summary> /// We assume that all the HTTP metrics implement the same route parameter to metric label mapping logic. /// Therefore, we only perform these tests on one of the metric types we measure, to avoid needless duplication. /// </summary> [TestClass] public sealed class RouteParameterMappingTests { private readonly DefaultHttpContext _context; private readonly RequestDelegate _next; private readonly CollectorRegistry _registry; private readonly MetricFactory _metrics; private const int TestStatusCode = 204; private const string TestMethod = "DELETE"; private const string TestController = "controllerAbcde"; private const string TestAction = "action1234"; public RouteParameterMappingTests() { _registry = Metrics.NewCustomRegistry(); _metrics = Metrics.WithCustomRegistry(_registry); _next = context => Task.CompletedTask; _context = new DefaultHttpContext(); } [TestMethod] public void DefaultMetric_AppliesStandardLabels() { SetupHttpContext(_context, TestStatusCode, TestMethod, TestAction, TestController); var middleware = new HttpRequestCountMiddleware(_next, new HttpRequestCountOptions { Registry = _registry }); var child = (ChildBase)middleware.CreateChild(_context); CollectionAssert.AreEquivalent(HttpRequestLabelNames.All, child.Labels.Names); CollectionAssert.AreEquivalent(new[] { TestStatusCode.ToString(), TestMethod, TestAction, TestController }, child.Labels.Values); } [TestMethod] public void CustomMetric_WithNoLabels_AppliesNoLabels() { SetupHttpContext(_context, TestStatusCode, TestMethod, TestAction, TestController); var middleware = new HttpRequestCountMiddleware(_next, new HttpRequestCountOptions { Counter = _metrics.CreateCounter("xxx", "") }); var child = (ChildBase)middleware.CreateChild(_context); Assert.AreEqual(0, child.Labels.Count); } [TestMethod] public void CustomMetric_WithStandardLabels_AppliesStandardLabels() { SetupHttpContext(_context, TestStatusCode, TestMethod, TestAction, TestController); var middleware = new HttpRequestCountMiddleware(_next, new HttpRequestCountOptions { Counter = _metrics.CreateCounter("xxx", "", HttpRequestLabelNames.All) }); var child = (ChildBase)middleware.CreateChild(_context); CollectionAssert.AreEquivalent(HttpRequestLabelNames.All, child.Labels.Names); CollectionAssert.AreEquivalent(new[] { TestStatusCode.ToString(), TestMethod, TestAction, TestController }, child.Labels.Values); } [TestMethod] public void CustomMetric_WithExtendedLabels_AppliesExtendedLabels() { // Route parameters tracked: // foo = 123 // bar = (missing) // method = excellent // remapped to route_method SetupHttpContext(_context, TestStatusCode, TestMethod, TestAction, TestController, new[] { ("foo", "123"), ("method", "excellent") }); var allLabelNames = HttpRequestLabelNames.All.Concat(new[] { "foo", "bar", "route_method" }).ToArray(); var middleware = new HttpRequestCountMiddleware(_next, new HttpRequestCountOptions { Counter = _metrics.CreateCounter("xxx", "", allLabelNames), AdditionalRouteParameters = { "foo", "bar", new HttpRouteParameterMapping("method", "route_method") } }); var child = (ChildBase)middleware.CreateChild(_context); CollectionAssert.AreEquivalent(allLabelNames, child.Labels.Names); CollectionAssert.AreEquivalent(new[] { TestStatusCode.ToString(), TestMethod, TestAction, TestController, "123", // foo "", // bar "excellent" // route_method }, child.Labels.Values); } [TestMethod] public void DefaultMetric_WithExtendedLabels_AppliesExtendedLabels() { // Route parameters tracked: // foo = 123 // bar = (missing) // method = excellent // remapped to route_method SetupHttpContext(_context, TestStatusCode, TestMethod, TestAction, TestController, new[] { ("foo", "123"), ("method", "excellent") }); var allLabelNames = HttpRequestLabelNames.All.Concat(new[] { "foo", "bar", "route_method" }).ToArray(); var middleware = new HttpRequestCountMiddleware(_next, new HttpRequestCountOptions { Registry = _registry, AdditionalRouteParameters = { "foo", "bar", new HttpRouteParameterMapping("method", "route_method") } }); var child = (ChildBase)middleware.CreateChild(_context); CollectionAssert.AreEquivalent(allLabelNames, child.Labels.Names); CollectionAssert.AreEquivalent(new[] { TestStatusCode.ToString(), TestMethod, TestAction, TestController, "123", // foo "", // bar "excellent" // route_method }, child.Labels.Values); } [TestMethod] public void CustomMetric_WithUnexpectedLabels_Throws() { Assert.ThrowsException<ArgumentException>(delegate { new HttpRequestCountMiddleware(_next, new HttpRequestCountOptions { Counter = Metrics.CreateCounter("xxx", "", "unknown_label_name") }); }); } [TestMethod] public void DefaultMetric_WithExtendedLabels_WithStandardParameterNameConflict_Throws() { Assert.ThrowsException<ArgumentException>(delegate { new HttpRequestCountMiddleware(_next, new HttpRequestCountOptions { Registry = _registry, AdditionalRouteParameters = { new HttpRouteParameterMapping("controller", "xxxxx") } }); }); } [TestMethod] public void DefaultMetric_WithExtendedLabels_WithStandardLabelNameConflict_Throws() { Assert.ThrowsException<ArgumentException>(delegate { new HttpRequestCountMiddleware(_next, new HttpRequestCountOptions { Registry = _registry, AdditionalRouteParameters = { new HttpRouteParameterMapping("xxxxx", "controller") } }); }); } [TestMethod] public void DefaultMetric_WithExtendedLabels_WithDuplicateParameterName_Throws() { Assert.ThrowsException<ArgumentException>(delegate { new HttpRequestCountMiddleware(_next, new HttpRequestCountOptions { Registry = _registry, AdditionalRouteParameters = { new HttpRouteParameterMapping("foo", "bar"), new HttpRouteParameterMapping("foo", "bang") } }); }); } [TestMethod] public void DefaultMetric_WithExtendedLabels_WithDuplicateLabelName_Throws() { Assert.ThrowsException<ArgumentException>(delegate { new HttpRequestCountMiddleware(_next, new HttpRequestCountOptions { Registry = _registry, AdditionalRouteParameters = { new HttpRouteParameterMapping("foo", "bar"), new HttpRouteParameterMapping("quux", "bar") } }); }); } private static void SetupHttpContext(DefaultHttpContext context, int statusCode, string httpMethod, string action, string controller, (string name, string value)[] routeParameters = null) { context.Response.StatusCode = statusCode; context.Request.Method = httpMethod; var routing = new FakeRoutingFeature { RouteData = new RouteData { Values = { { "Action", action }, { "Controller", controller } } } }; if (routeParameters != null) { foreach (var parameter in routeParameters) routing.RouteData.Values[parameter.name] = parameter.value; } context.Features[typeof(IRoutingFeature)] = routing; } internal class FakeRoutingFeature : IRoutingFeature { public RouteData RouteData { get; set; } } } }
35.879433
195
0.549516
[ "MIT" ]
3lvia/prometheus-net
Tests.NetCore/HttpExporter/RouteParameterMappingTests.cs
10,120
C#
using UnityEngine; using UnityEditor; using LineProperties = NicoplvTools.UiShapesKit.ShapeUtils.Lines.LineProperties; [CustomPropertyDrawer(typeof(LineProperties))] public class LinePropertiesDrawer : PropertyDrawer { public override void OnGUI (Rect position, SerializedProperty property, GUIContent label) { position.height = EditorGUIUtility.singleLineHeight; property.isExpanded = EditorGUI.Foldout(position, property.isExpanded, label); if (!property.isExpanded) return; EditorGUI.BeginProperty(position, label, property); LineProperties lineProperties = (LineProperties)fieldInfo.GetValue(property.serializedObject.targetObject); var indent = EditorGUI.indentLevel; EditorGUI.indentLevel++; Rect propertyPosition = new Rect (position.x, position.y + EditorGUIUtility.singleLineHeight, position.width, EditorGUIUtility.singleLineHeight); EditorGUI.PropertyField(propertyPosition, property.FindPropertyRelative("Closed"), new GUIContent("Closed")); propertyPosition.y += EditorGUIUtility.singleLineHeight * 1.25f; if (lineProperties.Closed) { EditorGUI.indentLevel--; return; } EditorGUI.PropertyField(propertyPosition, property.FindPropertyRelative("LineCap"), new GUIContent("Cap")); propertyPosition.y += EditorGUIUtility.singleLineHeight * 1.25f; switch (lineProperties.LineCap) { case LineProperties.LineCapTypes.Round: EditorGUI.PropertyField(propertyPosition, property.FindPropertyRelative("RoundedCapResolution"), new GUIContent("Resolution")); break; } EditorGUI.indentLevel = indent; EditorGUI.EndProperty (); } public override float GetPropertyHeight(SerializedProperty property, GUIContent label) { if (!property.isExpanded) { return EditorGUIUtility.singleLineHeight; } LineProperties lineProperties = (LineProperties)fieldInfo.GetValue(property.serializedObject.targetObject); if (lineProperties.Closed) { return EditorGUIUtility.singleLineHeight * 2.0f; } if (lineProperties.LineCap != LineProperties.LineCapTypes.Round) { return EditorGUIUtility.singleLineHeight * 3.25f; } return EditorGUIUtility.singleLineHeight * 6.5f; } }
29.351351
147
0.780847
[ "MIT" ]
nicoplv/ui-shapes-kit
Editor/CustomDrawers/LinePropertiesDrawer.cs
2,174
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Text; using JetBrains.Annotations; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Metadata.Internal; namespace Microsoft.EntityFrameworkCore.Update.Internal { /// <summary> /// This API supports the Entity Framework Core infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> public class SqlServerUpdateSqlGenerator : UpdateSqlGenerator, ISqlServerUpdateSqlGenerator { /// <summary> /// This API supports the Entity Framework Core infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> public SqlServerUpdateSqlGenerator( [NotNull] UpdateSqlGeneratorDependencies dependencies) : base(dependencies) { } /// <summary> /// This API supports the Entity Framework Core infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> public virtual ResultSetMapping AppendBulkInsertOperation( StringBuilder commandStringBuilder, IReadOnlyList<ModificationCommand> modificationCommands, int commandPosition) { if (modificationCommands.Count == 1 && modificationCommands[0].ColumnModifications.All( o => !o.IsKey || !o.IsRead || o.Property?.SqlServer().ValueGenerationStrategy == SqlServerValueGenerationStrategy.IdentityColumn)) { return AppendInsertOperation(commandStringBuilder, modificationCommands[0], commandPosition); } var readOperations = modificationCommands[0].ColumnModifications.Where(o => o.IsRead).ToList(); var writeOperations = modificationCommands[0].ColumnModifications.Where(o => o.IsWrite).ToList(); var keyOperations = modificationCommands[0].ColumnModifications.Where(o => o.IsKey).ToList(); var defaultValuesOnly = writeOperations.Count == 0; var nonIdentityOperations = modificationCommands[0].ColumnModifications .Where(o => o.Property?.SqlServer().ValueGenerationStrategy != SqlServerValueGenerationStrategy.IdentityColumn) .ToList(); if (defaultValuesOnly) { if (nonIdentityOperations.Count == 0 || readOperations.Count == 0) { foreach (var modification in modificationCommands) { AppendInsertOperation(commandStringBuilder, modification, commandPosition); } return readOperations.Count == 0 ? ResultSetMapping.NoResultSet : ResultSetMapping.LastInResultSet; } if (nonIdentityOperations.Count > 1) { nonIdentityOperations = new List<ColumnModification> { nonIdentityOperations.First() }; } } if (readOperations.Count == 0) { return AppendBulkInsertWithoutServerValues(commandStringBuilder, modificationCommands, writeOperations); } if (defaultValuesOnly) { return AppendBulkInsertWithServerValuesOnly(commandStringBuilder, modificationCommands, commandPosition, nonIdentityOperations, keyOperations, readOperations); } if (modificationCommands[0].Entries.SelectMany(e => e.EntityType.GetAllBaseTypesInclusive()) .Any(e => e.SqlServer().IsMemoryOptimized)) { if (!nonIdentityOperations.Any(o => o.IsRead && o.IsKey)) { foreach (var modification in modificationCommands) { AppendInsertOperation(commandStringBuilder, modification, commandPosition++); } } else { foreach (var modification in modificationCommands) { AppendInsertOperationWithServerKeys(commandStringBuilder, modification, keyOperations, readOperations, commandPosition++); } } return ResultSetMapping.LastInResultSet; } return AppendBulkInsertWithServerValues(commandStringBuilder, modificationCommands, commandPosition, writeOperations, keyOperations, readOperations); } private ResultSetMapping AppendBulkInsertWithoutServerValues( StringBuilder commandStringBuilder, IReadOnlyList<ModificationCommand> modificationCommands, List<ColumnModification> writeOperations) { Debug.Assert(writeOperations.Count > 0); var name = modificationCommands[0].TableName; var schema = modificationCommands[0].Schema; AppendInsertCommandHeader(commandStringBuilder, name, schema, writeOperations); AppendValuesHeader(commandStringBuilder, writeOperations); AppendValues(commandStringBuilder, writeOperations); for (var i = 1; i < modificationCommands.Count; i++) { commandStringBuilder.Append(",").AppendLine(); AppendValues(commandStringBuilder, modificationCommands[i].ColumnModifications.Where(o => o.IsWrite).ToList()); } commandStringBuilder.Append(SqlGenerationHelper.StatementTerminator).AppendLine(); return ResultSetMapping.NoResultSet; } private const string InsertedTableBaseName = "@inserted"; private const string ToInsertTableAlias = "i"; private const string PositionColumnName = "_Position"; private const string PositionColumnDeclaration = "[" + PositionColumnName + "] [int]"; private const string FullPositionColumnName = ToInsertTableAlias + "." + PositionColumnName; private ResultSetMapping AppendBulkInsertWithServerValues( StringBuilder commandStringBuilder, IReadOnlyList<ModificationCommand> modificationCommands, int commandPosition, List<ColumnModification> writeOperations, List<ColumnModification> keyOperations, List<ColumnModification> readOperations) { AppendDeclareTable( commandStringBuilder, InsertedTableBaseName, commandPosition, keyOperations, PositionColumnDeclaration); var name = modificationCommands[0].TableName; var schema = modificationCommands[0].Schema; AppendMergeCommandHeader( commandStringBuilder, name, schema, ToInsertTableAlias, modificationCommands, writeOperations, PositionColumnName); AppendOutputClause( commandStringBuilder, keyOperations, InsertedTableBaseName, commandPosition, FullPositionColumnName); commandStringBuilder.AppendLine(SqlGenerationHelper.StatementTerminator); AppendSelectCommand(commandStringBuilder, readOperations, keyOperations, InsertedTableBaseName, commandPosition, name, schema, orderColumn: PositionColumnName); return ResultSetMapping.NotLastInResultSet; } private ResultSetMapping AppendBulkInsertWithServerValuesOnly( StringBuilder commandStringBuilder, IReadOnlyList<ModificationCommand> modificationCommands, int commandPosition, List<ColumnModification> nonIdentityOperations, List<ColumnModification> keyOperations, List<ColumnModification> readOperations) { AppendDeclareTable(commandStringBuilder, InsertedTableBaseName, commandPosition, keyOperations); var name = modificationCommands[0].TableName; var schema = modificationCommands[0].Schema; AppendInsertCommandHeader(commandStringBuilder, name, schema, nonIdentityOperations); AppendOutputClause(commandStringBuilder, keyOperations, InsertedTableBaseName, commandPosition); AppendValuesHeader(commandStringBuilder, nonIdentityOperations); AppendValues(commandStringBuilder, nonIdentityOperations); for (var i = 1; i < modificationCommands.Count; i++) { commandStringBuilder.Append(",").AppendLine(); AppendValues(commandStringBuilder, nonIdentityOperations); } commandStringBuilder.Append(SqlGenerationHelper.StatementTerminator); AppendSelectCommand(commandStringBuilder, readOperations, keyOperations, InsertedTableBaseName, commandPosition, name, schema); return ResultSetMapping.NotLastInResultSet; } private void AppendMergeCommandHeader( [NotNull] StringBuilder commandStringBuilder, [NotNull] string name, [CanBeNull] string schema, [NotNull] string toInsertTableAlias, [NotNull] IReadOnlyList<ModificationCommand> modificationCommands, [NotNull] IReadOnlyList<ColumnModification> writeOperations, string additionalColumns = null) { commandStringBuilder.Append("MERGE "); SqlGenerationHelper.DelimitIdentifier(commandStringBuilder, name, schema); commandStringBuilder .Append(" USING ("); AppendValuesHeader(commandStringBuilder, writeOperations); AppendValues(commandStringBuilder, writeOperations, "0"); for (var i = 1; i < modificationCommands.Count; i++) { commandStringBuilder.Append(",").AppendLine(); AppendValues( commandStringBuilder, modificationCommands[i].ColumnModifications.Where(o => o.IsWrite).ToList(), i.ToString(CultureInfo.InvariantCulture)); } commandStringBuilder .Append(") AS ").Append(toInsertTableAlias) .Append(" (") .AppendJoin( writeOperations, SqlGenerationHelper, (sb, o, helper) => helper.DelimitIdentifier(sb, o.ColumnName)); if (additionalColumns != null) { commandStringBuilder .Append(", ") .Append(additionalColumns); } commandStringBuilder .Append(")") .AppendLine(" ON 1=0") .AppendLine("WHEN NOT MATCHED THEN"); commandStringBuilder .Append("INSERT ") .Append("(") .AppendJoin( writeOperations, SqlGenerationHelper, (sb, o, helper) => helper.DelimitIdentifier(sb, o.ColumnName)) .Append(")"); AppendValuesHeader(commandStringBuilder, writeOperations); commandStringBuilder .Append("(") .AppendJoin( writeOperations, toInsertTableAlias, SqlGenerationHelper, (sb, o, alias, helper) => { sb.Append(alias).Append("."); helper.DelimitIdentifier(sb, o.ColumnName); }) .Append(")"); } private void AppendValues( StringBuilder commandStringBuilder, IReadOnlyList<ColumnModification> operations, string additionalLiteral) { if (operations.Count > 0) { commandStringBuilder .Append("(") .AppendJoin( operations, SqlGenerationHelper, (sb, o, helper) => { if (o.IsWrite) { helper.GenerateParameterName(sb, o.ParameterName); } else { sb.Append("DEFAULT"); } }) .Append(", ") .Append(additionalLiteral) .Append(")"); } } private void AppendDeclareTable( StringBuilder commandStringBuilder, string name, int index, IReadOnlyList<ColumnModification> operations, string additionalColumns = null) { commandStringBuilder .Append("DECLARE ") .Append(name) .Append(index) .Append(" TABLE (") .AppendJoin( operations, this, (sb, o, generator) => { generator.SqlGenerationHelper.DelimitIdentifier(sb, o.ColumnName); sb.Append(" ").Append(generator.GetTypeNameForCopy(o.Property)); }); if (additionalColumns != null) { commandStringBuilder .Append(", ") .Append(additionalColumns); } commandStringBuilder .Append(")") .Append(SqlGenerationHelper.StatementTerminator) .AppendLine(); } private string GetTypeNameForCopy(IProperty property) { var typeName = property.SqlServer().ColumnType; if (typeName == null) { var principalProperty = property.FindPrincipal(); typeName = principalProperty?.SqlServer().ColumnType; if (typeName == null) { if (property.ClrType == typeof(string)) { typeName = Dependencies.RelationalTypeMapper.StringMapper?.FindMapping( property.IsUnicode() ?? principalProperty?.IsUnicode() ?? true, keyOrIndex: false, maxLength: null).StoreType; } else if (property.ClrType == typeof(byte[])) { typeName = Dependencies.RelationalTypeMapper.ByteArrayMapper?.FindMapping( rowVersion: false, keyOrIndex: false, size: null).StoreType; } else { typeName = Dependencies.RelationalTypeMapper.FindMapping(property.ClrType).StoreType; } } } if (property.ClrType == typeof(byte[]) && typeName != null && (typeName.Equals("rowversion", StringComparison.OrdinalIgnoreCase) || typeName.Equals("timestamp", StringComparison.OrdinalIgnoreCase))) { return property.IsNullable ? "varbinary(8)" : "binary(8)"; } return typeName; } // ReSharper disable once ParameterTypeCanBeEnumerable.Local private void AppendOutputClause( StringBuilder commandStringBuilder, IReadOnlyList<ColumnModification> operations, string tableName, int tableIndex, string additionalColumns = null) { commandStringBuilder .AppendLine() .Append("OUTPUT ") .AppendJoin( operations, SqlGenerationHelper, (sb, o, helper) => { sb.Append("INSERTED."); helper.DelimitIdentifier(sb, o.ColumnName); }); if (additionalColumns != null) { commandStringBuilder .Append(", ").Append(additionalColumns); } commandStringBuilder.AppendLine() .Append("INTO ").Append(tableName).Append(tableIndex); } private ResultSetMapping AppendInsertOperationWithServerKeys( StringBuilder commandStringBuilder, ModificationCommand command, IReadOnlyList<ColumnModification> keyOperations, IReadOnlyList<ColumnModification> readOperations, int commandPosition) { var name = command.TableName; var schema = command.Schema; var operations = command.ColumnModifications; var writeOperations = operations.Where(o => o.IsWrite).ToList(); AppendDeclareTable(commandStringBuilder, InsertedTableBaseName, commandPosition, keyOperations); AppendInsertCommandHeader(commandStringBuilder, name, schema, writeOperations); AppendOutputClause(commandStringBuilder, keyOperations, InsertedTableBaseName, commandPosition); AppendValuesHeader(commandStringBuilder, writeOperations); AppendValues(commandStringBuilder, writeOperations); commandStringBuilder.Append(SqlGenerationHelper.StatementTerminator); return AppendSelectCommand(commandStringBuilder, readOperations, keyOperations, InsertedTableBaseName, commandPosition, name, schema); } private ResultSetMapping AppendSelectCommand( StringBuilder commandStringBuilder, IReadOnlyList<ColumnModification> readOperations, IReadOnlyList<ColumnModification> keyOperations, string insertedTableName, int insertedTableIndex, string tableName, string schema, string orderColumn = null) { commandStringBuilder .AppendLine() .Append("SELECT ") .AppendJoin( readOperations, SqlGenerationHelper, (sb, o, helper) => helper.DelimitIdentifier(sb, o.ColumnName, "t")) .Append(" FROM "); SqlGenerationHelper.DelimitIdentifier(commandStringBuilder, tableName, schema); commandStringBuilder .Append(" t") .AppendLine() .Append("INNER JOIN ") .Append(insertedTableName).Append(insertedTableIndex) .Append(" i") .Append(" ON ") .AppendJoin( keyOperations, (sb, c) => { sb.Append("("); SqlGenerationHelper.DelimitIdentifier(sb, c.ColumnName, "t"); sb.Append(" = "); SqlGenerationHelper.DelimitIdentifier(sb, c.ColumnName, "i"); sb.Append(")"); }, " AND "); if (orderColumn != null) { commandStringBuilder .AppendLine() .Append("ORDER BY "); SqlGenerationHelper.DelimitIdentifier(commandStringBuilder, orderColumn, "i"); } commandStringBuilder .Append(SqlGenerationHelper.StatementTerminator).AppendLine() .AppendLine(); return ResultSetMapping.LastInResultSet; } /// <summary> /// This API supports the Entity Framework Core infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> protected override ResultSetMapping AppendSelectAffectedCountCommand(StringBuilder commandStringBuilder, string name, string schema, int commandPosition) { commandStringBuilder .Append("SELECT @@ROWCOUNT") .Append(SqlGenerationHelper.StatementTerminator).AppendLine() .AppendLine(); return ResultSetMapping.LastInResultSet; } /// <summary> /// This API supports the Entity Framework Core infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> public override void AppendBatchHeader(StringBuilder commandStringBuilder) => commandStringBuilder .Append("SET NOCOUNT ON") .Append(SqlGenerationHelper.StatementTerminator).AppendLine(); /// <summary> /// This API supports the Entity Framework Core infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> protected override void AppendIdentityWhereCondition(StringBuilder commandStringBuilder, ColumnModification columnModification) { SqlGenerationHelper.DelimitIdentifier(commandStringBuilder, columnModification.ColumnName); commandStringBuilder.Append(" = "); commandStringBuilder.Append("scope_identity()"); } /// <summary> /// This API supports the Entity Framework Core infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> protected override void AppendRowsAffectedWhereCondition(StringBuilder commandStringBuilder, int expectedRowsAffected) => commandStringBuilder .Append("@@ROWCOUNT = ") .Append(expectedRowsAffected.ToString(CultureInfo.InvariantCulture)); } }
42.863039
175
0.567583
[ "Apache-2.0" ]
tonysneed/Forks.EntityFrameworkCore
src/EFCore.SqlServer/Update/Internal/SqlServerUpdateSqlGenerator.cs
22,846
C#
using System; using System.Collections.Generic; using System.Text; namespace GetOffers { class Offer { public DateTime Date { get { return mDate; } set { mDate = value; } } private DateTime mDate; public double Bid { get { return mBid; } set { mBid = value; } } private double mBid; public double Ask { get { return mAsk; } set { mAsk = value; } } private double mAsk; public string OfferID { get { return mOfferID; } set { mOfferID = value; } } private string mOfferID; public string Instrument { get { return mInstrument; } set { mInstrument = value; } } private string mInstrument; public int Precision { get { return mPrecision; } set { mPrecision = value; } } private int mPrecision; public double PipSize { get { return mPipSize; } set { mPipSize = value; } } private double mPipSize; /// <summary> /// ctor /// </summary> /// <param name="sOfferID"></param> /// <param name="sInstrument"></param> /// <param name="iPrecision"></param> /// <param name="dPipSize"></param> /// <param name="date"></param> /// <param name="dBid"></param> /// <param name="dAsk"></param> public Offer(string sOfferID, string sInstrument, int iPrecision, double dPipSize, DateTime date, double dBid, double dAsk) { mOfferID = sOfferID; mInstrument = sInstrument; mPrecision = iPrecision; mPipSize = dPipSize; mDate = date; mBid = dBid; mAsk = dAsk; } } class OfferCollection : IEnumerable<Offer> { private List<Offer> mOffers; private Dictionary<string, Offer> mIDsAndOffers; private Object mSyncObj; /// <summary> /// ctor /// </summary> public OfferCollection() { mOffers = new List<Offer>(); mIDsAndOffers = new Dictionary<string,Offer>(); mSyncObj = new Object(); } /* Add offer to collection */ public void AddOffer(Offer offer) { lock (mSyncObj) { mIDsAndOffers[offer.OfferID] = offer; mOffers.Clear(); mOffers.AddRange(mIDsAndOffers.Values); } } /* Find offer by id */ public bool FindOffer(string sOfferID, out Offer offer) { bool result = false; lock (mSyncObj) { offer = null; if (mIDsAndOffers.ContainsKey(sOfferID)) { offer = mIDsAndOffers[sOfferID]; result = true; } } return result; } /* Get offer by index */ public Offer GetOffer(int index) { Offer offer = null; lock (mSyncObj) { if (index >= 0 && index < mOffers.Count) offer = mOffers[index]; } return offer; } /* Get number of offers */ public int Size() { int size = 0; lock (mSyncObj) { size = mOffers.Count; } return size; } /* Clear collection */ public void Clear() { lock (mSyncObj) { mOffers.Clear(); mIDsAndOffers.Clear(); } } #region IEnumerable<Offer> Members public IEnumerator<Offer> GetEnumerator() { return mOffers.GetEnumerator(); } #endregion #region IEnumerable Members System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return mOffers.GetEnumerator(); } #endregion } }
23.193548
132
0.39241
[ "Apache-2.0" ]
holgafx/gehtsoft
samples/Linux/netcore_for_Linux_x64_only/netcore1.0/NonTableManagerSamples/GetOffers/src/Offer.cs
5,035
C#
namespace Nancy.Demo.Dropbox { using DropNet; using System.IO; using System.Linq; public class DropboxModule : NancyModule { public DropboxModule(IDropNetClient dropNetClient) { Get["/files"] = _ => { this.RequiresDropboxAuthentication(dropNetClient); var metaData = dropNetClient.GetMetaData(list: true); return Response.AsJson(metaData.Contents .Select(f => new { Name = f.Name, Modified = f.Modified, Type = f.Is_Dir ? "Folder": "File" })); }; Post["/files"] = _ => { var file = Request.Files.FirstOrDefault(); if (file != null) { var uploaded = dropNetClient.UploadFile("/", file.Name, ReadFile(file.Value)); return uploaded != null ? HttpStatusCode.OK : HttpStatusCode.InternalServerError; } else { return HttpStatusCode.BadRequest; } }; Get["/login"] = _ => { dropNetClient.GetToken(); var url = dropNetClient.BuildAuthorizeUrl(); return Response.AsRedirect(url, Responses.RedirectResponse.RedirectType.Permanent); }; } public static byte[] ReadFile(Stream file) { using (MemoryStream ms = new MemoryStream()) { file.CopyTo(ms); return ms.ToArray(); } } } }
29.280702
101
0.469742
[ "MIT" ]
fagnercarvalho/Nancy.Demo.Dropbox
Nancy.Demo.Dropbox/DropboxModule.cs
1,671
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 StatsDownload.Logging { 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", "15.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class ErrorMessages { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal ErrorMessages() { } /// <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("StatsDownload.Logging.ErrorMessages", typeof(ErrorMessages).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; } } /// <summary> /// Looks up a localized string similar to There was a problem with the user&apos;s data. The user &apos;{0}&apos; has a bitcoin address length of &apos;{1}&apos; and exceeded the max bitcoin address length. The user should shorten their bitcoin address. You should contact your technical advisor to review the logs and rejected users.. /// </summary> internal static string BitcoinAddressExceedsMaxSize { get { return ResourceManager.GetString("BitcoinAddressExceedsMaxSize", resourceCulture); } } /// <summary> /// Looks up a localized string similar to There was a problem downloading the file payload. There was a problem connecting to the data store. The data store is unavailable, ensure the data store is available and configured correctly and try again.. /// </summary> internal static string DataStoreUnavailable { get { return ResourceManager.GetString("DataStoreUnavailable", resourceCulture); } } /// <summary> /// Looks up a localized string similar to There was a problem connecting to the database. The database is unavailable, ensure the database is available and configured correctly and try again.. /// </summary> internal static string DefaultDatabaseUnavailable { get { return ResourceManager.GetString("DefaultDatabaseUnavailable", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The database is missing required objects. Add the missing database objects and try again. You should contact your technical advisor to review the logs.. /// </summary> internal static string DefaultMissingRequiredObjects { get { return ResourceManager.GetString("DefaultMissingRequiredObjects", resourceCulture); } } /// <summary> /// Looks up a localized string similar to There was an unexpected exception. Check the log for more information.. /// </summary> internal static string DefaultUnexpectedException { get { return ResourceManager.GetString("DefaultUnexpectedException", resourceCulture); } } /// <summary> /// Looks up a localized string similar to There was a problem with the user&apos;s data. The user &apos;{0}&apos; has a FAH name length of &apos;{1}&apos; and exceeded the max FAH name length. The user should shorten their FAH name. You should contact your technical advisor to review the logs and rejected users.. /// </summary> internal static string FahNameExceedsMaxSize { get { return ResourceManager.GetString("FahNameExceedsMaxSize", resourceCulture); } } /// <summary> /// Looks up a localized string similar to There was a problem adding the user &apos;{0}&apos; to the database. Contact your technical advisor to review the logs and rejected users.. /// </summary> internal static string FailedAddUserToDatabase { get { return ResourceManager.GetString("FailedAddUserToDatabase", resourceCulture); } } /// <summary> /// Looks up a localized string similar to There was a problem parsing a user from the stats file. The user &apos;{0}&apos; failed data parsing. You should contact your technical advisor to review the logs and rejected users.. /// </summary> internal static string FailedParsingUserData { get { return ResourceManager.GetString("FailedParsingUserData", resourceCulture); } } /// <summary> /// Looks up a localized string similar to There was a problem uploading the file payload. The file passed validation but {0} lines failed; processing continued after encountering these lines. If this problem occurs again, then you should contact your technical advisor to review the logs and failed users.. /// </summary> internal static string FailedUserDataCount { get { return ResourceManager.GetString("FailedUserDataCount", resourceCulture); } } /// <summary> /// Looks up a localized string similar to There was a problem downloading the file payload. There was a problem connecting to the database. The database is unavailable, ensure the database is available and configured correctly and try again.. /// </summary> internal static string FileDownloadDatabaseUnavailable { get { return ResourceManager.GetString("FileDownloadDatabaseUnavailable", resourceCulture); } } /// <summary> /// Looks up a localized string similar to There was a problem decompressing the file payload. The file has been moved to a failed directory for review. If this problem occurs again, then you should contact your technical advisor to review the logs and failed files.. /// </summary> internal static string FileDownloadFailedDecompression { get { return ResourceManager.GetString("FileDownloadFailedDecompression", resourceCulture); } } /// <summary> /// Looks up a localized string similar to There was a problem downloading the file payload. The database is missing required objects. Add the missing database objects and try again. You should contact your technical advisor to review the logs.. /// </summary> internal static string FileDownloadMissingRequiredObjects { get { return ResourceManager.GetString("FileDownloadMissingRequiredObjects", resourceCulture); } } /// <summary> /// Looks up a localized string similar to There was a problem downloading the file payload. The file payload could not be found. Check the download URI configuration and try again. If this problem occurs again, then you should contact your technical advisor to review the logs.. /// </summary> internal static string FileDownloadNotFound { get { return ResourceManager.GetString("FileDownloadNotFound", resourceCulture); } } /// <summary> /// Looks up a localized string similar to There was a problem downloading the file payload. There was a timeout when downloading the file payload. If a timeout occurs again, then you can try increasing the configurable download timeout.. /// </summary> internal static string FileDownloadTimedOut { get { return ResourceManager.GetString("FileDownloadTimedOut", resourceCulture); } } /// <summary> /// Looks up a localized string similar to There was a problem downloading the file payload. There was an unexpected exception. Check the log for more information.. /// </summary> internal static string FileDownloadUnexpectedException { get { return ResourceManager.GetString("FileDownloadUnexpectedException", resourceCulture); } } /// <summary> /// Looks up a localized string similar to There was a problem with the user&apos;s data. The user &apos;{0}&apos; has a friendly name length of &apos;{1}&apos; and exceeded the max friendly name length. The user should shorten their friendly name. You should contact your technical advisor to review the logs and rejected users.. /// </summary> internal static string FriendlyNameExceedsMaxSize { get { return ResourceManager.GetString("FriendlyNameExceedsMaxSize", resourceCulture); } } /// <summary> /// Looks up a localized string similar to There was a problem uploading the file payload. The file failed validation; check the logs for more information. If this problem occurs again, then you should contact your technical advisor to review the logs and failed uploads.. /// </summary> internal static string InvalidStatsFile { get { return ResourceManager.GetString("InvalidStatsFile", resourceCulture); } } /// <summary> /// Looks up a localized string similar to There was a problem downloading the file payload. The file download service was run before the minimum wait time {0} or the configured wait time {1}. Configure to run the service less often or decrease your configured wait time and try again.. /// </summary> internal static string MinimumWaitTimeNotMet { get { return ResourceManager.GetString("MinimumWaitTimeNotMet", resourceCulture); } } /// <summary> /// Looks up a localized string similar to There was a problem downloading the file payload. The required settings are invalid; check the logs for more information. Ensure the settings are complete and accurate, then try again.. /// </summary> internal static string RequiredSettingsAreInvalid { get { return ResourceManager.GetString("RequiredSettingsAreInvalid", resourceCulture); } } /// <summary> /// Looks up a localized string similar to There was a problem uploading the file payload. There was a problem connecting to the database. The database is unavailable, ensure the database is available and configured correctly and try again.. /// </summary> internal static string StatsUploadDatabaseUnavailable { get { return ResourceManager.GetString("StatsUploadDatabaseUnavailable", resourceCulture); } } /// <summary> /// Looks up a localized string similar to There was a problem uploading the file payload. The database is missing required objects. Add the missing database objects and try again. You should contact your technical advisor to review the logs.. /// </summary> internal static string StatsUploadMissingRequiredObjects { get { return ResourceManager.GetString("StatsUploadMissingRequiredObjects", resourceCulture); } } /// <summary> /// Looks up a localized string similar to There was a problem uploading the file payload. There was an unexpected database exception and the file has been marked rejected. If this problem occurs again, then you should contact your technical advisor to review the rejections and logs.. /// </summary> internal static string StatsUploadTimeout { get { return ResourceManager.GetString("StatsUploadTimeout", resourceCulture); } } /// <summary> /// Looks up a localized string similar to There was a problem uploading the file payload. There was an unexpected exception. Check the log for more information.. /// </summary> internal static string StatsUploadUnexpectedException { get { return ResourceManager.GetString("StatsUploadUnexpectedException", resourceCulture); } } /// <summary> /// Looks up a localized string similar to There was a problem validating the file. There was an unexpected exception while validating. Check the log for more information.. /// </summary> internal static string UnexpectedValidationException { get { return ResourceManager.GetString("UnexpectedValidationException", resourceCulture); } } /// <summary> /// Looks up a localized string similar to There was a problem parsing a user from the stats file. The user &apos;{0}&apos; was in an unexpected format. You should contact your technical advisor to review the logs and rejected users.. /// </summary> internal static string UserDataUnexpectedFormat { get { return ResourceManager.GetString("UserDataUnexpectedFormat", resourceCulture); } } } }
53.190311
346
0.638889
[ "MIT" ]
FoldingCoin/FLDCDotNet
Shared/StatsDownload.Logging/ErrorMessages.Designer.cs
15,374
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Threading.Tasks; using Microsoft.Extensions.EnvironmentAbstractions; namespace Microsoft.Extensions.DependencyModel { public class DependencyContextLoader { private static Lazy<string[]> _depsFiles = new Lazy<string[]>(GetHostDepsList); private const string DepsJsonExtension = ".deps.json"; private readonly string _entryPointDepsLocation; private readonly string _runtimeDepsLocation; private readonly IFileSystem _fileSystem; private readonly IDependencyContextReader _jsonReader; public DependencyContextLoader() : this( GetDefaultEntrypointDepsLocation(), GetDefaultRuntimeDepsLocation(), FileSystemWrapper.Default, new DependencyContextJsonReader()) { } internal DependencyContextLoader( string entryPointDepsLocation, string runtimeDepsLocation, IFileSystem fileSystem, IDependencyContextReader jsonReader) { _entryPointDepsLocation = entryPointDepsLocation; _runtimeDepsLocation = runtimeDepsLocation; _fileSystem = fileSystem; _jsonReader = jsonReader; } public static DependencyContextLoader Default { get; } = new DependencyContextLoader(); internal virtual bool IsEntryAssembly(Assembly assembly) { return assembly.GetName() == Assembly.GetEntryAssembly()?.GetName(); } internal virtual Stream GetResourceStream(Assembly assembly, string name) { return assembly.GetManifestResourceStream(name); } public DependencyContext Load(Assembly assembly) { if (assembly == null) { throw new ArgumentNullException(nameof(assembly)); } DependencyContext context = null; if (IsEntryAssembly(assembly)) { context = LoadEntryAssemblyContext(); } if (context == null) { context = LoadAssemblyContext(assembly); } if (context?.Target.IsPortable == true) { var runtimeContext = LoadRuntimeContext(); if (runtimeContext != null) { context = context.Merge(runtimeContext); } } return context; } private DependencyContext LoadEntryAssemblyContext() { if (!string.IsNullOrEmpty(_entryPointDepsLocation)) { Debug.Assert(File.Exists(_entryPointDepsLocation)); using (var stream = _fileSystem.File.OpenRead(_entryPointDepsLocation)) { return _jsonReader.Read(stream); } } return null; } private DependencyContext LoadRuntimeContext() { if (!string.IsNullOrEmpty(_runtimeDepsLocation)) { Debug.Assert(File.Exists(_runtimeDepsLocation)); using (var stream = _fileSystem.File.OpenRead(_runtimeDepsLocation)) { return _jsonReader.Read(stream); } } return null; } private DependencyContext LoadAssemblyContext(Assembly assembly) { using (var stream = GetResourceStream(assembly, assembly.GetName().Name + DepsJsonExtension)) { if (stream != null) { return _jsonReader.Read(stream); } } var depsJsonFile = Path.ChangeExtension(assembly.Location, DepsJsonExtension); if (_fileSystem.File.Exists(depsJsonFile)) { using (var stream = _fileSystem.File.OpenRead(depsJsonFile)) { return _jsonReader.Read(stream); } } return null; } private static string GetDefaultRuntimeDepsLocation() { var deps = _depsFiles.Value; if (deps != null && deps.Length > 1) { return deps[1]; } return null; } private static string GetDefaultEntrypointDepsLocation() { var deps = _depsFiles.Value; if (deps != null && deps.Length > 0) { return deps[0]; } return null; } private static string[] GetHostDepsList() { // TODO: We're going to replace this with AppContext.GetData var appDomainType = typeof(object).GetTypeInfo().Assembly?.GetType("System.AppDomain"); var currentDomain = appDomainType?.GetProperty("CurrentDomain")?.GetValue(null); var deps = appDomainType?.GetMethod("GetData")?.Invoke(currentDomain, new[] { "APP_CONTEXT_DEPS_FILES" }); return (deps as string)?.Split(new [] { ';' }, StringSplitOptions.RemoveEmptyEntries); } } }
31.993939
118
0.565637
[ "MIT" ]
gkhanna79/cli
src/Microsoft.Extensions.DependencyModel/DependencyContextLoader.cs
5,281
C#
using Newtonsoft.Json; using Newtonsoft.Json.Linq; using RPGCore.Demo.Nodes; using RPGCore.Behaviour; using RPGCore.Behaviour.Editor; using RPGCore.Behaviour.Manifest; using RPGCore.Packages; using System; using System.Collections.Generic; using System.IO; using UnityEditor; using UnityEngine; namespace RPGCore.Unity.Editors { public class BehaviourEditor : EditorWindow { public BehaviourEditorView View; private ProjectImport CurrentPackage; private ProjectResource CurrentResource; private Rect ScreenRect; private Event CurrentEvent; private readonly JsonSerializer Serializer = JsonSerializer.Create (new JsonSerializerSettings () { Converters = new List<JsonConverter> () { new LocalPropertyIdJsonConverter() } }); [MenuItem ("Window/Behaviour")] public static void Open () { var window = GetWindow<BehaviourEditor> (); window.Show (); } private void OnEnable () { if (EditorGUIUtility.isProSkin) { titleContent = new GUIContent ("Behaviour", BehaviourGraphResources.Instance.DarkThemeIcon); } else { titleContent = new GUIContent ("Behaviour", BehaviourGraphResources.Instance.LightThemeIcon); } } private void OnGUI () { if (View == null) { View = new BehaviourEditorView (); } ScreenRect = new Rect (0, EditorGUIUtility.singleLineHeight + 1, position.width, position.height - (EditorGUIUtility.singleLineHeight + 1)); CurrentEvent = Event.current; DrawBackground (ScreenRect, View.PanPosition); DrawTopBar (); DrawAssetSelection (); DrawNodes (); DrawConnections (); HandleInput (); } private void DrawAssetSelection () { CurrentPackage = (ProjectImport)EditorGUILayout.ObjectField (CurrentPackage, typeof (ProjectImport), true); if (CurrentPackage != null) { var explorer = CurrentPackage.Explorer; foreach (var resource in explorer.Resources) { if (!resource.Name.EndsWith (".bhvr")) { continue; } if (GUILayout.Button (resource.ToString ())) { CurrentResource = resource; JObject editorTarget; using (var editorTargetData = CurrentResource.LoadStream ()) using (var sr = new StreamReader (editorTargetData)) using (var reader = new JsonTextReader (sr)) { editorTarget = JObject.Load (reader); } var nodes = NodeManifest.Construct (new Type[] { typeof (AddNode), typeof (RollNode), typeof (OutputValueNode) }); var types = TypeManifest.ConstructBaseTypes (); var manifest = new BehaviourManifest () { Nodes = nodes, Types = types, }; Debug.Log (editorTarget); var graphEditor = new EditorSession (manifest, editorTarget, "SerializedGraph", Serializer); View.BeginSession (graphEditor); } } } } private void DrawNodes () { if (View.Session != null) { var graphEditorNodes = View.Session.Root["Nodes"]; // Draw Nodes foreach (var node in graphEditorNodes) { var nodeEditor = node["Editor"]; var nodeEditorPosition = nodeEditor["Position"]; var nodeRect = new Rect ( View.PanPosition.x + nodeEditorPosition["x"].GetValue<int> (), View.PanPosition.y + nodeEditorPosition["y"].GetValue<int> (), 200, 180 ); if (CurrentEvent.type == EventType.Repaint) { GUI.skin.window.Draw (nodeRect, false, View.Selection.Contains (node.Name), false, false); } GUILayout.BeginArea (nodeRect); var nodeType = node["Type"]; EditorGUILayout.LabelField (nodeType.GetValue<string> ()); var nodeData = node["Data"]; foreach (var childField in nodeData) { DrawField (childField); } GUILayout.EndArea (); if (CurrentEvent.type == EventType.MouseDown) { if (nodeRect.Contains (CurrentEvent.mousePosition)) { View.Selection.Clear (); View.Selection.Add (node.Name); View.CurrentMode = BehaviourEditorView.Mode.NodeDragging; GUI.UnfocusWindow (); GUI.FocusControl (""); CurrentEvent.Use (); } } } } } public void DrawConnections () { if (View.Session != null) { var graphEditorNodes = View.Session.Root["Nodes"]; // Foreach output foreach (var node in graphEditorNodes) { var nodeEditor = node["Editor"]; var nodeEditorPosition = nodeEditor["Position"]; float nodePositionX = nodeEditorPosition["x"].GetValue<int> () + View.PanPosition.x; float nodePositionY = nodeEditorPosition["y"].GetValue<int> () + View.PanPosition.y; var nodeData = node["Data"]; // Foreach Output var outputRect = new Rect (nodePositionX + 202, nodePositionY + 6, 20, 20); var nodeInfo = (NodeInformation)nodeData.Type; foreach (var output in nodeInfo.Outputs) { if (CurrentEvent.type == EventType.Repaint) { EditorStyles.helpBox.Draw (outputRect, false, false, false, false); } else if (CurrentEvent.type == EventType.MouseDown && outputRect.Contains (CurrentEvent.mousePosition)) { var outputId = new LocalPropertyId (new LocalId (node.Name), output.Key); View.BeginConnectionFromOutput (outputId); GUI.UnfocusWindow (); GUI.FocusControl (""); CurrentEvent.Use (); } else if (CurrentEvent.type == EventType.MouseUp && outputRect.Contains (CurrentEvent.mousePosition)) { if (View.CurrentMode == BehaviourEditorView.Mode.CreatingConnection) { if (!View.IsOutputSocket) { var thisOutputSocket = new LocalPropertyId (new LocalId (node.Name), output.Key); View.ConnectionInput.SetValue (thisOutputSocket); View.ConnectionInput.ApplyModifiedProperties (); View.CurrentMode = BehaviourEditorView.Mode.None; GUI.UnfocusWindow (); GUI.FocusControl (""); CurrentEvent.Use (); } } } outputRect.y += outputRect.height + 4; } // Foreach Input foreach (var childField in nodeData) { if (childField.Field.Type == "InputSocket") { var fieldFeature = childField.GetOrCreateFeature<FieldFeature> (); fieldFeature.GlobalRenderedPosition = new Rect ( fieldFeature.LocalRenderedPosition.x + nodePositionX, fieldFeature.LocalRenderedPosition.y + nodePositionY, fieldFeature.LocalRenderedPosition.width, fieldFeature.LocalRenderedPosition.height); var socketRect = fieldFeature.InputSocketPosition; if (CurrentEvent.type == EventType.Repaint) { EditorStyles.helpBox.Draw (socketRect, false, false, false, false); } else if (CurrentEvent.type == EventType.MouseDown && socketRect.Contains (CurrentEvent.mousePosition)) { var thisInputId = new LocalPropertyId (new LocalId (node.Name), childField.Name); View.BeginConnectionFromInput (childField, node.Name); GUI.UnfocusWindow (); GUI.FocusControl (""); CurrentEvent.Use (); } else if (CurrentEvent.type == EventType.MouseUp && socketRect.Contains (CurrentEvent.mousePosition)) { if (View.CurrentMode == BehaviourEditorView.Mode.CreatingConnection) { if (View.IsOutputSocket) { childField.SetValue (View.ConnectionOutput); childField.ApplyModifiedProperties (); View.CurrentMode = BehaviourEditorView.Mode.None; GUI.UnfocusWindow (); GUI.FocusControl (""); CurrentEvent.Use (); } } } var thisInputConnectedTo = childField.GetValue<LocalPropertyId> (); if (thisInputConnectedTo != LocalPropertyId.None) { bool foundNode = false; var otherOutputRect = new Rect (); foreach (var otherNode in graphEditorNodes) { var otherNodeEditor = otherNode["Editor"]; var otherNodeEditorPosition = otherNodeEditor["Position"]; float otherNodePositionX = otherNodeEditorPosition["x"].GetValue<int> () + View.PanPosition.x; float otherNodePositionY = otherNodeEditorPosition["y"].GetValue<int> () + View.PanPosition.y; var otherNodeData = otherNode["Data"]; // Foreach Output otherOutputRect = new Rect (otherNodePositionX + 202, otherNodePositionY + 6, 20, 20); var otherNodeInfo = (NodeInformation)otherNodeData.Type; foreach (var output in otherNodeInfo.Outputs) { var otherOutputId = new LocalPropertyId (new LocalId (otherNode.Name), output.Key); if (otherOutputId == thisInputConnectedTo) { foundNode = true; break; } otherOutputRect.y += otherOutputRect.height + 4; } if (foundNode) { break; } } if (foundNode) { var start = new Vector3 (otherOutputRect.x, otherOutputRect.center.y); var end = new Vector3 (fieldFeature.GlobalRenderedPosition.x, fieldFeature.GlobalRenderedPosition.center.y); var startDir = new Vector3 (1, 0); var endDir = new Vector3 (-1, 0); DrawConnection (start, end, startDir, endDir); } } } } } // Draw active connection if (View.CurrentMode == BehaviourEditorView.Mode.CreatingConnection) { if (View.IsOutputSocket) { // Draw Nodes bool isFound = false; var outputRect = new Rect (); foreach (var node in graphEditorNodes) { var nodeEditor = node["Editor"]; var nodeEditorPosition = nodeEditor["Position"]; float nodePositionX = nodeEditorPosition["x"].GetValue<int> () + View.PanPosition.x; float nodePositionY = nodeEditorPosition["y"].GetValue<int> () + View.PanPosition.y; var nodeData = node["Data"]; // Foreach Output var nodeInfo = (NodeInformation)nodeData.Type; outputRect = new Rect (nodePositionX + 202, nodePositionY + 6, 20, 20); foreach (var output in nodeInfo.Outputs) { var otherOutputId = new LocalPropertyId (new LocalId (node.Name), output.Key); if (otherOutputId == View.ConnectionOutput) { isFound = true; break; } outputRect.y += outputRect.height + 4; } if (isFound) { break; } } if (isFound) { var start = new Vector3 (outputRect.x, outputRect.center.y); var end = new Vector3 (CurrentEvent.mousePosition.x, CurrentEvent.mousePosition.y); var startDir = new Vector3 (1, 0); var endDir = new Vector3 (-1, 0); DrawConnection (start, end, startDir, endDir); } } else { var startFieldFeature = View.ConnectionInput.GetOrCreateFeature<FieldFeature> (); var inputNode = graphEditorNodes[View.ConnectionInputNodeId.ToString ()]; var nodeEditor = inputNode["Editor"]; var nodeEditorPosition = nodeEditor["Position"]; float nodePositionX = nodeEditorPosition["x"].GetValue<int> () + View.PanPosition.x; float nodePositionY = nodeEditorPosition["y"].GetValue<int> () + View.PanPosition.y; var nodeData = inputNode["Data"]; var socketRect = startFieldFeature.InputSocketPosition; var start = new Vector3 (CurrentEvent.mousePosition.x, CurrentEvent.mousePosition.y); var end = new Vector3 (socketRect.xMax, socketRect.center.y); var startDir = new Vector3 (1, 0); var endDir = new Vector3 (-1, 0); DrawConnection (start, end, startDir, endDir); } } } } public static void DrawEditor (EditorSession editor) { foreach (var field in editor.Root) { DrawField (field); } } public static void DrawField (EditorField field) { // EditorGUILayout.LabelField(field.Json.Path); if (field.Field.Format == FieldFormat.List) { var fieldFeature = field.GetOrCreateFeature<FieldFeature> (); fieldFeature.Expanded = EditorGUILayout.Foldout (fieldFeature.Expanded, field.Name, true); if (fieldFeature.Expanded) { EditorGUI.indentLevel++; EditorGUI.BeginChangeCheck (); int newIndex = EditorGUILayout.DelayedIntField ("Size", field.Count); if (EditorGUI.EndChangeCheck ()) { } foreach (var childField in field) { DrawField (childField); } EditorGUI.indentLevel--; } } else if (field.Field.Type == "Int32") { EditorGUI.BeginChangeCheck (); int newValue = EditorGUILayout.IntField (field.Name, field.GetValue<int> ()); if (EditorGUI.EndChangeCheck ()) { field.SetValue (newValue); field.ApplyModifiedProperties (); } } else if (field.Field.Type == "String") { EditorGUI.BeginChangeCheck (); string newValue = EditorGUILayout.TextField (field.Name, field.GetValue<string> ()); if (EditorGUI.EndChangeCheck ()) { field.SetValue (newValue); field.ApplyModifiedProperties (); } } else if (field.Field.Type == "Boolean") { EditorGUI.BeginChangeCheck (); bool newValue = EditorGUILayout.Toggle (field.Name, field.GetValue<bool> ()); if (EditorGUI.EndChangeCheck ()) { field.SetValue (newValue); field.ApplyModifiedProperties (); } } else if (field.Field.Type == "InputSocket") { var fieldFeature = field.GetOrCreateFeature<FieldFeature> (); EditorGUI.BeginChangeCheck (); EditorGUILayout.LabelField (field.Name, field.GetValue<LocalPropertyId> ().ToString ()); var renderPos = GUILayoutUtility.GetLastRect (); fieldFeature.LocalRenderedPosition = renderPos; if (EditorGUI.EndChangeCheck ()) { //field.Json.Value = newValue; } // EditorGUI.DrawRect(renderPos, Color.red); } else if (field.Field.Format == FieldFormat.Dictionary) { EditorGUILayout.LabelField (field.Name); EditorGUI.indentLevel++; foreach (var childField in field) { DrawField (childField); } EditorGUI.indentLevel--; } else if (field.Field.Format == FieldFormat.Object) { var fieldFeature = field.GetOrCreateFeature<FieldFeature> (); fieldFeature.Expanded = EditorGUILayout.Foldout (fieldFeature.Expanded, field.Name, true); if (fieldFeature.Expanded) { EditorGUI.indentLevel++; foreach (var childField in field) { DrawField (childField); } EditorGUI.indentLevel--; } } else { EditorGUILayout.LabelField (field.Name, "Unknown Type"); } } private static void DrawConnection (Vector3 start, Vector3 end, Vector3 startDir, Vector3 endDir) { float distance = Vector3.Distance (start, end); var startTan = start + (startDir * distance * 0.5f); var endTan = end + (endDir * distance * 0.5f); var connectionColour = new Color (1.0f, 0.8f, 0.8f); Handles.DrawBezier (start, end, startTan, endTan, connectionColour, BehaviourGraphResources.Instance.SmallConnection, 10); } private void HandleInput () { if (CurrentEvent.type == EventType.MouseUp) { switch (View.CurrentMode) { case BehaviourEditorView.Mode.NodeDragging: CurrentEvent.Use (); foreach (string selectedNode in View.Selection) { var pos = View.Session.Root["Nodes"][selectedNode]["Editor"]["Position"]; var posX = pos["x"]; posX.ApplyModifiedProperties (); var posY = pos["y"]; posY.ApplyModifiedProperties (); } View.CurrentMode = BehaviourEditorView.Mode.None; break; case BehaviourEditorView.Mode.ViewDragging: View.CurrentMode = BehaviourEditorView.Mode.None; break; case BehaviourEditorView.Mode.CreatingConnection: View.CurrentMode = BehaviourEditorView.Mode.None; break; } Repaint (); } else if (CurrentEvent.type == EventType.KeyDown) { } else if (CurrentEvent.type == EventType.MouseDrag) { switch (View.CurrentMode) { case BehaviourEditorView.Mode.NodeDragging: foreach (string selectedNode in View.Selection) { var pos = View.Session.Root["Nodes"][selectedNode]["Editor"]["Position"]; var posX = pos["x"]; posX.SetValue (posX.GetValue<int> () + ((int)CurrentEvent.delta.x)); var posY = pos["y"]; posY.SetValue (posY.GetValue<int> () + ((int)CurrentEvent.delta.y)); } break; case BehaviourEditorView.Mode.ViewDragging: View.PanPosition += CurrentEvent.delta; break; } Repaint (); } else if (CurrentEvent.type == EventType.MouseDown) { if (ScreenRect.Contains (CurrentEvent.mousePosition)) { GUI.UnfocusWindow (); GUI.FocusControl (""); View.CurrentMode = BehaviourEditorView.Mode.ViewDragging; CurrentEvent.Use (); Repaint (); } } } private void DrawBackground (Rect backgroundRect, Vector2 viewPosition) { if (CurrentEvent.type == EventType.MouseMove) { return; } if (View.Session == null) { EditorGUI.LabelField (backgroundRect, "No Graph Selected", BehaviourGUIStyles.Instance.informationTextStyle); return; } #if HOVER_EFFECTS if (dragging_IsDragging) { EditorGUIUtility.AddCursorRect (backgroundRect, MouseCursor.Pan); } #endif /*if (Application.isPlaying) EditorGUI.DrawRect (screenRect, new Color (0.7f, 0.7f, 0.7f));*/ float gridScale = 0.5f; DrawImageTiled (backgroundRect, BehaviourGraphResources.Instance.WindowBackground, viewPosition, gridScale * 3); var originalTintColour = GUI.color; GUI.color = new Color (1, 1, 1, 0.6f); DrawImageTiled (backgroundRect, BehaviourGraphResources.Instance.WindowBackground, viewPosition, gridScale); GUI.color = originalTintColour; if (Application.isPlaying) { var runtimeInfo = new Rect (backgroundRect); runtimeInfo.yMin = runtimeInfo.yMax - 48; EditorGUI.LabelField (runtimeInfo, "Playmode Enabled: You may change values but you can't edit connections", BehaviourGUIStyles.Instance.informationTextStyle); } } private void DrawImageTiled (Rect rect, Texture2D texture, Vector2 positon, float zoom = 0.8f) { if (texture == null) { return; } if (CurrentEvent.type != EventType.Repaint) { return; } var tileOffset = new Vector2 ((-positon.x / texture.width) * zoom, (positon.y / texture.height) * zoom); var tileAmount = new Vector2 (Mathf.Round (rect.width * zoom) / texture.width, Mathf.Round (rect.height * zoom) / texture.height); tileOffset.y -= tileAmount.y; GUI.DrawTextureWithTexCoords (rect, texture, new Rect (tileOffset, tileAmount), true); } private void DrawTopBar () { EditorGUILayout.BeginHorizontal (EditorStyles.toolbar, GUILayout.ExpandWidth (true)); if (GUILayout.Button (CurrentPackage?.name, EditorStyles.toolbarButton, GUILayout.Width (100))) { } GUILayout.Space (6); if (GUILayout.Button ("Save", EditorStyles.toolbarButton, GUILayout.Width (100))) { using (var file = CurrentResource.WriteStream ()) { Serializer.Serialize ( new JsonTextWriter (file) { Formatting = Formatting.Indented }, View.Session.Instance ); } } if (GUILayout.Button (View.DescribeCurrentAction, EditorStyles.toolbarButton)) { } EditorGUILayout.EndHorizontal (); } } }
27.972701
120
0.647696
[ "Apache-2.0" ]
yika-aixi/RPGCore
src/RPGCoreUnity/Assets/RPGCore/Scripts/Editors/BehaviourEditor.cs
19,469
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 ComplexPasswordGenerator.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } } }
36.9
152
0.571816
[ "MIT" ]
HawkeyeZAR/ComplexPasswordGenerator
ComplexPasswordGenerator/Properties/Settings.Designer.cs
1,109
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the kinesisanalyticsv2-2018-05-23.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.KinesisAnalyticsV2.Model { /// <summary> /// For a SQL-based Kinesis Data Analytics application, describes the format of the data /// in the streaming source, and how each data element maps to corresponding columns created /// in the in-application stream. /// </summary> public partial class SourceSchema { private List<RecordColumn> _recordColumns = new List<RecordColumn>(); private string _recordEncoding; private RecordFormat _recordFormat; /// <summary> /// Gets and sets the property RecordColumns. /// <para> /// A list of <code>RecordColumn</code> objects. /// </para> /// </summary> [AWSProperty(Required=true, Min=1, Max=1000)] public List<RecordColumn> RecordColumns { get { return this._recordColumns; } set { this._recordColumns = value; } } // Check to see if RecordColumns property is set internal bool IsSetRecordColumns() { return this._recordColumns != null && this._recordColumns.Count > 0; } /// <summary> /// Gets and sets the property RecordEncoding. /// <para> /// Specifies the encoding of the records in the streaming source. For example, UTF-8. /// </para> /// </summary> [AWSProperty(Min=5, Max=5)] public string RecordEncoding { get { return this._recordEncoding; } set { this._recordEncoding = value; } } // Check to see if RecordEncoding property is set internal bool IsSetRecordEncoding() { return this._recordEncoding != null; } /// <summary> /// Gets and sets the property RecordFormat. /// <para> /// Specifies the format of the records on the streaming source. /// </para> /// </summary> [AWSProperty(Required=true)] public RecordFormat RecordFormat { get { return this._recordFormat; } set { this._recordFormat = value; } } // Check to see if RecordFormat property is set internal bool IsSetRecordFormat() { return this._recordFormat != null; } } }
33.05
117
0.602723
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/KinesisAnalyticsV2/Generated/Model/SourceSchema.cs
3,305
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure.Documents; using Microsoft.Azure.Documents.Client; using Microsoft.Azure.Graphs; using Gizmo.Configuration; using Gizmo.Console; using System.CommandLine; using Polly; namespace Gizmo.Connection { public class AzureGraphsExecutor : IQueryExecutor { private readonly CosmosDbConnection _config; private readonly IConsole _console; private DocumentClient _client; private DocumentCollection _graph; public string RemoteMessage => $"cosmos: {_graph.AltLink}@{_client.ServiceEndpoint}"; public AzureGraphsExecutor(CosmosDbConnection config, IConsole console) { _config = config; _console = console; } public void Dispose() { _client.Dispose(); } private async Task Initilize(CancellationToken ct = default) { _client = _client ?? GetDocumentClient(_config); _graph = _graph ?? await GetDocumentCollection(_client, _config); DocumentClient GetDocumentClient(CosmosDbConnection config) { // connection issues on osx // https://github.com/Azure/azure-documentdb-dotnet/issues/194 ConnectionPolicy connectionPolicy = new ConnectionPolicy(); if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { connectionPolicy.ConnectionMode = ConnectionMode.Direct; connectionPolicy.ConnectionProtocol = Protocol.Tcp; connectionPolicy.RetryOptions.MaxRetryAttemptsOnThrottledRequests = 0; } var client = new DocumentClient( config.DocumentEndpoint, config.AuthKey, connectionPolicy); return client; } async Task<DocumentCollection> GetDocumentCollection(DocumentClient client, CosmosDbConnection config) { var graph = await client.CreateDocumentCollectionIfNotExistsAsync( UriFactory.CreateDatabaseUri(config.DatabaseId), new DocumentCollection { Id = config.GraphId }); return graph; } } public async Task<bool> TestConnection(CancellationToken ct = default) { await Initilize(ct); var connected = false; try { string q = "g.inject(true);"; var query = _client.CreateGremlinQuery(_graph, q); if (query.HasMoreResults) { await query.ExecuteNextAsync<dynamic>(); connected = true; } } catch (Exception ex) { _console.WriteLine("Unable to connect to gremlin server. Please check you appsettings.json"); _console.WriteLine(ex); } return connected; } public async Task<QueryResultSet<T>> ExecuteQuery<T>(string query, CancellationToken ct = default) { await Initilize(ct); var timer = new System.Diagnostics.Stopwatch(); timer.Start(); // var output = new StringBuilder(); // int count = 0; // double cost = 0; var q = _client.CreateGremlinQuery<T>(_graph, query); var results = new FeedResponseAggregator<T>(query); int totalRetries = 0; while (q.HasMoreResults && !ct.IsCancellationRequested) { int retryCount = 0; var feedResponse = await GizmoPolicies.CosmosRetryAfterWait( new RetryOption() ).ExecuteAsync( (context) => { retryCount = (int)context["retryCount"]; return q.ExecuteNextAsync<T>(ct); }, new Polly.Context { {"retryCount", 0} }); totalRetries += retryCount; results.AddResponse(feedResponse); } //output.Insert(0, $"executed in {timer.Elapsed}. {cost:N2} RUs. {count} results. {output.Length} characters.{Environment.NewLine}"); //return output.ToString(); return results.ToQueryResultSet(totalRetries); } private class FeedResponseAggregator<T> { private readonly string _query; private readonly List<FeedResponse<T>> responses = new List<FeedResponse<T>>(); private readonly Stopwatch timer = Stopwatch.StartNew(); public FeedResponseAggregator(string query) { _query = query; } public void AddResponse(FeedResponse<T> response) { responses.Add(response); } public QueryResultSet<T> ToQueryResultSet(int retryCount = 0) { timer.Stop(); var data = responses.SelectMany(r => r).ToList(); double requestCharge = responses.Sum(r => r.RequestCharge); var attributes = new Dictionary<string, object> { ["RequestCharge"] = requestCharge, ["ElapsedTime"] = timer.Elapsed }; return new QueryResultSet<T>(_query, data.AsReadOnly(), timer.Elapsed, requestCharge, retryCount, attributes); } } } }
34.550898
145
0.560832
[ "MIT" ]
jasonchester/gizmo.sh
src/Gizmo/Connection/AzureGraphsExecutor.cs
5,770
C#
using System; using System.Collections.Generic; using System.Text; namespace Detrav.SypexGeo.Net.Helpers { public static class SpanExtentions { public static ReadOnlySpan<T> RTrim<T>(this ReadOnlySpan<T> span, T value) { int len = span.Length ; for (; len > 0 && value.Equals(span[len-1]); len--) ; if (len > 0) return span.Slice(0, len); return new ReadOnlySpan<T>(); } public static byte[][] Split(this byte[] bytes, byte ch) { List<byte[]> result = new List<byte[]>(); int lastPos = 0; for(int i = 0; i< bytes.Length; i++) { if (bytes[i] == ch) { if (lastPos == i) result.Add(new byte[0]); else result.Add(bytes.AsSpan(lastPos, i - lastPos).ToArray()); lastPos = i + 1; } } if(lastPos< bytes.Length) { result.Add(bytes.AsSpan(lastPos).ToArray()); } return result.ToArray(); } public static int Compare(this ReadOnlySpan<byte> str1, ReadOnlySpan<byte> str2) { int l1 = str1.Length; int l2 = str2.Length; int lmin = Math.Min(l1, l2); for (int i = 0; i < lmin; i++) { byte str1_ch = str1[i]; byte str2_ch = str2[i]; if (str1_ch != str2_ch) { return str1_ch - str2_ch; } } if (l1 != l2) { return l1 - l2; } else { return 0; } } } }
26.014085
88
0.40823
[ "MIT" ]
Detrav/Detrav.SypexGeo.Net
src/Detrav.SypexGeo.Net/Helpers/SpanExtentions.cs
1,849
C#
using System.ComponentModel.DataAnnotations; using YourBrand.Showroom.Application; using YourBrand.Showroom.Application.Common.Models; namespace YourBrand.Showroom.Application.Organizations; public record OrganizationDto ( string Id, string Name, AddressDto Address );
21.285714
56
0.771812
[ "MIT" ]
marinasundstrom/YourBrand
Showroom/Application/Organizations/OrganizationDto.cs
300
C#
using LiteDB; namespace Matrix.CLI.Model { public class TargetEntry { [BsonId] public string Alias { get; set; } public string Url { get; set; } } }
16.5
42
0.535354
[ "MIT" ]
matrix-platform/cmd
Matrix.CLI.Model/TargetEntry.cs
200
C#
using System; using Elk.Core; using GolPooch.Domain.Resources; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace GolPooch.Domain.Entity { [Table(nameof(Purchase), Schema = "Product")] public class Purchase : IEntity, IInsertDateProperties, IModifyDateProperties { [Key] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int PurchaseId { get; set; } [ForeignKey(nameof(UserId))] public User User { get; set; } public int UserId { get; set; } [ForeignKey(nameof(ProductOfferId))] public ProductOffer ProductOffer { get; set; } public int ProductOfferId { get; set; } [ForeignKey(nameof(PaymentTransactionId))] public PaymentTransaction PaymentTransaction { get; set; } public int PaymentTransactionId { get; set; } [Display(Name = nameof(DisplayNames.Chance), ResourceType = typeof(DisplayNames))] public byte Chance { get; set; } [Display(Name = nameof(DisplayNames.UsedChance), ResourceType = typeof(DisplayNames))] public byte UsedChance { get; set; } [Display(Name = nameof(DisplayNames.IsReFoundable), ResourceType = typeof(DisplayNames))] public bool IsReFoundable { get; set; } [Display(Name = nameof(DisplayNames.IsFinished), ResourceType = typeof(DisplayNames))] public bool IsFinished { get; set; } [Display(Name = nameof(DisplayNames.InsertDate), ResourceType = typeof(DisplayNames))] public DateTime InsertDateMi { get; set; } [Column(TypeName = "char(10)")] [Display(Name = nameof(DisplayNames.InsertDate), ResourceType = typeof(DisplayNames))] [MaxLength(10, ErrorMessageResourceName = nameof(ErrorMessage.MaxLength), ErrorMessageResourceType = typeof(ErrorMessage))] public string InsertDateSh { get; set; } [Display(Name = nameof(DisplayNames.ModifyDate), ResourceType = typeof(DisplayNames))] public DateTime ModifyDateMi { get; set; } [Column(TypeName = "char(10)")] [Display(Name = nameof(DisplayNames.ModifyDate), ResourceType = typeof(DisplayNames))] [MaxLength(10, ErrorMessageResourceName = nameof(ErrorMessage.MaxLength), ErrorMessageResourceType = typeof(ErrorMessage))] public string ModifyDateSh { get; set; } public ICollection<DrawChance> DrawChances { get; set; } } }
40.868852
131
0.68913
[ "MIT" ]
mehrannoruzi/GolYaPooch
GolPooch.Domain/Entity/Product/Purchase.cs
2,495
C#
using System.Threading.Tasks; using Neutronium.Core.Extension; using Neutronium.Core.Infra; using Neutronium.Core.WebBrowserEngine.JavascriptObject; using Neutronium.MVVMComponents; namespace Neutronium.Core.Binding.GlueObject.Executable { internal class JsResultCommand<TArg, TResult> : JsResultCommandBase<TResult, TArg>, IJsCsCachableGlue, IExecutableGlue { private readonly IResultCommand<TArg, TResult> _JsResultCommand; public object CValue => _JsResultCommand; public JsResultCommand(HtmlViewContext context, IJavascriptToCSharpConverter converter, IResultCommand<TArg, TResult> resultCommand) : base(context, converter) { _JsResultCommand = resultCommand; } protected override IJavascriptObject GetPromise(IJavascriptObject[] e) { return (e.Length > 1) ? e[1] : null; } protected override MayBe<TArg> ExecuteOnJsContextThread(IJavascriptObject[] e) { var argument = JavascriptToCSharpConverter.GetFirstArgument<TArg>(e); if (!argument.Success) { Logger.Error($"Impossible to call Execute on command<{typeof(TArg)}>, no matching argument found, received:{argument.TentativeValue} of type:{argument.TentativeValue?.GetType()} expectedType: {typeof(TArg)}"); } return argument; } protected override async Task<MayBe<TResult>> ExecuteOnUiThread(TArg argument) { var value = await _JsResultCommand.Execute(argument); return new MayBe<TResult>(value); } } }
38.714286
225
0.679582
[ "MIT" ]
simonbuehler/Neutronium
Neutronium.Core/Binding/GlueObject/Executable/JsResultCommand_Ta_Tr.cs
1,628
C#
using Pada1.BBCore; using UnityEngine; namespace BBUnity.Conditions { /// <summary> /// It is a perception condition to check if the objective is close depending on a given distance. /// </summary> [Condition("Perception/IsTargetClose")] [Help("Checks whether a target is close depending on a given distance")] public class IsTargetClose : GOCondition { ///<value>Input Target Parameter to to check the distance.</value> [InParam("target")] [Help("Target to check the distance")] public GameObject target; ///<value>Input maximun distance Parameter to consider that the target is close.</value> [InParam("closeDistance")] [Help("The maximun distance to consider that the target is close")] public float closeDistance; /// <summary> /// Checks whether a target is close depending on a given distance, /// calculates the magnitude between the gameobject and the target and then compares with the given distance. /// </summary> /// <returns>True if the magnitude between the gameobject and de target is lower that the given distance.</returns> public override bool Check() { return (gameObject.transform.position - target.transform.position).sqrMagnitude < closeDistance * closeDistance; } } }
41.030303
124
0.67356
[ "MIT" ]
Aitorlb7/IA-Tanks-Project
Assets/BehaviorBricks/Conditions/System/Perception/IsTargetClose.cs
1,356
C#
using System; using System.Threading.Tasks; namespace NadekoBot.Common { public interface IPubSub { public Task Pub<TData>(in TypedKey<TData> key, TData data); public Task Sub<TData>(in TypedKey<TData> key, Func<TData, ValueTask> action); } }
24.727273
86
0.6875
[ "MIT" ]
AnotherFoxGuy/NadekoBot
src/NadekoBot/Common/PubSub/IPubSub.cs
274
C#
namespace Craftsman.Helpers { using Craftsman.Models; using System; using System.Collections.Generic; public class TestBuildingHelpers { public static string GetUsingString(string dbContextName) { return $@"using (var context = new {dbContextName}(dbOptions))"; } } }
22
76
0.642424
[ "MIT" ]
wi3land/craftsman
Craftsman/Helpers/TestBuildingHelpers.cs
332
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("01.SumOfAllElementsOfMatrix")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("01.SumOfAllElementsOfMatrix")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("fcbd8b42-4382-4ff5-8602-f5adc2990696")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.432432
84
0.751758
[ "MIT" ]
ChrisPam/CSharpAdvanced
05.MatricesLab/01.SumOfAllElementsOfMatrix/Properties/AssemblyInfo.cs
1,425
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. namespace Microsoft.Azure.PowerShell.Cmdlets.Functions.Support { /// <summary>Log level.</summary> public partial struct LogLevel : System.IEquatable<LogLevel> { public static Microsoft.Azure.PowerShell.Cmdlets.Functions.Support.LogLevel Error = @"Error"; public static Microsoft.Azure.PowerShell.Cmdlets.Functions.Support.LogLevel Information = @"Information"; public static Microsoft.Azure.PowerShell.Cmdlets.Functions.Support.LogLevel Off = @"Off"; public static Microsoft.Azure.PowerShell.Cmdlets.Functions.Support.LogLevel Verbose = @"Verbose"; public static Microsoft.Azure.PowerShell.Cmdlets.Functions.Support.LogLevel Warning = @"Warning"; /// <summary>the value for an instance of the <see cref="LogLevel" /> Enum.</summary> private string _value { get; set; } /// <summary>Conversion from arbitrary object to LogLevel</summary> /// <param name="value">the value to convert to an instance of <see cref="LogLevel" />.</param> internal static object CreateFrom(object value) { return new LogLevel(global::System.Convert.ToString(value)); } /// <summary>Compares values of enum type LogLevel</summary> /// <param name="e">the value to compare against this instance.</param> /// <returns><c>true</c> if the two instances are equal to the same value</returns> public bool Equals(Microsoft.Azure.PowerShell.Cmdlets.Functions.Support.LogLevel e) { return _value.Equals(e._value); } /// <summary>Compares values of enum type LogLevel (override for Object)</summary> /// <param name="obj">the value to compare against this instance.</param> /// <returns><c>true</c> if the two instances are equal to the same value</returns> public override bool Equals(object obj) { return obj is LogLevel && Equals((LogLevel)obj); } /// <summary>Returns hashCode for enum LogLevel</summary> /// <returns>The hashCode of the value</returns> public override int GetHashCode() { return this._value.GetHashCode(); } /// <summary>Creates an instance of the <see cref="LogLevel" Enum class./></summary> /// <param name="underlyingValue">the value to create an instance for.</param> private LogLevel(string underlyingValue) { this._value = underlyingValue; } /// <summary>Returns string representation for LogLevel</summary> /// <returns>A string for this value.</returns> public override string ToString() { return this._value; } /// <summary>Implicit operator to convert string to LogLevel</summary> /// <param name="value">the value to convert to an instance of <see cref="LogLevel" />.</param> public static implicit operator LogLevel(string value) { return new LogLevel(value); } /// <summary>Implicit operator to convert LogLevel to string</summary> /// <param name="e">the value to convert to an instance of <see cref="LogLevel" />.</param> public static implicit operator string(Microsoft.Azure.PowerShell.Cmdlets.Functions.Support.LogLevel e) { return e._value; } /// <summary>Overriding != operator for enum LogLevel</summary> /// <param name="e1">the value to compare against <see cref="e2" /></param> /// <param name="e2">the value to compare against <see cref="e1" /></param> /// <returns><c>true</c> if the two instances are not equal to the same value</returns> public static bool operator !=(Microsoft.Azure.PowerShell.Cmdlets.Functions.Support.LogLevel e1, Microsoft.Azure.PowerShell.Cmdlets.Functions.Support.LogLevel e2) { return !e2.Equals(e1); } /// <summary>Overriding == operator for enum LogLevel</summary> /// <param name="e1">the value to compare against <see cref="e2" /></param> /// <param name="e2">the value to compare against <see cref="e1" /></param> /// <returns><c>true</c> if the two instances are equal to the same value</returns> public static bool operator ==(Microsoft.Azure.PowerShell.Cmdlets.Functions.Support.LogLevel e1, Microsoft.Azure.PowerShell.Cmdlets.Functions.Support.LogLevel e2) { return e2.Equals(e1); } } }
47.201923
171
0.636382
[ "MIT" ]
Agazoth/azure-powershell
src/Functions/generated/api/Support/LogLevel.cs
4,806
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the honeycode-2020-03-01.normal.json service model. */ using System; using System.Runtime.ExceptionServices; using System.Threading; using System.Threading.Tasks; using System.Collections.Generic; using System.Net; using Amazon.Honeycode.Model; using Amazon.Honeycode.Model.Internal.MarshallTransformations; using Amazon.Honeycode.Internal; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Auth; using Amazon.Runtime.Internal.Transform; namespace Amazon.Honeycode { /// <summary> /// Implementation for accessing Honeycode /// /// Amazon Honeycode is a fully managed service that allows you to quickly build mobile /// and web apps for teams—without programming. Build Honeycode apps for managing almost /// anything, like projects, customers, operations, approvals, resources, and even your /// team. /// </summary> public partial class AmazonHoneycodeClient : AmazonServiceClient, IAmazonHoneycode { private static IServiceMetadata serviceMetadata = new AmazonHoneycodeMetadata(); #region Constructors /// <summary> /// Constructs AmazonHoneycodeClient with the credentials loaded from the application's /// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance. /// /// Example App.config with credentials set. /// <code> /// &lt;?xml version="1.0" encoding="utf-8" ?&gt; /// &lt;configuration&gt; /// &lt;appSettings&gt; /// &lt;add key="AWSProfileName" value="AWS Default"/&gt; /// &lt;/appSettings&gt; /// &lt;/configuration&gt; /// </code> /// /// </summary> public AmazonHoneycodeClient() : base(FallbackCredentialsFactory.GetCredentials(), new AmazonHoneycodeConfig()) { } /// <summary> /// Constructs AmazonHoneycodeClient with the credentials loaded from the application's /// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance. /// /// Example App.config with credentials set. /// <code> /// &lt;?xml version="1.0" encoding="utf-8" ?&gt; /// &lt;configuration&gt; /// &lt;appSettings&gt; /// &lt;add key="AWSProfileName" value="AWS Default"/&gt; /// &lt;/appSettings&gt; /// &lt;/configuration&gt; /// </code> /// /// </summary> /// <param name="region">The region to connect.</param> public AmazonHoneycodeClient(RegionEndpoint region) : base(FallbackCredentialsFactory.GetCredentials(), new AmazonHoneycodeConfig{RegionEndpoint = region}) { } /// <summary> /// Constructs AmazonHoneycodeClient with the credentials loaded from the application's /// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance. /// /// Example App.config with credentials set. /// <code> /// &lt;?xml version="1.0" encoding="utf-8" ?&gt; /// &lt;configuration&gt; /// &lt;appSettings&gt; /// &lt;add key="AWSProfileName" value="AWS Default"/&gt; /// &lt;/appSettings&gt; /// &lt;/configuration&gt; /// </code> /// /// </summary> /// <param name="config">The AmazonHoneycodeClient Configuration Object</param> public AmazonHoneycodeClient(AmazonHoneycodeConfig config) : base(FallbackCredentialsFactory.GetCredentials(), config) { } /// <summary> /// Constructs AmazonHoneycodeClient with AWS Credentials /// </summary> /// <param name="credentials">AWS Credentials</param> public AmazonHoneycodeClient(AWSCredentials credentials) : this(credentials, new AmazonHoneycodeConfig()) { } /// <summary> /// Constructs AmazonHoneycodeClient with AWS Credentials /// </summary> /// <param name="credentials">AWS Credentials</param> /// <param name="region">The region to connect.</param> public AmazonHoneycodeClient(AWSCredentials credentials, RegionEndpoint region) : this(credentials, new AmazonHoneycodeConfig{RegionEndpoint = region}) { } /// <summary> /// Constructs AmazonHoneycodeClient with AWS Credentials and an /// AmazonHoneycodeClient Configuration object. /// </summary> /// <param name="credentials">AWS Credentials</param> /// <param name="clientConfig">The AmazonHoneycodeClient Configuration Object</param> public AmazonHoneycodeClient(AWSCredentials credentials, AmazonHoneycodeConfig clientConfig) : base(credentials, clientConfig) { } /// <summary> /// Constructs AmazonHoneycodeClient with AWS Access Key ID and AWS Secret Key /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> public AmazonHoneycodeClient(string awsAccessKeyId, string awsSecretAccessKey) : this(awsAccessKeyId, awsSecretAccessKey, new AmazonHoneycodeConfig()) { } /// <summary> /// Constructs AmazonHoneycodeClient with AWS Access Key ID and AWS Secret Key /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="region">The region to connect.</param> public AmazonHoneycodeClient(string awsAccessKeyId, string awsSecretAccessKey, RegionEndpoint region) : this(awsAccessKeyId, awsSecretAccessKey, new AmazonHoneycodeConfig() {RegionEndpoint=region}) { } /// <summary> /// Constructs AmazonHoneycodeClient with AWS Access Key ID, AWS Secret Key and an /// AmazonHoneycodeClient Configuration object. /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="clientConfig">The AmazonHoneycodeClient Configuration Object</param> public AmazonHoneycodeClient(string awsAccessKeyId, string awsSecretAccessKey, AmazonHoneycodeConfig clientConfig) : base(awsAccessKeyId, awsSecretAccessKey, clientConfig) { } /// <summary> /// Constructs AmazonHoneycodeClient with AWS Access Key ID and AWS Secret Key /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="awsSessionToken">AWS Session Token</param> public AmazonHoneycodeClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken) : this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonHoneycodeConfig()) { } /// <summary> /// Constructs AmazonHoneycodeClient with AWS Access Key ID and AWS Secret Key /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="awsSessionToken">AWS Session Token</param> /// <param name="region">The region to connect.</param> public AmazonHoneycodeClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, RegionEndpoint region) : this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonHoneycodeConfig{RegionEndpoint = region}) { } /// <summary> /// Constructs AmazonHoneycodeClient with AWS Access Key ID, AWS Secret Key and an /// AmazonHoneycodeClient Configuration object. /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="awsSessionToken">AWS Session Token</param> /// <param name="clientConfig">The AmazonHoneycodeClient Configuration Object</param> public AmazonHoneycodeClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, AmazonHoneycodeConfig clientConfig) : base(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, clientConfig) { } #endregion #if AWS_ASYNC_ENUMERABLES_API private IHoneycodePaginatorFactory _paginators; /// <summary> /// Paginators for the service /// </summary> public IHoneycodePaginatorFactory Paginators { get { if (this._paginators == null) { this._paginators = new HoneycodePaginatorFactory(this); } return this._paginators; } } #endif #region Overrides /// <summary> /// Creates the signer for the service. /// </summary> protected override AbstractAWSSigner CreateSigner() { return new AWS4Signer(); } /// <summary> /// Capture metadata for the service. /// </summary> protected override IServiceMetadata ServiceMetadata { get { return serviceMetadata; } } #endregion #region Dispose /// <summary> /// Disposes the service client. /// </summary> protected override void Dispose(bool disposing) { base.Dispose(disposing); } #endregion #region BatchCreateTableRows internal virtual BatchCreateTableRowsResponse BatchCreateTableRows(BatchCreateTableRowsRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = BatchCreateTableRowsRequestMarshaller.Instance; options.ResponseUnmarshaller = BatchCreateTableRowsResponseUnmarshaller.Instance; return Invoke<BatchCreateTableRowsResponse>(request, options); } /// <summary> /// The BatchCreateTableRows API allows you to create one or more rows at the end of /// a table in a workbook. The API allows you to specify the values to set in some or /// all of the columns in the new rows. /// /// /// <para> /// If a column is not explicitly set in a specific row, then the column level formula /// specified in the table will be applied to the new row. If there is no column level /// formula but the last row of the table has a formula, then that formula will be copied /// down to the new row. If there is no column level formula and no formula in the last /// row of the table, then that column will be left blank for the new rows. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the BatchCreateTableRows service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the BatchCreateTableRows service method, as returned by Honeycode.</returns> /// <exception cref="Amazon.Honeycode.Model.AccessDeniedException"> /// You do not have sufficient access to perform this action. Check that the workbook /// is owned by you and your IAM policy allows access to the resource in the request. /// </exception> /// <exception cref="Amazon.Honeycode.Model.InternalServerException"> /// There were unexpected errors from the server. /// </exception> /// <exception cref="Amazon.Honeycode.Model.RequestTimeoutException"> /// The request timed out. /// </exception> /// <exception cref="Amazon.Honeycode.Model.ResourceNotFoundException"> /// A Workbook, Table, App, Screen or Screen Automation was not found with the given ID. /// </exception> /// <exception cref="Amazon.Honeycode.Model.ServiceQuotaExceededException"> /// The request caused service quota to be breached. /// </exception> /// <exception cref="Amazon.Honeycode.Model.ServiceUnavailableException"> /// Remote service is unreachable. /// </exception> /// <exception cref="Amazon.Honeycode.Model.ThrottlingException"> /// Tps(transactions per second) rate reached. /// </exception> /// <exception cref="Amazon.Honeycode.Model.ValidationException"> /// Request is invalid. The message in the response contains details on why the request /// is invalid. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/honeycode-2020-03-01/BatchCreateTableRows">REST API Reference for BatchCreateTableRows Operation</seealso> public virtual Task<BatchCreateTableRowsResponse> BatchCreateTableRowsAsync(BatchCreateTableRowsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var options = new InvokeOptions(); options.RequestMarshaller = BatchCreateTableRowsRequestMarshaller.Instance; options.ResponseUnmarshaller = BatchCreateTableRowsResponseUnmarshaller.Instance; return InvokeAsync<BatchCreateTableRowsResponse>(request, options, cancellationToken); } #endregion #region BatchDeleteTableRows internal virtual BatchDeleteTableRowsResponse BatchDeleteTableRows(BatchDeleteTableRowsRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = BatchDeleteTableRowsRequestMarshaller.Instance; options.ResponseUnmarshaller = BatchDeleteTableRowsResponseUnmarshaller.Instance; return Invoke<BatchDeleteTableRowsResponse>(request, options); } /// <summary> /// The BatchDeleteTableRows API allows you to delete one or more rows from a table in /// a workbook. You need to specify the ids of the rows that you want to delete from the /// table. /// </summary> /// <param name="request">Container for the necessary parameters to execute the BatchDeleteTableRows service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the BatchDeleteTableRows service method, as returned by Honeycode.</returns> /// <exception cref="Amazon.Honeycode.Model.AccessDeniedException"> /// You do not have sufficient access to perform this action. Check that the workbook /// is owned by you and your IAM policy allows access to the resource in the request. /// </exception> /// <exception cref="Amazon.Honeycode.Model.InternalServerException"> /// There were unexpected errors from the server. /// </exception> /// <exception cref="Amazon.Honeycode.Model.RequestTimeoutException"> /// The request timed out. /// </exception> /// <exception cref="Amazon.Honeycode.Model.ResourceNotFoundException"> /// A Workbook, Table, App, Screen or Screen Automation was not found with the given ID. /// </exception> /// <exception cref="Amazon.Honeycode.Model.ServiceUnavailableException"> /// Remote service is unreachable. /// </exception> /// <exception cref="Amazon.Honeycode.Model.ThrottlingException"> /// Tps(transactions per second) rate reached. /// </exception> /// <exception cref="Amazon.Honeycode.Model.ValidationException"> /// Request is invalid. The message in the response contains details on why the request /// is invalid. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/honeycode-2020-03-01/BatchDeleteTableRows">REST API Reference for BatchDeleteTableRows Operation</seealso> public virtual Task<BatchDeleteTableRowsResponse> BatchDeleteTableRowsAsync(BatchDeleteTableRowsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var options = new InvokeOptions(); options.RequestMarshaller = BatchDeleteTableRowsRequestMarshaller.Instance; options.ResponseUnmarshaller = BatchDeleteTableRowsResponseUnmarshaller.Instance; return InvokeAsync<BatchDeleteTableRowsResponse>(request, options, cancellationToken); } #endregion #region BatchUpdateTableRows internal virtual BatchUpdateTableRowsResponse BatchUpdateTableRows(BatchUpdateTableRowsRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = BatchUpdateTableRowsRequestMarshaller.Instance; options.ResponseUnmarshaller = BatchUpdateTableRowsResponseUnmarshaller.Instance; return Invoke<BatchUpdateTableRowsResponse>(request, options); } /// <summary> /// The BatchUpdateTableRows API allows you to update one or more rows in a table in /// a workbook. /// /// /// <para> /// You can specify the values to set in some or all of the columns in the table for /// the specified rows. If a column is not explicitly specified in a particular row, then /// that column will not be updated for that row. To clear out the data in a specific /// cell, you need to set the value as an empty string (""). /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the BatchUpdateTableRows service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the BatchUpdateTableRows service method, as returned by Honeycode.</returns> /// <exception cref="Amazon.Honeycode.Model.AccessDeniedException"> /// You do not have sufficient access to perform this action. Check that the workbook /// is owned by you and your IAM policy allows access to the resource in the request. /// </exception> /// <exception cref="Amazon.Honeycode.Model.InternalServerException"> /// There were unexpected errors from the server. /// </exception> /// <exception cref="Amazon.Honeycode.Model.RequestTimeoutException"> /// The request timed out. /// </exception> /// <exception cref="Amazon.Honeycode.Model.ResourceNotFoundException"> /// A Workbook, Table, App, Screen or Screen Automation was not found with the given ID. /// </exception> /// <exception cref="Amazon.Honeycode.Model.ServiceUnavailableException"> /// Remote service is unreachable. /// </exception> /// <exception cref="Amazon.Honeycode.Model.ThrottlingException"> /// Tps(transactions per second) rate reached. /// </exception> /// <exception cref="Amazon.Honeycode.Model.ValidationException"> /// Request is invalid. The message in the response contains details on why the request /// is invalid. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/honeycode-2020-03-01/BatchUpdateTableRows">REST API Reference for BatchUpdateTableRows Operation</seealso> public virtual Task<BatchUpdateTableRowsResponse> BatchUpdateTableRowsAsync(BatchUpdateTableRowsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var options = new InvokeOptions(); options.RequestMarshaller = BatchUpdateTableRowsRequestMarshaller.Instance; options.ResponseUnmarshaller = BatchUpdateTableRowsResponseUnmarshaller.Instance; return InvokeAsync<BatchUpdateTableRowsResponse>(request, options, cancellationToken); } #endregion #region BatchUpsertTableRows internal virtual BatchUpsertTableRowsResponse BatchUpsertTableRows(BatchUpsertTableRowsRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = BatchUpsertTableRowsRequestMarshaller.Instance; options.ResponseUnmarshaller = BatchUpsertTableRowsResponseUnmarshaller.Instance; return Invoke<BatchUpsertTableRowsResponse>(request, options); } /// <summary> /// The BatchUpsertTableRows API allows you to upsert one or more rows in a table. The /// upsert operation takes a filter expression as input and evaluates it to find matching /// rows on the destination table. If matching rows are found, it will update the cells /// in the matching rows to new values specified in the request. If no matching rows are /// found, a new row is added at the end of the table and the cells in that row are set /// to the new values specified in the request. /// /// /// <para> /// You can specify the values to set in some or all of the columns in the table for /// the matching or newly appended rows. If a column is not explicitly specified for a /// particular row, then that column will not be updated for that row. To clear out the /// data in a specific cell, you need to set the value as an empty string (""). /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the BatchUpsertTableRows service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the BatchUpsertTableRows service method, as returned by Honeycode.</returns> /// <exception cref="Amazon.Honeycode.Model.AccessDeniedException"> /// You do not have sufficient access to perform this action. Check that the workbook /// is owned by you and your IAM policy allows access to the resource in the request. /// </exception> /// <exception cref="Amazon.Honeycode.Model.InternalServerException"> /// There were unexpected errors from the server. /// </exception> /// <exception cref="Amazon.Honeycode.Model.RequestTimeoutException"> /// The request timed out. /// </exception> /// <exception cref="Amazon.Honeycode.Model.ResourceNotFoundException"> /// A Workbook, Table, App, Screen or Screen Automation was not found with the given ID. /// </exception> /// <exception cref="Amazon.Honeycode.Model.ServiceQuotaExceededException"> /// The request caused service quota to be breached. /// </exception> /// <exception cref="Amazon.Honeycode.Model.ServiceUnavailableException"> /// Remote service is unreachable. /// </exception> /// <exception cref="Amazon.Honeycode.Model.ThrottlingException"> /// Tps(transactions per second) rate reached. /// </exception> /// <exception cref="Amazon.Honeycode.Model.ValidationException"> /// Request is invalid. The message in the response contains details on why the request /// is invalid. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/honeycode-2020-03-01/BatchUpsertTableRows">REST API Reference for BatchUpsertTableRows Operation</seealso> public virtual Task<BatchUpsertTableRowsResponse> BatchUpsertTableRowsAsync(BatchUpsertTableRowsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var options = new InvokeOptions(); options.RequestMarshaller = BatchUpsertTableRowsRequestMarshaller.Instance; options.ResponseUnmarshaller = BatchUpsertTableRowsResponseUnmarshaller.Instance; return InvokeAsync<BatchUpsertTableRowsResponse>(request, options, cancellationToken); } #endregion #region DescribeTableDataImportJob internal virtual DescribeTableDataImportJobResponse DescribeTableDataImportJob(DescribeTableDataImportJobRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = DescribeTableDataImportJobRequestMarshaller.Instance; options.ResponseUnmarshaller = DescribeTableDataImportJobResponseUnmarshaller.Instance; return Invoke<DescribeTableDataImportJobResponse>(request, options); } /// <summary> /// The DescribeTableDataImportJob API allows you to retrieve the status and details /// of a table data import job. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeTableDataImportJob service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the DescribeTableDataImportJob service method, as returned by Honeycode.</returns> /// <exception cref="Amazon.Honeycode.Model.AccessDeniedException"> /// You do not have sufficient access to perform this action. Check that the workbook /// is owned by you and your IAM policy allows access to the resource in the request. /// </exception> /// <exception cref="Amazon.Honeycode.Model.InternalServerException"> /// There were unexpected errors from the server. /// </exception> /// <exception cref="Amazon.Honeycode.Model.RequestTimeoutException"> /// The request timed out. /// </exception> /// <exception cref="Amazon.Honeycode.Model.ResourceNotFoundException"> /// A Workbook, Table, App, Screen or Screen Automation was not found with the given ID. /// </exception> /// <exception cref="Amazon.Honeycode.Model.ServiceUnavailableException"> /// Remote service is unreachable. /// </exception> /// <exception cref="Amazon.Honeycode.Model.ThrottlingException"> /// Tps(transactions per second) rate reached. /// </exception> /// <exception cref="Amazon.Honeycode.Model.ValidationException"> /// Request is invalid. The message in the response contains details on why the request /// is invalid. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/honeycode-2020-03-01/DescribeTableDataImportJob">REST API Reference for DescribeTableDataImportJob Operation</seealso> public virtual Task<DescribeTableDataImportJobResponse> DescribeTableDataImportJobAsync(DescribeTableDataImportJobRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var options = new InvokeOptions(); options.RequestMarshaller = DescribeTableDataImportJobRequestMarshaller.Instance; options.ResponseUnmarshaller = DescribeTableDataImportJobResponseUnmarshaller.Instance; return InvokeAsync<DescribeTableDataImportJobResponse>(request, options, cancellationToken); } #endregion #region GetScreenData internal virtual GetScreenDataResponse GetScreenData(GetScreenDataRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = GetScreenDataRequestMarshaller.Instance; options.ResponseUnmarshaller = GetScreenDataResponseUnmarshaller.Instance; return Invoke<GetScreenDataResponse>(request, options); } /// <summary> /// The GetScreenData API allows retrieval of data from a screen in a Honeycode app. /// The API allows setting local variables in the screen to filter, sort or otherwise /// affect what will be displayed on the screen. /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetScreenData service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the GetScreenData service method, as returned by Honeycode.</returns> /// <exception cref="Amazon.Honeycode.Model.AccessDeniedException"> /// You do not have sufficient access to perform this action. Check that the workbook /// is owned by you and your IAM policy allows access to the resource in the request. /// </exception> /// <exception cref="Amazon.Honeycode.Model.InternalServerException"> /// There were unexpected errors from the server. /// </exception> /// <exception cref="Amazon.Honeycode.Model.RequestTimeoutException"> /// The request timed out. /// </exception> /// <exception cref="Amazon.Honeycode.Model.ResourceNotFoundException"> /// A Workbook, Table, App, Screen or Screen Automation was not found with the given ID. /// </exception> /// <exception cref="Amazon.Honeycode.Model.ServiceUnavailableException"> /// Remote service is unreachable. /// </exception> /// <exception cref="Amazon.Honeycode.Model.ThrottlingException"> /// Tps(transactions per second) rate reached. /// </exception> /// <exception cref="Amazon.Honeycode.Model.ValidationException"> /// Request is invalid. The message in the response contains details on why the request /// is invalid. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/honeycode-2020-03-01/GetScreenData">REST API Reference for GetScreenData Operation</seealso> public virtual Task<GetScreenDataResponse> GetScreenDataAsync(GetScreenDataRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var options = new InvokeOptions(); options.RequestMarshaller = GetScreenDataRequestMarshaller.Instance; options.ResponseUnmarshaller = GetScreenDataResponseUnmarshaller.Instance; return InvokeAsync<GetScreenDataResponse>(request, options, cancellationToken); } #endregion #region InvokeScreenAutomation internal virtual InvokeScreenAutomationResponse InvokeScreenAutomation(InvokeScreenAutomationRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = InvokeScreenAutomationRequestMarshaller.Instance; options.ResponseUnmarshaller = InvokeScreenAutomationResponseUnmarshaller.Instance; return Invoke<InvokeScreenAutomationResponse>(request, options); } /// <summary> /// The InvokeScreenAutomation API allows invoking an action defined in a screen in a /// Honeycode app. The API allows setting local variables, which can then be used in the /// automation being invoked. This allows automating the Honeycode app interactions to /// write, update or delete data in the workbook. /// </summary> /// <param name="request">Container for the necessary parameters to execute the InvokeScreenAutomation service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the InvokeScreenAutomation service method, as returned by Honeycode.</returns> /// <exception cref="Amazon.Honeycode.Model.AccessDeniedException"> /// You do not have sufficient access to perform this action. Check that the workbook /// is owned by you and your IAM policy allows access to the resource in the request. /// </exception> /// <exception cref="Amazon.Honeycode.Model.AutomationExecutionException"> /// The automation execution did not end successfully. /// </exception> /// <exception cref="Amazon.Honeycode.Model.AutomationExecutionTimeoutException"> /// The automation execution timed out. /// </exception> /// <exception cref="Amazon.Honeycode.Model.InternalServerException"> /// There were unexpected errors from the server. /// </exception> /// <exception cref="Amazon.Honeycode.Model.RequestTimeoutException"> /// The request timed out. /// </exception> /// <exception cref="Amazon.Honeycode.Model.ResourceNotFoundException"> /// A Workbook, Table, App, Screen or Screen Automation was not found with the given ID. /// </exception> /// <exception cref="Amazon.Honeycode.Model.ServiceQuotaExceededException"> /// The request caused service quota to be breached. /// </exception> /// <exception cref="Amazon.Honeycode.Model.ServiceUnavailableException"> /// Remote service is unreachable. /// </exception> /// <exception cref="Amazon.Honeycode.Model.ThrottlingException"> /// Tps(transactions per second) rate reached. /// </exception> /// <exception cref="Amazon.Honeycode.Model.ValidationException"> /// Request is invalid. The message in the response contains details on why the request /// is invalid. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/honeycode-2020-03-01/InvokeScreenAutomation">REST API Reference for InvokeScreenAutomation Operation</seealso> public virtual Task<InvokeScreenAutomationResponse> InvokeScreenAutomationAsync(InvokeScreenAutomationRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var options = new InvokeOptions(); options.RequestMarshaller = InvokeScreenAutomationRequestMarshaller.Instance; options.ResponseUnmarshaller = InvokeScreenAutomationResponseUnmarshaller.Instance; return InvokeAsync<InvokeScreenAutomationResponse>(request, options, cancellationToken); } #endregion #region ListTableColumns internal virtual ListTableColumnsResponse ListTableColumns(ListTableColumnsRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = ListTableColumnsRequestMarshaller.Instance; options.ResponseUnmarshaller = ListTableColumnsResponseUnmarshaller.Instance; return Invoke<ListTableColumnsResponse>(request, options); } /// <summary> /// The ListTableColumns API allows you to retrieve a list of all the columns in a table /// in a workbook. /// </summary> /// <param name="request">Container for the necessary parameters to execute the ListTableColumns service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the ListTableColumns service method, as returned by Honeycode.</returns> /// <exception cref="Amazon.Honeycode.Model.AccessDeniedException"> /// You do not have sufficient access to perform this action. Check that the workbook /// is owned by you and your IAM policy allows access to the resource in the request. /// </exception> /// <exception cref="Amazon.Honeycode.Model.InternalServerException"> /// There were unexpected errors from the server. /// </exception> /// <exception cref="Amazon.Honeycode.Model.RequestTimeoutException"> /// The request timed out. /// </exception> /// <exception cref="Amazon.Honeycode.Model.ResourceNotFoundException"> /// A Workbook, Table, App, Screen or Screen Automation was not found with the given ID. /// </exception> /// <exception cref="Amazon.Honeycode.Model.ServiceUnavailableException"> /// Remote service is unreachable. /// </exception> /// <exception cref="Amazon.Honeycode.Model.ThrottlingException"> /// Tps(transactions per second) rate reached. /// </exception> /// <exception cref="Amazon.Honeycode.Model.ValidationException"> /// Request is invalid. The message in the response contains details on why the request /// is invalid. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/honeycode-2020-03-01/ListTableColumns">REST API Reference for ListTableColumns Operation</seealso> public virtual Task<ListTableColumnsResponse> ListTableColumnsAsync(ListTableColumnsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var options = new InvokeOptions(); options.RequestMarshaller = ListTableColumnsRequestMarshaller.Instance; options.ResponseUnmarshaller = ListTableColumnsResponseUnmarshaller.Instance; return InvokeAsync<ListTableColumnsResponse>(request, options, cancellationToken); } #endregion #region ListTableRows internal virtual ListTableRowsResponse ListTableRows(ListTableRowsRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = ListTableRowsRequestMarshaller.Instance; options.ResponseUnmarshaller = ListTableRowsResponseUnmarshaller.Instance; return Invoke<ListTableRowsResponse>(request, options); } /// <summary> /// The ListTableRows API allows you to retrieve a list of all the rows in a table in /// a workbook. /// </summary> /// <param name="request">Container for the necessary parameters to execute the ListTableRows service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the ListTableRows service method, as returned by Honeycode.</returns> /// <exception cref="Amazon.Honeycode.Model.AccessDeniedException"> /// You do not have sufficient access to perform this action. Check that the workbook /// is owned by you and your IAM policy allows access to the resource in the request. /// </exception> /// <exception cref="Amazon.Honeycode.Model.InternalServerException"> /// There were unexpected errors from the server. /// </exception> /// <exception cref="Amazon.Honeycode.Model.RequestTimeoutException"> /// The request timed out. /// </exception> /// <exception cref="Amazon.Honeycode.Model.ResourceNotFoundException"> /// A Workbook, Table, App, Screen or Screen Automation was not found with the given ID. /// </exception> /// <exception cref="Amazon.Honeycode.Model.ServiceUnavailableException"> /// Remote service is unreachable. /// </exception> /// <exception cref="Amazon.Honeycode.Model.ThrottlingException"> /// Tps(transactions per second) rate reached. /// </exception> /// <exception cref="Amazon.Honeycode.Model.ValidationException"> /// Request is invalid. The message in the response contains details on why the request /// is invalid. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/honeycode-2020-03-01/ListTableRows">REST API Reference for ListTableRows Operation</seealso> public virtual Task<ListTableRowsResponse> ListTableRowsAsync(ListTableRowsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var options = new InvokeOptions(); options.RequestMarshaller = ListTableRowsRequestMarshaller.Instance; options.ResponseUnmarshaller = ListTableRowsResponseUnmarshaller.Instance; return InvokeAsync<ListTableRowsResponse>(request, options, cancellationToken); } #endregion #region ListTables internal virtual ListTablesResponse ListTables(ListTablesRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = ListTablesRequestMarshaller.Instance; options.ResponseUnmarshaller = ListTablesResponseUnmarshaller.Instance; return Invoke<ListTablesResponse>(request, options); } /// <summary> /// The ListTables API allows you to retrieve a list of all the tables in a workbook. /// </summary> /// <param name="request">Container for the necessary parameters to execute the ListTables service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the ListTables service method, as returned by Honeycode.</returns> /// <exception cref="Amazon.Honeycode.Model.AccessDeniedException"> /// You do not have sufficient access to perform this action. Check that the workbook /// is owned by you and your IAM policy allows access to the resource in the request. /// </exception> /// <exception cref="Amazon.Honeycode.Model.InternalServerException"> /// There were unexpected errors from the server. /// </exception> /// <exception cref="Amazon.Honeycode.Model.RequestTimeoutException"> /// The request timed out. /// </exception> /// <exception cref="Amazon.Honeycode.Model.ResourceNotFoundException"> /// A Workbook, Table, App, Screen or Screen Automation was not found with the given ID. /// </exception> /// <exception cref="Amazon.Honeycode.Model.ServiceUnavailableException"> /// Remote service is unreachable. /// </exception> /// <exception cref="Amazon.Honeycode.Model.ThrottlingException"> /// Tps(transactions per second) rate reached. /// </exception> /// <exception cref="Amazon.Honeycode.Model.ValidationException"> /// Request is invalid. The message in the response contains details on why the request /// is invalid. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/honeycode-2020-03-01/ListTables">REST API Reference for ListTables Operation</seealso> public virtual Task<ListTablesResponse> ListTablesAsync(ListTablesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var options = new InvokeOptions(); options.RequestMarshaller = ListTablesRequestMarshaller.Instance; options.ResponseUnmarshaller = ListTablesResponseUnmarshaller.Instance; return InvokeAsync<ListTablesResponse>(request, options, cancellationToken); } #endregion #region ListTagsForResource internal virtual ListTagsForResourceResponse ListTagsForResource(ListTagsForResourceRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = ListTagsForResourceRequestMarshaller.Instance; options.ResponseUnmarshaller = ListTagsForResourceResponseUnmarshaller.Instance; return Invoke<ListTagsForResourceResponse>(request, options); } /// <summary> /// The ListTagsForResource API allows you to return a resource's tags. /// </summary> /// <param name="request">Container for the necessary parameters to execute the ListTagsForResource service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the ListTagsForResource service method, as returned by Honeycode.</returns> /// <exception cref="Amazon.Honeycode.Model.AccessDeniedException"> /// You do not have sufficient access to perform this action. Check that the workbook /// is owned by you and your IAM policy allows access to the resource in the request. /// </exception> /// <exception cref="Amazon.Honeycode.Model.InternalServerException"> /// There were unexpected errors from the server. /// </exception> /// <exception cref="Amazon.Honeycode.Model.RequestTimeoutException"> /// The request timed out. /// </exception> /// <exception cref="Amazon.Honeycode.Model.ResourceNotFoundException"> /// A Workbook, Table, App, Screen or Screen Automation was not found with the given ID. /// </exception> /// <exception cref="Amazon.Honeycode.Model.ServiceUnavailableException"> /// Remote service is unreachable. /// </exception> /// <exception cref="Amazon.Honeycode.Model.ThrottlingException"> /// Tps(transactions per second) rate reached. /// </exception> /// <exception cref="Amazon.Honeycode.Model.ValidationException"> /// Request is invalid. The message in the response contains details on why the request /// is invalid. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/honeycode-2020-03-01/ListTagsForResource">REST API Reference for ListTagsForResource Operation</seealso> public virtual Task<ListTagsForResourceResponse> ListTagsForResourceAsync(ListTagsForResourceRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var options = new InvokeOptions(); options.RequestMarshaller = ListTagsForResourceRequestMarshaller.Instance; options.ResponseUnmarshaller = ListTagsForResourceResponseUnmarshaller.Instance; return InvokeAsync<ListTagsForResourceResponse>(request, options, cancellationToken); } #endregion #region QueryTableRows internal virtual QueryTableRowsResponse QueryTableRows(QueryTableRowsRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = QueryTableRowsRequestMarshaller.Instance; options.ResponseUnmarshaller = QueryTableRowsResponseUnmarshaller.Instance; return Invoke<QueryTableRowsResponse>(request, options); } /// <summary> /// The QueryTableRows API allows you to use a filter formula to query for specific rows /// in a table. /// </summary> /// <param name="request">Container for the necessary parameters to execute the QueryTableRows service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the QueryTableRows service method, as returned by Honeycode.</returns> /// <exception cref="Amazon.Honeycode.Model.AccessDeniedException"> /// You do not have sufficient access to perform this action. Check that the workbook /// is owned by you and your IAM policy allows access to the resource in the request. /// </exception> /// <exception cref="Amazon.Honeycode.Model.InternalServerException"> /// There were unexpected errors from the server. /// </exception> /// <exception cref="Amazon.Honeycode.Model.RequestTimeoutException"> /// The request timed out. /// </exception> /// <exception cref="Amazon.Honeycode.Model.ResourceNotFoundException"> /// A Workbook, Table, App, Screen or Screen Automation was not found with the given ID. /// </exception> /// <exception cref="Amazon.Honeycode.Model.ServiceUnavailableException"> /// Remote service is unreachable. /// </exception> /// <exception cref="Amazon.Honeycode.Model.ThrottlingException"> /// Tps(transactions per second) rate reached. /// </exception> /// <exception cref="Amazon.Honeycode.Model.ValidationException"> /// Request is invalid. The message in the response contains details on why the request /// is invalid. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/honeycode-2020-03-01/QueryTableRows">REST API Reference for QueryTableRows Operation</seealso> public virtual Task<QueryTableRowsResponse> QueryTableRowsAsync(QueryTableRowsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var options = new InvokeOptions(); options.RequestMarshaller = QueryTableRowsRequestMarshaller.Instance; options.ResponseUnmarshaller = QueryTableRowsResponseUnmarshaller.Instance; return InvokeAsync<QueryTableRowsResponse>(request, options, cancellationToken); } #endregion #region StartTableDataImportJob internal virtual StartTableDataImportJobResponse StartTableDataImportJob(StartTableDataImportJobRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = StartTableDataImportJobRequestMarshaller.Instance; options.ResponseUnmarshaller = StartTableDataImportJobResponseUnmarshaller.Instance; return Invoke<StartTableDataImportJobResponse>(request, options); } /// <summary> /// The StartTableDataImportJob API allows you to start an import job on a table. This /// API will only return the id of the job that was started. To find out the status of /// the import request, you need to call the DescribeTableDataImportJob API. /// </summary> /// <param name="request">Container for the necessary parameters to execute the StartTableDataImportJob service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the StartTableDataImportJob service method, as returned by Honeycode.</returns> /// <exception cref="Amazon.Honeycode.Model.AccessDeniedException"> /// You do not have sufficient access to perform this action. Check that the workbook /// is owned by you and your IAM policy allows access to the resource in the request. /// </exception> /// <exception cref="Amazon.Honeycode.Model.InternalServerException"> /// There were unexpected errors from the server. /// </exception> /// <exception cref="Amazon.Honeycode.Model.RequestTimeoutException"> /// The request timed out. /// </exception> /// <exception cref="Amazon.Honeycode.Model.ResourceNotFoundException"> /// A Workbook, Table, App, Screen or Screen Automation was not found with the given ID. /// </exception> /// <exception cref="Amazon.Honeycode.Model.ServiceQuotaExceededException"> /// The request caused service quota to be breached. /// </exception> /// <exception cref="Amazon.Honeycode.Model.ServiceUnavailableException"> /// Remote service is unreachable. /// </exception> /// <exception cref="Amazon.Honeycode.Model.ThrottlingException"> /// Tps(transactions per second) rate reached. /// </exception> /// <exception cref="Amazon.Honeycode.Model.ValidationException"> /// Request is invalid. The message in the response contains details on why the request /// is invalid. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/honeycode-2020-03-01/StartTableDataImportJob">REST API Reference for StartTableDataImportJob Operation</seealso> public virtual Task<StartTableDataImportJobResponse> StartTableDataImportJobAsync(StartTableDataImportJobRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var options = new InvokeOptions(); options.RequestMarshaller = StartTableDataImportJobRequestMarshaller.Instance; options.ResponseUnmarshaller = StartTableDataImportJobResponseUnmarshaller.Instance; return InvokeAsync<StartTableDataImportJobResponse>(request, options, cancellationToken); } #endregion #region TagResource internal virtual TagResourceResponse TagResource(TagResourceRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = TagResourceRequestMarshaller.Instance; options.ResponseUnmarshaller = TagResourceResponseUnmarshaller.Instance; return Invoke<TagResourceResponse>(request, options); } /// <summary> /// The TagResource API allows you to add tags to an ARN-able resource. Resource includes /// workbook, table, screen and screen-automation. /// </summary> /// <param name="request">Container for the necessary parameters to execute the TagResource service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the TagResource service method, as returned by Honeycode.</returns> /// <exception cref="Amazon.Honeycode.Model.AccessDeniedException"> /// You do not have sufficient access to perform this action. Check that the workbook /// is owned by you and your IAM policy allows access to the resource in the request. /// </exception> /// <exception cref="Amazon.Honeycode.Model.InternalServerException"> /// There were unexpected errors from the server. /// </exception> /// <exception cref="Amazon.Honeycode.Model.RequestTimeoutException"> /// The request timed out. /// </exception> /// <exception cref="Amazon.Honeycode.Model.ResourceNotFoundException"> /// A Workbook, Table, App, Screen or Screen Automation was not found with the given ID. /// </exception> /// <exception cref="Amazon.Honeycode.Model.ServiceUnavailableException"> /// Remote service is unreachable. /// </exception> /// <exception cref="Amazon.Honeycode.Model.ThrottlingException"> /// Tps(transactions per second) rate reached. /// </exception> /// <exception cref="Amazon.Honeycode.Model.ValidationException"> /// Request is invalid. The message in the response contains details on why the request /// is invalid. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/honeycode-2020-03-01/TagResource">REST API Reference for TagResource Operation</seealso> public virtual Task<TagResourceResponse> TagResourceAsync(TagResourceRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var options = new InvokeOptions(); options.RequestMarshaller = TagResourceRequestMarshaller.Instance; options.ResponseUnmarshaller = TagResourceResponseUnmarshaller.Instance; return InvokeAsync<TagResourceResponse>(request, options, cancellationToken); } #endregion #region UntagResource internal virtual UntagResourceResponse UntagResource(UntagResourceRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = UntagResourceRequestMarshaller.Instance; options.ResponseUnmarshaller = UntagResourceResponseUnmarshaller.Instance; return Invoke<UntagResourceResponse>(request, options); } /// <summary> /// The UntagResource API allows you to removes tags from an ARN-able resource. Resource /// includes workbook, table, screen and screen-automation. /// </summary> /// <param name="request">Container for the necessary parameters to execute the UntagResource service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the UntagResource service method, as returned by Honeycode.</returns> /// <exception cref="Amazon.Honeycode.Model.AccessDeniedException"> /// You do not have sufficient access to perform this action. Check that the workbook /// is owned by you and your IAM policy allows access to the resource in the request. /// </exception> /// <exception cref="Amazon.Honeycode.Model.InternalServerException"> /// There were unexpected errors from the server. /// </exception> /// <exception cref="Amazon.Honeycode.Model.RequestTimeoutException"> /// The request timed out. /// </exception> /// <exception cref="Amazon.Honeycode.Model.ResourceNotFoundException"> /// A Workbook, Table, App, Screen or Screen Automation was not found with the given ID. /// </exception> /// <exception cref="Amazon.Honeycode.Model.ServiceUnavailableException"> /// Remote service is unreachable. /// </exception> /// <exception cref="Amazon.Honeycode.Model.ThrottlingException"> /// Tps(transactions per second) rate reached. /// </exception> /// <exception cref="Amazon.Honeycode.Model.ValidationException"> /// Request is invalid. The message in the response contains details on why the request /// is invalid. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/honeycode-2020-03-01/UntagResource">REST API Reference for UntagResource Operation</seealso> public virtual Task<UntagResourceResponse> UntagResourceAsync(UntagResourceRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var options = new InvokeOptions(); options.RequestMarshaller = UntagResourceRequestMarshaller.Instance; options.ResponseUnmarshaller = UntagResourceResponseUnmarshaller.Instance; return InvokeAsync<UntagResourceResponse>(request, options, cancellationToken); } #endregion } }
51.233558
221
0.666935
[ "Apache-2.0" ]
Hazy87/aws-sdk-net
sdk/src/Services/Honeycode/Generated/_netstandard/AmazonHoneycodeClient.cs
60,765
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Telegram.Bot; using Telegram.Bot.Types; using Telegram.Bot.Types.Enums; using WordCounterBot.BLL.Common; using WordCounterBot.DAL.Contracts; namespace WordCounterBot.BLL.Contracts { public class GetStatsForCurrentDayCommand : ICommand { public string Name { get; } = @"getstatscurrentday"; private readonly IUserDao _userDao; private readonly TelegramBotClient _client; private readonly ICounterDatedDao _counterDatedDao; public GetStatsForCurrentDayCommand(ICounterDatedDao counterDatedDao, IUserDao userDao, TelegramBotClient client) { _userDao = userDao; _client = client; _counterDatedDao = counterDatedDao; } public async Task Execute(Update update, string command, params string[] args) { await GetTopNAndRespond(update, 16); } private async Task GetTopNAndRespond(Update update, int N) { var date = update.Message.Date.Date; var counters = await _counterDatedDao.GetCounters(update.Message.Chat.Id, date, N); var userCounters = await Task.WhenAll(counters.Select(async (c) => new { User = await _userDao.GetUserById(c.UserId), Counter = c.Value })); var result = userCounters .Select(uc => ( (uc.User != null ? uc.User.FirstName + " " + uc.User.LastName : "%Unknown%").Escape(), uc.Counter)); var text = CreateText(result, date); await _client.SendTextMessageAsync( update.Message.Chat.Id, text, replyToMessageId: update.Message.MessageId, parseMode: ParseMode.Html); } private static string CreateText(IEnumerable<(string Username, long Counter)> users, DateTime date) { var values = users.ToList(); return TableGenerator.GenerateTop($@"Top {values.Count()} counters for {date:dd MMMM yyyy}:", values); } } }
33.477612
121
0.608114
[ "MIT" ]
admiralWoop/multi-purpose-tg-bot
dotnet-app/BLL/WordCounterBot.BLL.Core/Commands/GetStatsForCurrentDayCommand.cs
2,245
C#
using System; using HandHistories.Objects.GameDescription; using HandHistories.Objects.Hand; using HandHistories.Parser.UnitTests.Parsers.Base; using NUnit.Framework; namespace HandHistories.Parser.UnitTests.Parsers.HandSummaryParserTests.FormatTests { [TestFixture("IPoker", 3305969126, 8)] class HandParserHandFormatTests : HandHistoryParserBaseTests { private readonly string _unformattedXmlHand; private readonly long _expectedHandId; private readonly int _expectedNumActions; public HandParserHandFormatTests(string site, long handId, int expectedNumActions) : base(site) { _expectedHandId = handId; _expectedNumActions = expectedNumActions; try { _unformattedXmlHand = SampleHandHistoryRepository.GetFormatHandHistoryText(PokerFormat.CashGame, Site, "UnformattedXmlHand"); } catch (Exception ex) { Assert.Fail(ex.Message); } } [Test] public void HandleUnformattedHand_Works() { Assert.IsTrue(GetParser().IsValidHand(_unformattedXmlHand)); HandHistorySummary summary = GetParser().ParseFullHandSummary(_unformattedXmlHand); HandHistory fullHandParse = GetParser().ParseFullHandHistory(_unformattedXmlHand); Assert.AreEqual(_expectedHandId, summary.HandId, "IHandHistorySummaryParser: ParseHandId"); Assert.AreEqual(_expectedHandId, fullHandParse.HandId, "IHandHistoryParser: ParseHandId"); Assert.AreEqual(_expectedNumActions, fullHandParse.HandActions.Count, "IHandHistoryParser: ParseHandId"); } } }
36.93617
141
0.682604
[ "Unlicense" ]
joshurtree/PokerAnalytics
HandHistories.Parser.UnitTests/Parsers/FastParserTests/IPoker/FormatTests/HandParserHandFormatTests.cs
1,738
C#
using System; using NetOffice; namespace NetOffice.OWC10Api.Enums { /// <summary> /// SupportByVersion OWC10 1 /// </summary> [SupportByVersionAttribute("OWC10", 1)] [EntityTypeAttribute(EntityType.IsEnum)] public enum ChartErrorBarTypeEnum { /// <summary> /// SupportByVersion OWC10 1 /// </summary> /// <remarks>0</remarks> [SupportByVersionAttribute("OWC10", 1)] chErrorBarTypeFixedValue = 0, /// <summary> /// SupportByVersion OWC10 1 /// </summary> /// <remarks>1</remarks> [SupportByVersionAttribute("OWC10", 1)] chErrorBarTypePercent = 1, /// <summary> /// SupportByVersion OWC10 1 /// </summary> /// <remarks>2</remarks> [SupportByVersionAttribute("OWC10", 1)] chErrorBarTypeCustom = 2 } }
24.121212
43
0.63191
[ "MIT" ]
NetOffice/NetOffice
Source/OWC10/Enums/ChartErrorBarTypeEnum.cs
796
C#
// Copyright 2019 Jon Skeet. All rights reserved. // Use of this source code is governed by the Apache License 2.0, // as found in the LICENSE.txt file. using VDrumExplorer.Model.Schema.Physical; namespace VDrumExplorer.Model.Schema.Fields { /// <summary> /// Field representing an instrument within a kit. (More work required...) /// </summary> public sealed class InstrumentField : FieldBase { /// <summary> /// The offset within the same container for the single-byte instrument bank field, /// with a value of 0 for preset instruments and 1 for user samples. /// This is null for modules that don't support user samples /// </summary> internal ModuleOffset? BankOffset { get; } internal InstrumentField(FieldContainer? parent, FieldParameters common, ModuleOffset? bankOffset) : base(parent, common) => BankOffset = bankOffset; internal override FieldBase WithParent(FieldContainer parent) => new InstrumentField(parent, Parameters, BankOffset); } }
39.222222
132
0.68933
[ "Apache-2.0" ]
jskeet/DemoCode
Drums/VDrumExplorer.Model/Schema/Fields/InstrumentField.cs
1,061
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.Diagnostics; using System.Runtime.InteropServices; using Microsoft.Win32.SafeHandles; internal static partial class Interop { internal static partial class Crypto { [LibraryImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_HmacCreate")] internal static partial SafeHmacCtxHandle HmacCreate(ref byte key, int keyLen, IntPtr md); [LibraryImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_HmacDestroy")] internal static partial void HmacDestroy(IntPtr ctx); [LibraryImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_HmacReset")] internal static partial int HmacReset(SafeHmacCtxHandle ctx); internal static int HmacUpdate(SafeHmacCtxHandle ctx, ReadOnlySpan<byte> data, int len) => HmacUpdate(ctx, ref MemoryMarshal.GetReference(data), len); [LibraryImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_HmacUpdate")] private static partial int HmacUpdate(SafeHmacCtxHandle ctx, ref byte data, int len); [LibraryImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_HmacFinal")] internal static partial int HmacFinal(SafeHmacCtxHandle ctx, ref byte data, ref int len); [LibraryImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_HmacCurrent")] internal static partial int HmacCurrent(SafeHmacCtxHandle ctx, ref byte data, ref int len); [LibraryImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_HmacOneShot")] private static unsafe partial int HmacOneShot(IntPtr type, byte* key, int keySize, byte* source, int sourceSize, byte* md, int* mdSize); internal static unsafe int HmacOneShot(IntPtr type, ReadOnlySpan<byte> key, ReadOnlySpan<byte> source, Span<byte> destination) { int size = destination.Length; const int Success = 1; fixed (byte* pKey = key) fixed (byte* pSource = source) fixed (byte* pDestination = destination) { int result = HmacOneShot(type, pKey, key.Length, pSource, source.Length, pDestination, &size); if (result != Success) { Debug.Assert(result == 0); throw CreateOpenSslCryptographicException(); } } return size; } } }
42.898305
144
0.680363
[ "MIT" ]
AUTOMATE-2001/runtime
src/libraries/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.Hmac.cs
2,531
C#
#region License // -------------------------------------------------------------------------------------------------------------------- // <copyright file="ExplicitExpression{T,TProperty}.cs" company="MorseCode Software"> // Copyright (c) 2015 MorseCode Software // </copyright> // <summary> // The MIT License (MIT) // // Copyright (c) 2015 MorseCode Software // // 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. // </summary> // -------------------------------------------------------------------------------------------------------------------- #endregion namespace MorseCode.FrameworkExtensions { using System; using System.Diagnostics.Contracts; using System.Linq.Expressions; /// <summary> /// Represents an explicit property expression created from an expression. /// </summary> /// <typeparam name="T"> /// The type of the object on which to get the property for the expression. /// </typeparam> /// <typeparam name="TProperty"> /// The type of the property returned by the expression. /// </typeparam> /// <remarks> /// Explicit property expressions can be used to prevent expressions from apply a conversion to their return type automatically. /// For instance, if a method expects an expression of type <see cref="System.Linq.Expressions.Expression{TDelegate}"/> where <c>TDelegate</c> is a function returning /// a nullable value-type from an object, then an expression returning a non-nullable property may be passed in as the return type of the /// function will automatically be converted to the nullable type. This class is a way to declare the expression with the exact type of the /// property to ensure no automatic conversions are unknowingly applied. /// </remarks> public class ExplicitExpression<T, TProperty> { #region Fields private readonly Expression<Func<T, TProperty>> expression; #endregion #region Constructors and Destructors /// <summary> /// Initializes a new instance of the <see cref="ExplicitExpression{T,TProperty}"/> class. /// </summary> /// <param name="expression"> /// The expression from which to create the explicit property expression. /// </param> public ExplicitExpression(Expression<Func<T, TProperty>> expression) { Contract.Requires<ArgumentNullException>(expression != null, "expression"); this.expression = expression; } #endregion #region Public Properties /// <summary> /// Gets the expression from which this explicit expression was created. /// </summary> public Expression<Func<T, TProperty>> Expression { get { return this.expression; } } #endregion } }
40.968421
170
0.642343
[ "MIT" ]
jam40jeff/FrameworkExtensions
Source/MorseCode.FrameworkExtensions/_Root/ExplicitExpression{T,TProperty}.cs
3,894
C#
using Microsoft.AspNetCore.Mvc; namespace WebApplication1.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(Name = "GetWeatherForecast")] 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(); } } }
31.151515
110
0.589494
[ "Apache-2.0" ]
shimat/net6_webapi_test_sample
WebApplication1/Controllers/WeatherForecastController.cs
1,028
C#
using AppBlocks.Autofac.Support; using log4net; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Reflection; using System.Text; namespace AppBlocks.Autofac.Tests.KeyedAndNamedServices { [AppBlocksKeyedService("KeyedService2", typeof(IKeyedService))] public class KeyedService2 : IKeyedService { private readonly ILogger<KeyedService2> logger; public KeyedService2(ILogger<KeyedService2> logger) { this.logger = logger; } private static int callCount; public static int GetCallCount() => callCount; public static void ResetCount() => callCount = 0; public void RunKeyedService() { callCount++; if (logger.IsEnabled(LogLevel.Information)) logger.LogInformation($"{nameof(KeyedService2)}.{nameof(RunKeyedService)} called successfully"); } } }
27.705882
112
0.674098
[ "MIT" ]
AdsophicSolutions/AppBlocks.Autofac
src/AppBlocks.Autofac.Tests/KeyedAndNamedServices/KeyedService2.cs
944
C#
// <copyright file=HydraEditorUtils company=Hydra> // Copyright (c) 2015 All Rights Reserved // </copyright> // <author>Christopher Cameron</author> using System; using System.IO; using Hydra.HydraCommon.Editor.Extensions; using Hydra.HydraCommon.Extensions; using Hydra.HydraCommon.Utils; using UnityEditor; using UnityEngine; namespace Hydra.HydraCommon.Editor.Utils { public static class HydraEditorUtils { public const string BROWSE_BUTTON_TEXTURE_NAME = "Browse.tif"; public const float STANDARD_HORIZONTAL_SPACING = 2.0f; public const float AXIS_LABEL_WIDTH = 16.0f; public const float BROWSE_BUTTON_WIDTH = 32.0f; public static readonly GUIContent s_AxisXLabel = new GUIContent("X"); public static readonly GUIContent s_AxisYLabel = new GUIContent("Y"); private static string[] s_LayerNames; private static AxisInfo[] s_AxesInfo; private static string[] s_AxesNames; #region Methods /// <summary> /// Creates a rect that prevents the mouse from effecting the scene. /// </summary> /// <param name="position">Position.</param> /// <param name="controlId">Control identifier.</param> public static void EatMouseInput(Rect position, int controlId) { controlId = GUIUtility.GetControlID(controlId, FocusType.Native, position); switch (Event.current.GetTypeForControl(controlId)) { case EventType.MouseDown: if (position.Contains(Event.current.mousePosition)) { GUIUtility.hotControl = controlId; Event.current.Use(); } break; case EventType.MouseUp: if (GUIUtility.hotControl == controlId) { GUIUtility.hotControl = 0; Event.current.Use(); } break; case EventType.MouseDrag: if (GUIUtility.hotControl == controlId) Event.current.Use(); break; case EventType.ScrollWheel: if (position.Contains(Event.current.mousePosition)) Event.current.Use(); break; } } /// <summary> /// Draws a Save File field. /// </summary> /// <returns>The save path.</returns> /// <param name="position">Position.</param> /// <param name="label">Label.</param> /// <param name="path">Path.</param> /// <param name="extention">Extention.</param> public static string SaveFileField(Rect position, GUIContent label, string path, string extention) { Rect content = new Rect(position); content.width -= BROWSE_BUTTON_WIDTH; content.width -= STANDARD_HORIZONTAL_SPACING; EditorGUI.TextField(content, label, path); Rect buttonRect = new Rect(content); buttonRect.x += content.width + STANDARD_HORIZONTAL_SPACING; buttonRect.width = BROWSE_BUTTON_WIDTH; Texture2D buttonTexture = EditorResourceCache.GetResource<Texture2D>("HydraCommon", "Textures", BROWSE_BUTTON_TEXTURE_NAME); GUIStyle style = HydraEditorGUIStyles.PictureButtonStyle(buttonRect); bool pressed = DrawUnindented(() => GUI.Button(buttonRect, buttonTexture, style)); if (pressed) path = SaveFilePanel(label, path, extention); return path; } /// <summary> /// Shows the Save File panel. /// </summary> /// <returns>The new path.</returns> /// <param name="title">Title.</param> /// <param name="path">Path.</param> /// <param name="extention">Extention.</param> public static string SaveFilePanel(GUIContent title, string path, string extention) { path = Path.ChangeExtension(path, extention); string directory = string.IsNullOrEmpty(path) ? string.Empty : Path.GetDirectoryName(path); string defaultName = string.IsNullOrEmpty(path) ? string.Empty : Path.GetFileName(path); return EditorUtility.SaveFilePanel(title.text, directory, defaultName, extention); } /// <summary> /// Draws a scene field. /// </summary> /// <param name="position">Position.</param> /// <param name="label">Label.</param> /// <param name="prop">Property.</param> /// <param name="style">Style.</param> public static void SceneField(Rect position, GUIContent label, SerializedProperty prop, GUIStyle style) { label = EditorGUI.BeginProperty(position, label, prop); EditorBuildSettingsScene[] scenes = EditorSceneUtils.GetEnabledScenes(); string[] names = EditorSceneUtils.GetSceneNames(scenes); EditorGUI.BeginChangeCheck(); int selected = EditorGUI.Popup(position, label.text, GetSceneIndex(prop, scenes), names, style); EditorBuildSettingsScene value = (selected < scenes.Length) ? scenes[selected] : null; if (EditorGUI.EndChangeCheck()) prop.stringValue = (value != null) ? AssetDatabase.AssetPathToGUID(value.path) : string.Empty; EditorGUI.EndProperty(); } /// <summary> /// Gets the current scene index for the scene property. /// </summary> /// <returns>The scene index.</returns> /// <param name="prop">Property.</param> /// <param name="scenes">Scenes.</param> private static int GetSceneIndex(SerializedProperty prop, EditorBuildSettingsScene[] scenes) { for (int index = 0; index < scenes.Length; index++) { string path = scenes[index].path; string guid = AssetDatabase.AssetPathToGUID(path); if (guid == prop.stringValue) return index; } try { return EditorSceneUtils.GetSceneIndex(EditorApplication.currentScene); } catch (ArgumentOutOfRangeException) { return 0; } } /// <summary> /// Draws an axis input field. /// </summary> /// <param name="position">Position.</param> /// <param name="label">Label.</param> /// <param name="prop">Property.</param> public static void AxisInputField(Rect position, GUIContent label, SerializedProperty prop, GUIStyle style) { label = EditorGUI.BeginProperty(position, label, prop); InputUtils.GetAxesInfo(ref s_AxesInfo); Array.Resize(ref s_AxesNames, s_AxesInfo.Length); int selected = 0; for (int index = 0; index < s_AxesInfo.Length; index++) { string name = s_AxesInfo[index].name; if (name == prop.stringValue) selected = index; s_AxesNames[index] = name; } EditorGUI.BeginChangeCheck(); selected = EditorGUI.Popup(position, label.text, selected, s_AxesNames, style); string value = s_AxesNames[selected]; if (EditorGUI.EndChangeCheck()) prop.stringValue = value; EditorGUI.EndProperty(); } /// <summary> /// Draws a texture field. /// </summary> /// <param name="position">Position.</param> /// <param name="label">Label.</param> /// <param name="prop">Property.</param> public static void TextureField(Rect position, GUIContent label, SerializedProperty prop) { TextureField(position, label, prop, false); } /// <summary> /// Draws a texture field. /// </summary> /// <param name="position">Position.</param> /// <param name="label">Label.</param> /// <param name="prop">Property.</param> /// <param name="readable">If set to <c>true</c> readable.</param> public static void TextureField(Rect position, GUIContent label, SerializedProperty prop, bool readable) { label = EditorGUI.BeginProperty(position, label, prop); Texture texture = EditorGUI.ObjectField(position, label, prop.objectReferenceValue, typeof(Texture), false) as Texture; if (readable && texture != null && !(texture as Texture2D).IsReadable()) { string warning = string.Format("Texture {0} is not readable.", texture.name); Debug.LogWarning(warning); texture = null; } if (texture != prop.objectReferenceValue) prop.objectReferenceValue = texture; EditorGUI.EndProperty(); } /// <summary> /// Draws an int field for a property, using the validator to process the new value. /// </summary> /// <param name="position">Position.</param> /// <param name="label">Label.</param> /// <param name="prop">Property.</param> /// <param name="validator">Validator.</param> public static void ValidateIntField(Rect position, GUIContent label, SerializedProperty prop, Func<int, int> validator) { label = EditorGUI.BeginProperty(position, label, prop); EditorGUI.BeginChangeCheck(); int value = EditorGUI.IntField(position, label, prop.intValue); if (EditorGUI.EndChangeCheck()) prop.intValue = validator(value); EditorGUI.EndProperty(); } /// <summary> /// Draws a float field for a property, using the validator to process the new value. /// </summary> /// <param name="position">Position.</param> /// <param name="label">Label.</param> /// <param name="prop">Property.</param> /// <param name="validator">Validator.</param> public static void ValidateFloatField(Rect position, GUIContent label, SerializedProperty prop, Func<float, float> validator) { label = EditorGUI.BeginProperty(position, label, prop); EditorGUI.BeginChangeCheck(); float value = EditorGUI.FloatField(position, label, prop.floatValue); if (EditorGUI.EndChangeCheck()) prop.floatValue = validator(value); EditorGUI.EndProperty(); } /// <summary> /// Draws a Vector3 field for a property, using the validator to process the new value. /// </summary> /// <param name="position">Position.</param> /// <param name="label">Label.</param> /// <param name="prop">Property.</param> /// <param name="validator">Validator.</param> public static void ValidateVector3Field(Rect position, GUIContent label, SerializedProperty prop, Func<Vector3, Vector3> validator) { label = EditorGUI.BeginProperty(position, label, prop); EditorGUI.BeginChangeCheck(); bool wide = EditorGUIUtility.wideMode; EditorGUIUtility.wideMode = true; Vector3 value = EditorGUI.Vector3Field(position, label, prop.vector3Value); if (EditorGUI.EndChangeCheck()) prop.vector3Value = validator(value); EditorGUIUtility.wideMode = wide; EditorGUI.EndProperty(); } /// <summary> /// Draws two integer properties, using the validator to process the new values. /// </summary> /// <param name="position">Position.</param> /// <param name="label">Label.</param> /// <param name="propA">Property a.</param> /// <param name="propB">Property b.</param> /// <param name="validator">Validator.</param> public static void Validate2IntField(Rect position, GUIContent label, SerializedProperty propA, SerializedProperty propB, Func<int, int> validator) { Rect content = EditorGUI.PrefixLabel(position, GUIUtility.GetControlID(FocusType.Passive), label); Rect halfContent = new Rect(content); halfContent.width -= STANDARD_HORIZONTAL_SPACING; halfContent.width /= 2.0f; float oldLabelWidth = EditorGUIUtility.labelWidth; EditorGUIUtility.labelWidth = AXIS_LABEL_WIDTH; DrawUnindented(() => ValidateIntField(halfContent, s_AxisXLabel, propA, validator)); halfContent.x += halfContent.width + STANDARD_HORIZONTAL_SPACING; DrawUnindented(() => ValidateIntField(halfContent, s_AxisYLabel, propB, validator)); EditorGUIUtility.labelWidth = oldLabelWidth; } /// <summary> /// Behaves like a boolean field but draws a textured button. /// </summary> /// <param name="position">Position.</param> /// <param name="label">Label.</param> /// <param name="prop">Property.</param> /// <param name="trueTexture">True texture.</param> /// <param name="falseTexture">False texture.</param> public static void ToggleTexturesField(Rect position, GUIContent label, SerializedProperty prop, Texture2D trueTexture, Texture2D falseTexture) { label = EditorGUI.BeginProperty(position, label, prop); Rect contentPosition = EditorGUI.PrefixLabel(position, GUIUtility.GetControlID(FocusType.Passive), label); contentPosition.width = contentPosition.height; GUIStyle style = HydraEditorGUIStyles.TextureButtonStyle(contentPosition); Texture2D buttonTexture = prop.boolValue ? trueTexture : falseTexture; bool pressed = GUI.Button(contentPosition, buttonTexture, style); if (pressed) { prop.boolValue = !prop.boolValue; GUI.changed = true; } EditorGUI.EndProperty(); } /// <summary> /// Shorthand toggle left field. /// </summary> /// <param name="position">Position.</param> /// <param name="label">Label.</param> /// <param name="prop">Property.</param> public static void ToggleLeftField(Rect position, GUIContent label, SerializedProperty prop) { label = EditorGUI.BeginProperty(position, label, prop); EditorGUI.BeginChangeCheck(); bool value = EditorGUI.ToggleLeft(position, label, prop.boolValue); if (EditorGUI.EndChangeCheck()) prop.boolValue = value; EditorGUI.EndProperty(); } /// <summary> /// Draws a LayerMask field with the given style. /// </summary> /// <param name="position">Position.</param> /// <param name="label">Label.</param> /// <param name="prop">Property.</param> /// <param name="style">Style.</param> public static void LayerMaskField(Rect position, GUIContent label, SerializedProperty prop, GUIStyle style) { label = EditorGUI.BeginProperty(position, label, prop); EditorGUI.BeginChangeCheck(); LayerMaskUtils.GetMaskFieldNames(ref s_LayerNames); int mappedMask = LayerMaskUtils.MapToMaskField(prop.intValue); mappedMask = EditorGUI.MaskField(position, label, mappedMask, s_LayerNames, style); if (EditorGUI.EndChangeCheck()) { LayerMask newMask = LayerMaskUtils.MapFromMaskField(mappedMask); prop.SetMask(newMask); } EditorGUI.EndProperty(); } /// <summary> /// Shorthand enum popup field with a style. /// </summary> /// <param name="position">Position.</param> /// <param name="label">Label.</param> /// <param name="prop">Property.</param> /// <param name="style">Style.</param> /// <typeparam name="T">The enum type.</typeparam> public static void EnumPopupField<T>(Rect position, GUIContent label, SerializedProperty prop, GUIStyle style) { label = EditorGUI.BeginProperty(position, label, prop); EditorGUI.BeginChangeCheck(); Enum enumValue = (Enum)Enum.ToObject(typeof(T), prop.enumValueIndex); enumValue = EditorGUI.EnumPopup(position, label, enumValue, style); if (EditorGUI.EndChangeCheck()) prop.enumValueIndex = Convert.ToInt32(enumValue); EditorGUI.EndProperty(); } /// <summary> /// Draws a single float field and applies that value to all of the axis on the Vector3 /// property. /// </summary> /// <param name="position">Position.</param> /// <param name="label">Label.</param> /// <param name="prop">Property.</param> public static void UniformVector3Field(Rect position, GUIContent label, SerializedProperty prop) { label = EditorGUI.BeginProperty(position, label, prop); EditorGUI.BeginChangeCheck(); float axis = EditorGUI.FloatField(position, label, prop.vector3Value.x); if (EditorGUI.EndChangeCheck()) prop.vector3Value = Vector3.one * axis; EditorGUI.EndProperty(); } /// <summary> /// Draws a Vector3 field. For some reason Unity throws an error with vector3 property /// fields, so this is a workaround. /// </summary> /// <param name="position">Position.</param> /// <param name="label">Label.</param> /// <param name="prop">Property.</param> public static void Vector3Field(Rect position, GUIContent label, SerializedProperty prop) { label = EditorGUI.BeginProperty(position, label, prop); EditorGUI.BeginChangeCheck(); bool wide = EditorGUIUtility.wideMode; EditorGUIUtility.wideMode = true; Vector3 newValue = EditorGUI.Vector3Field(position, label, prop.vector3Value); if (EditorGUI.EndChangeCheck()) prop.vector3Value = newValue; EditorGUIUtility.wideMode = wide; EditorGUI.EndProperty(); } /// <summary> /// Draws a Vector3 field, tidying to 2 decimal places. /// </summary> /// <param name="position">Position.</param> /// <param name="label">Label.</param> /// <param name="prop">Property.</param> public static void Vector3Field2Dp(Rect position, GUIContent label, SerializedProperty prop) { label = EditorGUI.BeginProperty(position, label, prop); EditorGUI.LabelField(position, label); Rect content = new Rect(position); content.x += EditorGUIUtility.labelWidth; content.width -= EditorGUIUtility.labelWidth; content.width = content.width - STANDARD_HORIZONTAL_SPACING * 2.0f; content.width /= 3.0f; float oldLabelWidth = EditorGUIUtility.labelWidth; EditorGUIUtility.labelWidth = AXIS_LABEL_WIDTH; EditorGUI.BeginChangeCheck(); Vector3 value = prop.vector3Value; float x = DrawUnindented(() => FloatField2Dp(content, new GUIContent("X"), value.x)); content.x += content.width + STANDARD_HORIZONTAL_SPACING; float y = DrawUnindented(() => FloatField2Dp(content, new GUIContent("Y"), value.y)); content.x += content.width + STANDARD_HORIZONTAL_SPACING; float z = DrawUnindented(() => FloatField2Dp(content, new GUIContent("Z"), value.z)); if (EditorGUI.EndChangeCheck()) prop.vector3Value = new Vector3(x, y, z); EditorGUIUtility.labelWidth = oldLabelWidth; EditorGUI.EndProperty(); } /// <summary> /// Draws a float field with 2 decimal places. /// </summary> /// <returns>The new value.</returns> /// <param name="position">Position.</param> /// <param name="label">Label.</param> /// <param name="value">Value.</param> public static float FloatField2Dp(Rect position, GUIContent label, float value) { string floatString = value.ToString("0.00"); floatString = TrimDecimalPlaces(floatString); string input = EditorGUI.TextField(position, label, floatString); if (input != floatString) { float inputFloat; bool valid = float.TryParse(input, out inputFloat); if (valid) value = inputFloat; } return value; } /// <summary> /// Removes trailing "." and "0" characters. /// </summary> /// <returns>The trimmed string.</returns> /// <param name="input">Input.</param> private static string TrimDecimalPlaces(string input) { if (input.Contains(".")) { input = input.TrimEnd('0'); input = input.TrimEnd('.'); } return input; } /// <summary> /// Draws a texture in the inspector. /// </summary> /// <param name="position">Position.</param> /// <param name="texture">Texture.</param> public static void PreviewTexture(Rect position, Texture2D texture) { EditorGUI.DrawPreviewTexture(position, texture); GUI.Box(position, GUIContent.none, HydraEditorGUIStyles.previewTextureStyle); } /// <summary> /// Clears the indentation level and calls the draw method. /// </summary> /// <param name="drawMethod">Draw method.</param> public static void DrawUnindented(Action drawMethod) { int oldIndent = EditorGUI.indentLevel; EditorGUI.indentLevel = 0; drawMethod(); EditorGUI.indentLevel = oldIndent; } /// <summary> /// Clears the indentation level and calls the draw method. /// </summary> /// <param name="drawMethod">Draw method.</param> /// <typeparam name="T">The return type.</typeparam> public static T DrawUnindented<T>(Func<T> drawMethod) { int oldIndent = EditorGUI.indentLevel; EditorGUI.indentLevel = 0; T result = drawMethod(); EditorGUI.indentLevel = oldIndent; return result; } /// <summary> /// Draws the foldout. /// </summary> /// <param name="title">Title.</param> /// <param name="position">Position.</param> public static bool DrawFoldout(GUIContent title, Rect position) { bool state = EditorPrefsUtils.GetFoldoutState(title); bool newState = EditorGUI.Foldout(position, state, title); if (newState != state) EditorPrefsUtils.SetFoldoutState(title, newState); return newState; } #endregion } }
31.488
121
0.692835
[ "BSD-3-Clause" ]
TeamSpatch/EndoWars
Assets/Hydra/HydraCommon/Scripts/Editor/Utils/HydraEditorUtils.cs
19,680
C#
using Jering.Javascript.NodeJS; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Threading.Tasks; namespace Codeuctivity.PdfjsSharp { /// <summary> /// Rasterizes PDFs, Depands on node /// </summary> public class Rasterizer : PdfJsWrapper, IRasterizer { /// <summary> /// Converts a pdf to pngs /// </summary> /// <param name="pathToPdf"></param> /// <param name="pathToPngOutput">Prefix of file path to pngs created for each page of pdf. E.g. c:\temp\PdfPage will result in c:\temp\PdfPage1.png and c:\temp\PdfPage2.png for a Pdf with two pages.</param> /// <returns>Collection of paths to pngs for each page in the pdf</returns> public async Task<IReadOnlyList<string>> ConvertToPngAsync(string pathToPdf, string pathToPngOutput) { await InitNodeModules().ConfigureAwait(false); var assembly = Assembly.GetExecutingAssembly(); var stream = assembly.GetManifestResourceStream("Codeuctivity.PdfjsSharp.Rasterize.js"); using var reader = new StreamReader(stream!); var script = reader.ReadToEnd(); var scriptWithAbsolutePathsToNodeModules = script.Replace("MagicPrefix", pathToNodeModules); var pdfRasterizerJsCodeToExecute = scriptWithAbsolutePathsToNodeModules; var pathsToPngOfEachPage = new List<string>(); var pageQuantity = await StaticNodeJSService.InvokeFromStringAsync<int>(pdfRasterizerJsCodeToExecute, args: new object[] { pathToPdf, pathToPngOutput }).ConfigureAwait(false); for (var pagenumber = 1; pagenumber <= pageQuantity; pagenumber++) { pathsToPngOfEachPage.Add($"{pathToPngOutput}{pagenumber}.png"); } return pathsToPngOfEachPage.AsReadOnly(); } } }
43.790698
215
0.669676
[ "Apache-2.0" ]
Codeuctivity/PdfjsSharp
PdfjsSharp/Rasterizer.cs
1,885
C#
// Licensed to Elasticsearch B.V under // one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information using System; using System.Collections.Generic; using System.Diagnostics; using System.Threading.Tasks; using Elastic.Apm.Api; using Elastic.Apm.Api.Constraints; using Elastic.Apm.Libraries.Newtonsoft.Json; namespace Elastic.Apm.Model { /// <summary> /// A transaction implementation which is used when the agent is not recording (either recording=false or enabled=false). /// It has no knowledge about the PayloadSender and will be never sent to APM Server. /// It only executes minimum amount of code and isn't guaranteed that values you set on it will be kept. /// </summary> internal class NoopTransaction : ITransaction { private static readonly Context ReusableContextInstance = new Context(); private readonly ICurrentExecutionSegmentsContainer _currentExecutionSegmentsContainer; private readonly Lazy<Dictionary<string, string>> _custom = new Lazy<Dictionary<string, string>>(); private readonly Lazy<Dictionary<string, string>> _labels = new Lazy<Dictionary<string, string>>(); public NoopTransaction(string name, string type, ICurrentExecutionSegmentsContainer currentExecutionSegmentsContainer) { Name = name; Type = type; _currentExecutionSegmentsContainer = currentExecutionSegmentsContainer; _currentExecutionSegmentsContainer.CurrentTransaction = this; } public Context Context => ReusableContextInstance; public Dictionary<string, string> Custom => _custom.Value; public double? Duration { get; set; } [MaxLength] public string Id { get; } public bool IsSampled => false; public Dictionary<string, string> Labels => _labels.Value; [MaxLength] public string Name { get; set; } public Outcome Outcome { get; set; } public DistributedTracingData OutgoingDistributedTracingData { get; } [JsonProperty("parent_id")] [MaxLength] public string ParentId { get; } [MaxLength] public string Result { get; set; } [JsonProperty("span_count")] public SpanCount SpanCount { get; } [JsonProperty("trace_id")] [MaxLength] public string TraceId { get; } [MaxLength] public string Type { get; set; } public void CaptureError(string message, string culprit, StackFrame[] frames, string parentId = null, Dictionary<string, Label> labels = null ) { } public void CaptureException(Exception exception, string culprit = null, bool isHandled = false, string parentId = null, Dictionary<string, Label> labels = null ) { } public void CaptureSpan(string name, string type, Action<ISpan> capturedAction, string subType = null, string action = null) => ExecutionSegmentCommon.CaptureSpan(new NoopSpan(name, type, subType, action, _currentExecutionSegmentsContainer), capturedAction); public void CaptureSpan(string name, string type, Action capturedAction, string subType = null, string action = null) => ExecutionSegmentCommon.CaptureSpan(new NoopSpan(name, type, subType, action, _currentExecutionSegmentsContainer), capturedAction); public T CaptureSpan<T>(string name, string type, Func<ISpan, T> func, string subType = null, string action = null) => ExecutionSegmentCommon.CaptureSpan(new NoopSpan(name, type, subType, action, _currentExecutionSegmentsContainer), func); public T CaptureSpan<T>(string name, string type, Func<T> func, string subType = null, string action = null) => ExecutionSegmentCommon.CaptureSpan(new NoopSpan(name, type, subType, action, _currentExecutionSegmentsContainer), func); public Task CaptureSpan(string name, string type, Func<Task> func, string subType = null, string action = null) => ExecutionSegmentCommon.CaptureSpan(new NoopSpan(name, type, subType, action, _currentExecutionSegmentsContainer), func); public Task CaptureSpan(string name, string type, Func<ISpan, Task> func, string subType = null, string action = null) => ExecutionSegmentCommon.CaptureSpan(new NoopSpan(name, type, subType, action, _currentExecutionSegmentsContainer), func); public Task<T> CaptureSpan<T>(string name, string type, Func<Task<T>> func, string subType = null, string action = null) => ExecutionSegmentCommon.CaptureSpan(new NoopSpan(name, type, subType, action, _currentExecutionSegmentsContainer), func); public Task<T> CaptureSpan<T>(string name, string type, Func<ISpan, Task<T>> func, string subType = null, string action = null) => ExecutionSegmentCommon.CaptureSpan(new NoopSpan(name, type, subType, action, _currentExecutionSegmentsContainer), func); public void End() => _currentExecutionSegmentsContainer.CurrentTransaction = null; public void SetLabel(string key, string value) { } public void SetLabel(string key, bool value) { } public void SetLabel(string key, double value) { } public void SetLabel(string key, int value) { } public void SetLabel(string key, long value) { } public void SetLabel(string key, decimal value) { } public ISpan StartSpan(string name, string type, string subType = null, string action = null) => new NoopSpan(name, type, subType, action, _currentExecutionSegmentsContainer); public string EnsureParentId() => string.Empty; public void SetService(string serviceName, string serviceVersion) { } public bool TryGetLabel<T>(string key, out T value) { value = default; return false; } public void CaptureErrorLog(ErrorLog errorLog, string parentId = null, Exception exception = null, Dictionary<string, Label> labels = null ) { } } }
41.533333
143
0.757446
[ "Apache-2.0" ]
AAimson/apm-agent-dotnet
src/Elastic.Apm/Model/NoopTransaction.cs
5,609
C#
//----------------------------------------------------------------------- // <copyright file="ListFormatter.cs" company="Sirenix IVS"> // Copyright (c) 2018 Sirenix IVS // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> //----------------------------------------------------------------------- using TWC.OdinSerializer; [assembly: RegisterFormatter(typeof(ListFormatter<>))] namespace TWC.OdinSerializer { using System; using System.Collections.Generic; /// <summary> /// Custom generic formatter for the generic type definition <see cref="List{T}"/>. /// </summary> /// <typeparam name="T">The element type of the formatted list.</typeparam> /// <seealso cref="BaseFormatter{System.Collections.Generic.List{T}}" /> public class ListFormatter<T> : BaseFormatter<List<T>> { private static readonly Serializer<T> TSerializer = Serializer.Get<T>(); static ListFormatter() { // This exists solely to prevent IL2CPP code stripping from removing the generic type's instance constructor // which it otherwise seems prone to do, regardless of what might be defined in any link.xml file. new ListFormatter<int>(); } public ListFormatter() { } /// <summary> /// Returns null. /// </summary> /// <returns> /// A null value. /// </returns> protected override List<T> GetUninitializedObject() { return null; } /// <summary> /// Provides the actual implementation for deserializing a value of type <see cref="T" />. /// </summary> /// <param name="value">The uninitialized value to serialize into. This value will have been created earlier using <see cref="BaseFormatter{T}.GetUninitializedObject" />.</param> /// <param name="reader">The reader to deserialize with.</param> protected override void DeserializeImplementation(ref List<T> value, IDataReader reader) { string name; var entry = reader.PeekEntry(out name); if (entry == EntryType.StartOfArray) { try { long length; reader.EnterArray(out length); value = new List<T>((int)length); // We must remember to register the list reference ourselves, since we return null in GetUninitializedObject this.RegisterReferenceID(value, reader); // There aren't any OnDeserializing callbacks on lists. // Hence we don't invoke this.InvokeOnDeserializingCallbacks(value, reader, context); for (int i = 0; i < length; i++) { if (reader.PeekEntry(out name) == EntryType.EndOfArray) { reader.Context.Config.DebugContext.LogError("Reached end of array after " + i + " elements, when " + length + " elements were expected."); break; } value.Add(TSerializer.ReadValue(reader)); if (reader.IsInArrayNode == false) { // Something has gone wrong reader.Context.Config.DebugContext.LogError("Reading array went wrong. Data dump: " + reader.GetDataDump()); break; } } } finally { reader.ExitArray(); } } else { reader.SkipEntry(); } } /// <summary> /// Provides the actual implementation for serializing a value of type <see cref="T" />. /// </summary> /// <param name="value">The value to serialize.</param> /// <param name="writer">The writer to serialize with.</param> protected override void SerializeImplementation(ref List<T> value, IDataWriter writer) { try { writer.BeginArrayNode(value.Count); for (int i = 0; i < value.Count; i++) { try { TSerializer.WriteValue(value[i], writer); } catch (Exception ex) { writer.Context.Config.DebugContext.LogException(ex); } } } finally { writer.EndArrayNode(); } } } }
37.411348
186
0.516967
[ "MIT" ]
JohnMurwin/NaturalSelectionSimulation
Assets/Plugins/TileWorldCreator/Code/TileWorldCreator.OdinSerializer/Core/Formatters/ListFormatter.cs
5,277
C#
#pragma warning disable 0472 using System; using System.Text; using System.IO; using System.Collections; using System.ComponentModel; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using System.Xml.Serialization; using BLToolkit.Aspects; using BLToolkit.DataAccess; using BLToolkit.EditableObjects; using BLToolkit.Data; using BLToolkit.Data.DataProvider; using BLToolkit.Mapping; using BLToolkit.Reflection; using bv.common.Configuration; using bv.common.Enums; using bv.common.Core; using bv.model.BLToolkit; using bv.model.Model; using bv.model.Helpers; using bv.model.Model.Extenders; using bv.model.Model.Core; using bv.model.Model.Handlers; using bv.model.Model.Validators; using eidss.model.Core; using eidss.model.Enums; namespace eidss.model.Schema { [XmlType(AnonymousType = true)] public abstract partial class VectorType2PensideTest : EditableObject<VectorType2PensideTest> , IObject , IDisposable , ILookupUsage { [MapField(_str_idfPensideTestTypeForVectorType), NonUpdatable, PrimaryKey] public abstract Int64 idfPensideTestTypeForVectorType { get; set; } [LocalizedDisplayName(_str_idfsPensideTestName)] [MapField(_str_idfsPensideTestName)] public abstract Int64 idfsPensideTestName { get; set; } protected Int64 idfsPensideTestName_Original { get { return ((EditableValue<Int64>)((dynamic)this)._idfsPensideTestName).OriginalValue; } } protected Int64 idfsPensideTestName_Previous { get { return ((EditableValue<Int64>)((dynamic)this)._idfsPensideTestName).PreviousValue; } } [LocalizedDisplayName(_str_idfsVectorType)] [MapField(_str_idfsVectorType)] public abstract Int64 idfsVectorType { get; set; } protected Int64 idfsVectorType_Original { get { return ((EditableValue<Int64>)((dynamic)this)._idfsVectorType).OriginalValue; } } protected Int64 idfsVectorType_Previous { get { return ((EditableValue<Int64>)((dynamic)this)._idfsVectorType).PreviousValue; } } #region Set/Get values #region filed_info definifion protected class field_info { internal string _name; internal string _formname; internal string _type; internal Func<VectorType2PensideTest, object> _get_func; internal Action<VectorType2PensideTest, string> _set_func; internal Action<VectorType2PensideTest, VectorType2PensideTest, CompareModel> _compare_func; } internal const string _str_Parent = "Parent"; internal const string _str_IsNew = "IsNew"; internal const string _str_idfPensideTestTypeForVectorType = "idfPensideTestTypeForVectorType"; internal const string _str_idfsPensideTestName = "idfsPensideTestName"; internal const string _str_idfsVectorType = "idfsVectorType"; internal const string _str_PensideTest = "PensideTest"; private static readonly field_info[] _field_infos = { new field_info { _name = _str_idfPensideTestTypeForVectorType, _formname = _str_idfPensideTestTypeForVectorType, _type = "Int64", _get_func = o => o.idfPensideTestTypeForVectorType, _set_func = (o, val) => { var newval = ParsingHelper.ParseInt64(val); if (o.idfPensideTestTypeForVectorType != newval) o.idfPensideTestTypeForVectorType = newval; }, _compare_func = (o, c, m) => { if (o.idfPensideTestTypeForVectorType != c.idfPensideTestTypeForVectorType || o.IsRIRPropChanged(_str_idfPensideTestTypeForVectorType, c)) m.Add(_str_idfPensideTestTypeForVectorType, o.ObjectIdent + _str_idfPensideTestTypeForVectorType, o.ObjectIdent2 + _str_idfPensideTestTypeForVectorType, o.ObjectIdent3 + _str_idfPensideTestTypeForVectorType, "Int64", o.idfPensideTestTypeForVectorType == null ? "" : o.idfPensideTestTypeForVectorType.ToString(), o.IsReadOnly(_str_idfPensideTestTypeForVectorType), o.IsInvisible(_str_idfPensideTestTypeForVectorType), o.IsRequired(_str_idfPensideTestTypeForVectorType)); } }, new field_info { _name = _str_idfsPensideTestName, _formname = _str_idfsPensideTestName, _type = "Int64", _get_func = o => o.idfsPensideTestName, _set_func = (o, val) => { var newval = ParsingHelper.ParseInt64(val); if (o.idfsPensideTestName != newval) o.PensideTest = o.PensideTestLookup.FirstOrDefault(c => c.idfsBaseReference == newval); if (o.idfsPensideTestName != newval) o.idfsPensideTestName = newval; }, _compare_func = (o, c, m) => { if (o.idfsPensideTestName != c.idfsPensideTestName || o.IsRIRPropChanged(_str_idfsPensideTestName, c)) m.Add(_str_idfsPensideTestName, o.ObjectIdent + _str_idfsPensideTestName, o.ObjectIdent2 + _str_idfsPensideTestName, o.ObjectIdent3 + _str_idfsPensideTestName, "Int64", o.idfsPensideTestName == null ? "" : o.idfsPensideTestName.ToString(), o.IsReadOnly(_str_idfsPensideTestName), o.IsInvisible(_str_idfsPensideTestName), o.IsRequired(_str_idfsPensideTestName)); } }, new field_info { _name = _str_idfsVectorType, _formname = _str_idfsVectorType, _type = "Int64", _get_func = o => o.idfsVectorType, _set_func = (o, val) => { var newval = ParsingHelper.ParseInt64(val); if (o.idfsVectorType != newval) o.idfsVectorType = newval; }, _compare_func = (o, c, m) => { if (o.idfsVectorType != c.idfsVectorType || o.IsRIRPropChanged(_str_idfsVectorType, c)) m.Add(_str_idfsVectorType, o.ObjectIdent + _str_idfsVectorType, o.ObjectIdent2 + _str_idfsVectorType, o.ObjectIdent3 + _str_idfsVectorType, "Int64", o.idfsVectorType == null ? "" : o.idfsVectorType.ToString(), o.IsReadOnly(_str_idfsVectorType), o.IsInvisible(_str_idfsVectorType), o.IsRequired(_str_idfsVectorType)); } }, new field_info { _name = _str_PensideTest, _formname = _str_PensideTest, _type = "Lookup", _get_func = o => { if (o.PensideTest == null) return null; return o.PensideTest.idfsBaseReference; }, _set_func = (o, val) => { o.PensideTest = o.PensideTestLookup.Where(c => c.idfsBaseReference.ToString() == val).SingleOrDefault(); }, _compare_func = (o, c, m) => { if (o.idfsPensideTestName != c.idfsPensideTestName || o.IsRIRPropChanged(_str_PensideTest, c)) { m.Add(_str_PensideTest, o.ObjectIdent + _str_PensideTest, o.ObjectIdent2 + _str_PensideTest, o.ObjectIdent3 + _str_PensideTest, "Lookup", o.idfsPensideTestName == null ? "" : o.idfsPensideTestName.ToString(), o.IsReadOnly(_str_PensideTest), o.IsInvisible(_str_PensideTest), o.IsRequired(_str_PensideTest)); } } }, new field_info { _name = _str_PensideTest + "Lookup", _formname = _str_PensideTest + "Lookup", _type = "LookupContent", _get_func = o => o.PensideTestLookup, _set_func = (o, val) => { }, _compare_func = (o, c, m) => { }, }, new field_info() }; #endregion private string _getType(string name) { var i = _field_infos.FirstOrDefault(n => n._name == name); return i == null ? "" : i._type; } private object _getValue(string name) { var i = _field_infos.FirstOrDefault(n => n._name == name); return i == null ? null : i._get_func(this); } private void _setValue(string name, string val) { var i = _field_infos.FirstOrDefault(n => n._name == name); if (i != null) i._set_func(this, val); } internal CompareModel _compare(IObject o, CompareModel ret) { if (ret == null) ret = new CompareModel(); if (o == null) return ret; VectorType2PensideTest obj = (VectorType2PensideTest)o; foreach (var i in _field_infos) if (i != null && i._compare_func != null) i._compare_func(this, obj, ret); return ret; } #endregion [LocalizedDisplayName(_str_PensideTest)] [Relation(typeof(BaseReference), eidss.model.Schema.BaseReference._str_idfsBaseReference, _str_idfsPensideTestName)] public BaseReference PensideTest { get { return _PensideTest == null ? null : ((long)_PensideTest.Key == 0 ? null : _PensideTest); } set { var oldVal = _PensideTest; _PensideTest = value == null ? null : ((long) value.Key == 0 ? null : value); if (_PensideTest != oldVal) { if (idfsPensideTestName != (_PensideTest == null ? new Int64() : (Int64)_PensideTest.idfsBaseReference)) idfsPensideTestName = _PensideTest == null ? new Int64() : (Int64)_PensideTest.idfsBaseReference; OnPropertyChanged(_str_PensideTest); } } } private BaseReference _PensideTest; public BaseReferenceList PensideTestLookup { get { return _PensideTestLookup; } } private BaseReferenceList _PensideTestLookup = new BaseReferenceList("rftPensideTestType"); private BvSelectList _getList(string name) { switch(name) { case _str_PensideTest: return new BvSelectList(PensideTestLookup, eidss.model.Schema.BaseReference._str_idfsBaseReference, null, PensideTest, _str_idfsPensideTestName); } return null; } protected CacheScope m_CS; protected Accessor _getAccessor() { return Accessor.Instance(m_CS); } private IObjectPermissions m_permissions = null; internal IObjectPermissions _permissions { get { return m_permissions; } set { m_permissions = value; } } internal string m_ObjectName = "VectorType2PensideTest"; #region Parent and Clone supporting [XmlIgnore] public IObject Parent { get { return m_Parent; } set { m_Parent = value; /*OnPropertyChanged(_str_Parent);*/ } } private IObject m_Parent; internal void _setParent() { } partial void Cloned(); partial void ClonedWithSetup(); public override object Clone() { var ret = base.Clone() as VectorType2PensideTest; ret.Cloned(); ret.m_Parent = this.Parent; ret.m_IsMarkedToDelete = this.m_IsMarkedToDelete; ret.m_IsForcedToDelete = this.m_IsForcedToDelete; ret._setParent(); if (this.IsDirty && !ret.IsDirty) ret.SetChange(); else if (!this.IsDirty && ret.IsDirty) ret.RejectChanges(); return ret; } public IObject CloneWithSetup(DbManagerProxy manager, bool bRestricted = false) { var ret = base.Clone() as VectorType2PensideTest; ret.m_Parent = this.Parent; ret.m_IsMarkedToDelete = this.m_IsMarkedToDelete; ret.m_IsForcedToDelete = this.m_IsForcedToDelete; ret.m_IsNew = this.IsNew; ret.m_ObjectName = this.m_ObjectName; Accessor.Instance(null)._SetupLoad(manager, ret, true); ret.ClonedWithSetup(); ret.DeepAcceptChanges(); ret._setParent(); ret._permissions = _permissions; return ret; } public VectorType2PensideTest CloneWithSetup() { using (DbManagerProxy manager = DbManagerFactory.Factory.Create(ModelUserContext.Instance)) { return CloneWithSetup(manager) as VectorType2PensideTest; } } #endregion #region IObject implementation public object Key { get { return idfPensideTestTypeForVectorType; } } public string KeyName { get { return "idfPensideTestTypeForVectorType"; } } public string ToStringProp { get { return ToString(); } } private bool m_IsNew; public bool IsNew { get { return m_IsNew; } } [XmlIgnore] [LocalizedDisplayName("HasChanges")] public bool HasChanges { get { return IsDirty ; } } public new void RejectChanges() { var _prev_idfsPensideTestName_PensideTest = idfsPensideTestName; base.RejectChanges(); if (_prev_idfsPensideTestName_PensideTest != idfsPensideTestName) { _PensideTest = _PensideTestLookup.FirstOrDefault(c => c.idfsBaseReference == idfsPensideTestName); } } public void DeepRejectChanges() { RejectChanges(); } public void DeepAcceptChanges() { AcceptChanges(); } private bool m_bForceDirty; public override void AcceptChanges() { m_bForceDirty = false; base.AcceptChanges(); } [XmlIgnore] [LocalizedDisplayName("IsDirty")] public override bool IsDirty { get { return m_bForceDirty || base.IsDirty; } } public void SetChange() { m_bForceDirty = true; } public void DeepSetChange() { SetChange(); } public bool MarkToDelete() { return _Delete(false); } public string ObjectName { get { return m_ObjectName; } } public string ObjectIdent { get { return ObjectName + "_" + Key.ToString() + "_"; } } public string ObjectIdent2 { get { return ObjectIdent; } } public string ObjectIdent3 { get { return ObjectIdent; } } public IObjectAccessor GetAccessor() { return _getAccessor(); } public IObjectPermissions GetPermissions() { return _permissions; } private IObjectEnvironment _environment; public IObjectEnvironment Environment { get { return _environment; } set { _environment = value; } } public bool ReadOnly { get { return _readOnly; } set { _readOnly = value; } } public bool IsReadOnly(string name) { return _isReadOnly(name); } public bool IsInvisible(string name) { return _isInvisible(name); } public bool IsRequired(string name) { return _isRequired(m_isRequired, name); } public bool IsHiddenPersonalData(string name) { return _isHiddenPersonalData(name); } public string GetType(string name) { return _getType(name); } public object GetValue(string name) { return _getValue(name); } public void SetValue(string name, string val) { _setValue(name, val); } public CompareModel Compare(IObject o) { return _compare(o, null); } public BvSelectList GetList(string name) { return _getList(name); } public event ValidationEvent Validation; public event ValidationEvent ValidationEnd; public event AfterPostEvent AfterPost; public Dictionary<string, string> GetFieldTags(string name) { return null; } #endregion private bool IsRIRPropChanged(string fld, VectorType2PensideTest c) { return IsReadOnly(fld) != c.IsReadOnly(fld) || IsInvisible(fld) != c.IsInvisible(fld) || IsRequired(fld) != c._isRequired(m_isRequired, fld); } public VectorType2PensideTest() { } partial void Changed(string fieldName); partial void Created(DbManagerProxy manager); partial void Loaded(DbManagerProxy manager); partial void Deleted(); partial void ParsedFormCollection(NameValueCollection form); private bool m_IsForcedToDelete; [LocalizedDisplayName("IsForcedToDelete")] public bool IsForcedToDelete { get { return m_IsForcedToDelete; } } private bool m_IsMarkedToDelete; [LocalizedDisplayName("IsMarkedToDelete")] public bool IsMarkedToDelete { get { return m_IsMarkedToDelete; } } public void _SetupMainHandler() { PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(VectorType2PensideTest_PropertyChanged); } public void _RevokeMainHandler() { PropertyChanged -= new System.ComponentModel.PropertyChangedEventHandler(VectorType2PensideTest_PropertyChanged); } private void VectorType2PensideTest_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) { (sender as VectorType2PensideTest).Changed(e.PropertyName); } public bool ForceToDelete() { return _Delete(true); } internal bool _Delete(bool isForceDelete) { if (!_ValidateOnDelete()) return false; _DeletingExtenders(); m_IsMarkedToDelete = true; m_IsForcedToDelete = m_IsForcedToDelete ? m_IsForcedToDelete : isForceDelete; OnPropertyChanged("IsMarkedToDelete"); _DeletedExtenders(); Deleted(); return true; } private bool _ValidateOnDelete(bool bReport = true) { return true; } private void _DeletingExtenders() { VectorType2PensideTest obj = this; } private void _DeletedExtenders() { VectorType2PensideTest obj = this; } public bool OnValidation(ValidationModelException ex) { if (Validation != null) { var args = new ValidationEventArgs(ex.MessageId, ex.FieldName, ex.PropertyName, ex.Pars, ex.ValidatorType, ex.Obj, ex.ShouldAsk); Validation(this, args); return args.Continue; } return false; } public bool OnValidationEnd(ValidationModelException ex) { if (ValidationEnd != null) { var args = new ValidationEventArgs(ex.MessageId, ex.FieldName, ex.PropertyName, ex.Pars, ex.ValidatorType, ex.Obj, ex.ShouldAsk); ValidationEnd(this, args); return args.Continue; } return false; } public void OnAfterPost() { if (AfterPost != null) { AfterPost(this, EventArgs.Empty); } } public FormSize FormSize { get { return FormSize.Undefined; } } private bool _isInvisible(string name) { return false; } private bool _isReadOnly(string name) { return ReadOnly; } private bool m_readOnly; private bool _readOnly { get { return m_readOnly; } set { m_readOnly = value; } } internal Dictionary<string, Func<VectorType2PensideTest, bool>> m_isRequired; private bool _isRequired(Dictionary<string, Func<VectorType2PensideTest, bool>> isRequiredDict, string name) { if (isRequiredDict != null && isRequiredDict.ContainsKey(name)) return isRequiredDict[name](this); return false; } public void AddRequired(string name, Func<VectorType2PensideTest, bool> func) { if (m_isRequired == null) m_isRequired = new Dictionary<string, Func<VectorType2PensideTest, bool>>(); if (!m_isRequired.ContainsKey(name)) m_isRequired.Add(name, func); } internal Dictionary<string, Func<VectorType2PensideTest, bool>> m_isHiddenPersonalData; private bool _isHiddenPersonalData(string name) { if (m_isHiddenPersonalData != null && m_isHiddenPersonalData.ContainsKey(name)) return m_isHiddenPersonalData[name](this); return false; } public void AddHiddenPersonalData(string name, Func<VectorType2PensideTest, bool> func) { if (m_isHiddenPersonalData == null) m_isHiddenPersonalData = new Dictionary<string, Func<VectorType2PensideTest, bool>>(); if (!m_isHiddenPersonalData.ContainsKey(name)) m_isHiddenPersonalData.Add(name, func); } #region IDisposable Members private bool bIsDisposed; ~VectorType2PensideTest() { Dispose(); } public void Dispose() { if (!bIsDisposed) { bIsDisposed = true; LookupManager.RemoveObject("rftPensideTestType", this); } } #endregion #region ILookupUsage Members public void ReloadLookupItem(DbManagerProxy manager, string lookup_object) { if (lookup_object == "rftPensideTestType") _getAccessor().LoadLookup_PensideTest(manager, this); } #endregion public void ParseFormCollection(NameValueCollection form, bool bParseLookups = true, bool bParseRelations = true) { if (bParseLookups) { _field_infos.Where(i => i._type == "Lookup").ToList().ForEach(a => { if (form[ObjectIdent + a._formname] != null) a._set_func(this, form[ObjectIdent + a._formname]);} ); } _field_infos.Where(i => i._type != "Lookup" && i._type != "Child" && i._type != "Relation" && i._type != null) .ToList().ForEach(a => { if (form.AllKeys.Contains(ObjectIdent + a._formname)) a._set_func(this, form[ObjectIdent + a._formname]);} ); if (bParseRelations) { } ParsedFormCollection(form); } #region Class for web grid public class VectorType2PensideTestGridModel : IGridModelItem { public string ErrorMessage { get; set; } public long ItemKey { get; set; } public long idfPensideTestTypeForVectorType { get; set; } public long idfsPensideTestName { get; set; } } public partial class VectorType2PensideTestGridModelList : List<VectorType2PensideTestGridModel>, IGridModelList, IGridModelListLoad { public long ListKey { get; protected set; } public List<string> Columns { get; protected set; } public List<string> Hiddens { get; protected set; } public Dictionary<string, string> Labels { get; protected set; } public Dictionary<string, ActionMetaItem> Actions { get; protected set; } public List<string> Keys { get; protected set; } public bool IsHiddenPersonalData(string name) { return Meta._isHiddenPersonalData(name); } public VectorType2PensideTestGridModelList() { } public void Load(long key, IEnumerable items, string errMes) { LoadGridModelList(key, items as IEnumerable<VectorType2PensideTest>, errMes); } public VectorType2PensideTestGridModelList(long key, IEnumerable items, string errMes) { LoadGridModelList(key, items as IEnumerable<VectorType2PensideTest>, errMes); } public VectorType2PensideTestGridModelList(long key, IEnumerable<VectorType2PensideTest> items) { LoadGridModelList(key, items, null); } public VectorType2PensideTestGridModelList(long key) { LoadGridModelList(key, new List<VectorType2PensideTest>(), null); } partial void filter(List<VectorType2PensideTest> items); private void LoadGridModelList(long key, IEnumerable<VectorType2PensideTest> items, string errMes) { ListKey = key; Columns = new List<string> {_str_idfsPensideTestName}; Hiddens = new List<string> {_str_idfPensideTestTypeForVectorType}; Keys = new List<string> {}; Labels = new Dictionary<string, string> {{_str_idfsPensideTestName, _str_idfsPensideTestName}}; Actions = new Dictionary<string, ActionMetaItem> {}; VectorType2PensideTest.Meta.Actions.ForEach(a => Actions.Add("@" + a.Name, a)); var list = new List<VectorType2PensideTest>(items); filter(list); AddRange(list.Where(c => !c.IsMarkedToDelete).Select(c => new VectorType2PensideTestGridModel() { idfPensideTestTypeForVectorType=c.idfPensideTestTypeForVectorType,idfsPensideTestName=c.idfsPensideTestName })); if (Count > 0) { this.Last().ErrorMessage = errMes; } } } #endregion #region Accessor public abstract partial class Accessor : DataAccessor<VectorType2PensideTest> , IObjectAccessor , IObjectMeta , IObjectValidator , IObjectCreator , IObjectCreator<VectorType2PensideTest> , IObjectSelectDetailList , IObjectPost { #region IObjectAccessor public string KeyName { get { return "idfPensideTestTypeForVectorType"; } } #endregion private delegate void on_action(VectorType2PensideTest obj); private static Accessor g_Instance = CreateInstance<Accessor>(); private CacheScope m_CS; public static Accessor Instance(CacheScope cs) { if (cs == null) return g_Instance; lock(cs) { object acc = cs.Get(typeof (Accessor)); if (acc != null) { return acc as Accessor; } Accessor ret = CreateInstance<Accessor>(); ret.m_CS = cs; cs.Add(typeof(Accessor), ret); return ret; } } private BaseReference.Accessor PensideTestAccessor { get { return eidss.model.Schema.BaseReference.Accessor.Instance(m_CS); } } public virtual List<IObject> SelectDetailList(DbManagerProxy manager, object ident, int? HACode = null) { return _SelectList(manager , null , null ).Cast<IObject>().ToList(); } public virtual List<VectorType2PensideTest> SelectList(DbManagerProxy manager ) { return _SelectList(manager , delegate(VectorType2PensideTest obj) { } , delegate(VectorType2PensideTest obj) { } ); } private List<VectorType2PensideTest> _SelectList(DbManagerProxy manager , on_action loading, on_action loaded ) { try { MapResultSet[] sets = new MapResultSet[1]; List<VectorType2PensideTest> objs = new List<VectorType2PensideTest>(); sets[0] = new MapResultSet(typeof(VectorType2PensideTest), objs); manager .SetSpCommand("spPensideTestForVectorType_SelectDetail" ) .ExecuteResultSet(sets); foreach(var obj in objs) { obj.m_CS = m_CS; if (loading != null) loading(obj); _SetupLoad(manager, obj); if (loaded != null) loaded(obj); } return objs; } catch(DataException e) { throw DbModelException.Create(e); } } internal void _SetupLoad(DbManagerProxy manager, VectorType2PensideTest obj, bool bCloning = false) { if (obj == null) return; // loading extenters - begin // loading extenters - end if (!bCloning) { } _LoadLookups(manager, obj); obj._setParent(); // loaded extenters - begin // loaded extenters - end _SetupHandlers(obj); _SetupChildHandlers(obj, null); _SetPermitions(obj._permissions, obj); _SetupRequired(obj); _SetupPersonalDataRestrictions(obj); obj._SetupMainHandler(); obj.AcceptChanges(); } internal void _SetPermitions(IObjectPermissions permissions, VectorType2PensideTest obj) { if (obj != null) { obj._permissions = permissions; if (obj._permissions != null) { } } } private VectorType2PensideTest _CreateNew(DbManagerProxy manager, IObject Parent, int? HACode, on_action creating, on_action created, bool isFake = false) { try { VectorType2PensideTest obj = VectorType2PensideTest.CreateInstance(); obj.m_CS = m_CS; obj.m_IsNew = true; obj.Parent = Parent; if (creating != null) creating(obj); // creating extenters - begin obj.idfPensideTestTypeForVectorType = (new AutoIncrementExtender<VectorType2PensideTest>()).GetScalar(manager, obj, isFake); // creating extenters - end _LoadLookups(manager, obj); _SetupHandlers(obj); _SetupChildHandlers(obj, null); obj._SetupMainHandler(); obj._setParent(); // created extenters - begin // created extenters - end if (created != null) created(obj); obj.Created(manager); _SetPermitions(obj._permissions, obj); _SetupRequired(obj); _SetupPersonalDataRestrictions(obj); return obj; } catch(DataException e) { throw DbModelException.Create(e); } } public VectorType2PensideTest CreateNewT(DbManagerProxy manager, IObject Parent, int? HACode = null) { return _CreateNew(manager, Parent, HACode, null, null); } public IObject CreateNew(DbManagerProxy manager, IObject Parent, int? HACode = null) { return _CreateNew(manager, Parent, HACode, null, null); } public VectorType2PensideTest CreateFakeT(DbManagerProxy manager, IObject Parent, int? HACode = null) { return _CreateNew(manager, Parent, HACode, null, null, true); } public IObject CreateFake(DbManagerProxy manager, IObject Parent, int? HACode = null) { return _CreateNew(manager, Parent, HACode, null, null, true); } public VectorType2PensideTest CreateWithParamsT(DbManagerProxy manager, IObject Parent, List<object> pars) { return _CreateNew(manager, Parent, null, null, null); } public IObject CreateWithParams(DbManagerProxy manager, IObject Parent, List<object> pars) { return _CreateNew(manager, Parent, null, null, null); } private void _SetupChildHandlers(VectorType2PensideTest obj, object newobj) { } private void _SetupHandlers(VectorType2PensideTest obj) { } public void LoadLookup_PensideTest(DbManagerProxy manager, VectorType2PensideTest obj) { obj.PensideTestLookup.Clear(); obj.PensideTestLookup.Add(PensideTestAccessor.CreateNewT(manager, null)); obj.PensideTestLookup.AddRange(PensideTestAccessor.rftPensideTestType_SelectList(manager ) .Where(c => (c.intRowStatus == 0) || (c.idfsBaseReference == obj.idfsPensideTestName)) .ToList()); if (obj.idfsPensideTestName != 0) { obj.PensideTest = obj.PensideTestLookup .SingleOrDefault(c => c.idfsBaseReference == obj.idfsPensideTestName); } LookupManager.AddObject("rftPensideTestType", obj, PensideTestAccessor.GetType(), "rftPensideTestType_SelectList" , "SelectLookupList"); } private void _LoadLookups(DbManagerProxy manager, VectorType2PensideTest obj) { LoadLookup_PensideTest(manager, obj); } [SprocName("spPensideTestForVectorType_Post")] protected abstract void _post(DbManagerProxy manager, int Action, [Direction.InputOutput("idfPensideTestTypeForVectorType")] VectorType2PensideTest obj); protected void _postPredicate(DbManagerProxy manager, int Action, [Direction.InputOutput("idfPensideTestTypeForVectorType")] VectorType2PensideTest obj) { _post(manager, Action, obj); } public bool Post(DbManagerProxy manager, IObject obj, bool bChildObject = false) { bool bTransactionStarted = false; bool bSuccess; try { VectorType2PensideTest bo = obj as VectorType2PensideTest; if (!bo.IsNew && bo.IsMarkedToDelete) // delete { } else if (bo.IsNew && !bo.IsMarkedToDelete) // insert { } else if (!bo.IsMarkedToDelete) // update { } if (!manager.IsTransactionStarted) { bTransactionStarted = true; manager.BeginTransaction(); } bSuccess = _PostNonTransaction(manager, obj as VectorType2PensideTest, bChildObject); if (bTransactionStarted) { if (bSuccess) { obj.DeepAcceptChanges(); manager.CommitTransaction(); } else { manager.RollbackTransaction(); } } if (bSuccess && bo.IsNew && !bo.IsMarkedToDelete) // insert { bo.m_IsNew = false; } if (bSuccess && bTransactionStarted) { bo.OnAfterPost(); } } catch(Exception e) { if (bTransactionStarted) { manager.RollbackTransaction(); } if (e is DataException) { throw DbModelException.Create(e as DataException); } else throw; } return bSuccess; } private bool _PostNonTransaction(DbManagerProxy manager, VectorType2PensideTest obj, bool bChildObject) { bool bHasChanges = obj.HasChanges; if (!obj.IsNew && obj.IsMarkedToDelete) // delete { if (!ValidateCanDelete(manager, obj)) return false; _postPredicate(manager, 8, obj); } else if (!obj.IsMarkedToDelete) // insert/update { if (!bChildObject) if (!Validate(manager, obj, true, true, true)) return false; // posting extenters - begin // posting extenters - end if (obj.IsNew && !obj.IsMarkedToDelete && obj.HasChanges) _postPredicate(manager, 4, obj); else if (!obj.IsNew && !obj.IsMarkedToDelete && obj.HasChanges) _postPredicate(manager, 16, obj); // posted extenters - begin // posted extenters - end } //obj.AcceptChanges(); return true; } public bool ValidateCanDelete(VectorType2PensideTest obj) { using (DbManagerProxy manager = DbManagerFactory.Factory.Create(ModelUserContext.Instance)) { return ValidateCanDelete(manager, obj); } } public bool ValidateCanDelete(DbManagerProxy manager, VectorType2PensideTest obj) { return true; } protected ValidationModelException ChainsValidate(VectorType2PensideTest obj) { return null; } protected bool ChainsValidate(VectorType2PensideTest obj, bool bRethrowException) { ValidationModelException ex = ChainsValidate(obj); if (ex != null) { if (bRethrowException) throw ex; if (!obj.OnValidation(ex)) { obj.OnValidationEnd(ex); return false; } } return true; } public bool Validate(DbManagerProxy manager, IObject obj, bool bPostValidation, bool bChangeValidation, bool bDeepValidation, bool bRethrowException = false) { return Validate(manager, obj as VectorType2PensideTest, bPostValidation, bChangeValidation, bDeepValidation, bRethrowException); } public bool Validate(DbManagerProxy manager, VectorType2PensideTest obj, bool bPostValidation, bool bChangeValidation, bool bDeepValidation, bool bRethrowException = false) { if (!ChainsValidate(obj, bRethrowException)) return false; try { if (bPostValidation) { (new RequiredValidator( "idfsPensideTestName", "idfsPensideTestName","", false )).Validate(c => true, obj, obj.idfsPensideTestName); } if (bChangeValidation) { } if (bDeepValidation) { } } catch(ValidationModelException ex) { if (bRethrowException) throw; if (!obj.OnValidation(ex)) { obj.OnValidationEnd(ex); return false; } } return true; } private void _SetupRequired(VectorType2PensideTest obj) { obj .AddRequired("idfsPensideTestName", c => true); obj .AddRequired("PensideTest", c => true); } private void _SetupPersonalDataRestrictions(VectorType2PensideTest obj) { } #region IObjectMeta public int? MaxSize(string name) { return Meta.Sizes.ContainsKey(name) ? (int?)Meta.Sizes[name] : null; } public bool RequiredByField(string name, IObject obj) { return Meta.RequiredByField.ContainsKey(name) ? Meta.RequiredByField[name](obj as VectorType2PensideTest) : false; } public bool RequiredByProperty(string name, IObject obj) { return Meta.RequiredByProperty.ContainsKey(name) ? Meta.RequiredByProperty[name](obj as VectorType2PensideTest) : false; } public List<SearchPanelMetaItem> SearchPanelMeta { get { return Meta.SearchPanelMeta; } } public List<GridMetaItem> GridMeta { get { return Meta.GridMeta; } } public List<ActionMetaItem> Actions { get { return Meta.Actions; } } public string DetailPanel { get { return "VectorType2PensideTestDetail"; } } public string HelpIdWin { get { return ""; } } public string HelpIdWeb { get { return ""; } } public string HelpIdHh { get { return ""; } } #endregion } #region Meta public static class Meta { public static string spSelect = "spPensideTestForVectorType_SelectDetail"; public static string spCount = ""; public static string spPost = "spPensideTestForVectorType_Post"; public static string spInsert = ""; public static string spUpdate = ""; public static string spDelete = ""; public static string spCanDelete = ""; public static Dictionary<string, int> Sizes = new Dictionary<string, int>(); public static Dictionary<string, Func<VectorType2PensideTest, bool>> RequiredByField = new Dictionary<string, Func<VectorType2PensideTest, bool>>(); public static Dictionary<string, Func<VectorType2PensideTest, bool>> RequiredByProperty = new Dictionary<string, Func<VectorType2PensideTest, bool>>(); public static List<SearchPanelMetaItem> SearchPanelMeta = new List<SearchPanelMetaItem>(); public static List<GridMetaItem> GridMeta = new List<GridMetaItem>(); public static List<ActionMetaItem> Actions = new List<ActionMetaItem>(); private static Dictionary<string, List<Func<bool>>> m_isHiddenPersonalData = new Dictionary<string, List<Func<bool>>>(); internal static bool _isHiddenPersonalData(string name) { if (m_isHiddenPersonalData.ContainsKey(name)) return m_isHiddenPersonalData[name].Aggregate(false, (s,c) => s | c()); return false; } private static void AddHiddenPersonalData(string name, Func<bool> func) { if (!m_isHiddenPersonalData.ContainsKey(name)) m_isHiddenPersonalData.Add(name, new List<Func<bool>>()); m_isHiddenPersonalData[name].Add(func); } static Meta() { if (!RequiredByField.ContainsKey("idfsPensideTestName")) RequiredByField.Add("idfsPensideTestName", c => true); if (!RequiredByProperty.ContainsKey("idfsPensideTestName")) RequiredByProperty.Add("idfsPensideTestName", c => true); GridMeta.Add(new GridMetaItem( _str_idfPensideTestTypeForVectorType, _str_idfPensideTestTypeForVectorType, null, false, true, true, true, null )); GridMeta.Add(new GridMetaItem( _str_idfsPensideTestName, _str_idfsPensideTestName, null, true, true, true, true, null )); Actions.Add(new ActionMetaItem( "Create", ActionTypes.Create, false, String.Empty, String.Empty, (manager, c, pars) => new ActResult(true, Accessor.Instance(null).CreateWithParams(manager, c, pars)), null, new ActionMetaItem.VisualItem( /*from BvMessages*/"strCreate_Id", "add", /*from BvMessages*/"tooltipCreate_Id", /*from BvMessages*/"", "", /*from BvMessages*/"tooltipCreate_Id", ActionsAlignment.Right, ActionsPanelType.Group, ActionsAppType.All ), false, null, null, null, null, null, false )); Actions.Add(new ActionMetaItem( "Edit", ActionTypes.Edit, false, String.Empty, String.Empty, (manager, c, pars) => new ActResult(true, c), null, new ActionMetaItem.VisualItem( /*from BvMessages*/"strEdit_Id", "edit", /*from BvMessages*/"tooltipEdit_Id", /*from BvMessages*/"strView_Id", "View1", /*from BvMessages*/"tooltipEdit_Id", ActionsAlignment.Right, ActionsPanelType.Group, ActionsAppType.All ), false, null, null, null, null, null, false )); Actions.Add(new ActionMetaItem( "Delete", ActionTypes.Delete, false, String.Empty, String.Empty, (manager, c, pars) => ((VectorType2PensideTest)c).MarkToDelete(), null, new ActionMetaItem.VisualItem( /*from BvMessages*/"strDelete_Id", "Delete_Remove", /*from BvMessages*/"tooltipDelete_Id", /*from BvMessages*/"", "", /*from BvMessages*/"tooltipDelete_Id", ActionsAlignment.Right, ActionsPanelType.Group, ActionsAppType.All ), false, null, null, null, null, null, false )); Actions.Add(new ActionMetaItem( "Ok", ActionTypes.Ok, false, String.Empty, String.Empty, (manager, c, pars) => new ActResult(true, c), null, new ActionMetaItem.VisualItem( /*from BvMessages*/"strOK_Id", "", /*from BvMessages*/"tooltipOK_Id", /*from BvMessages*/"", "", /*from BvMessages*/"tooltipOK_Id", ActionsAlignment.Right, ActionsPanelType.Main, ActionsAppType.All ), false, null, null, null, null, null, false )); Actions.Add(new ActionMetaItem( "Cancel", ActionTypes.Cancel, false, String.Empty, String.Empty, (manager, c, pars) => new ActResult(true, c), null, new ActionMetaItem.VisualItem( /*from BvMessages*/"strCancel_Id", "", /*from BvMessages*/"tooltipCancel_Id", /*from BvMessages*/"strOK_Id", "", /*from BvMessages*/"tooltipCancel_Id", ActionsAlignment.Right, ActionsPanelType.Main, ActionsAppType.All ), false, null, null, null, null, null, false )); _SetupPersonalDataRestrictions(); } private static void _SetupPersonalDataRestrictions() { } } #endregion #endregion } }
40.745083
326
0.5022
[ "BSD-2-Clause" ]
EIDSS/EIDSS-Legacy
EIDSS v6/eidss.model/Schema/VectorType2PensideTest.model.cs
53,867
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. namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; using System.Runtime.Serialization; using Newtonsoft.Json; /// <summary> /// The type Identity. /// </summary> [DataContract] [JsonConverter(typeof(DerivedTypeConverter))] public partial class Identity { /// <summary> /// Gets or sets displayName. /// </summary> [DataMember(Name = "displayName", EmitDefaultValue = false, IsRequired = false)] public string DisplayName { get; set; } /// <summary> /// Gets or sets id. /// </summary> [DataMember(Name = "id", EmitDefaultValue = false, IsRequired = false)] public string Id { get; set; } /// <summary> /// Gets or sets additional data. /// </summary> [JsonExtensionData(ReadData = true)] public IDictionary<string, object> AdditionalData { get; set; } } }
31.704545
153
0.539068
[ "MIT" ]
MIchaelMainer/GraphAPI
src/Microsoft.Graph/Models/Generated/Identity.cs
1,395
C#
using System; using System.Linq; using NUnit.Framework; namespace LinqInfer.UnitTests.Maths { [TestFixture] public class RandomTests { [TestCase(1000)] public void NextDouble(int iterations) { var rnd = new LinqInfer.Maths.Random(); double total = 0; double first = 0; foreach(var n in Enumerable.Range(1, iterations)) { var x = rnd.NextDouble(); if (total == 0) first = x; total += x; // Console.WriteLine(x); } var ave = total / iterations; Console.WriteLine("Ave:{0}", ave); Assert.That(ave, Is.AtLeast(0.4d)); Assert.That(ave, Is.AtMost(0.6d)); Assert.That(ave, Is.Not.EqualTo(first)); } [TestCase(1000)] public void NextInt(int iterations) { var rnd = new LinqInfer.Maths.Random(); int total = 0; foreach (var n in Enumerable.Range(1, iterations)) { var x = rnd.Next(100); total += x; //Console.WriteLine(x); } var ave = total / (double)iterations; Console.WriteLine("Ave:{0}", ave); Assert.That(ave, Is.AtLeast(36d)); Assert.That(ave, Is.AtMost(64d)); } [Test] public void ByteTest() { Write("Max int", int.MaxValue, BitConverter.GetBytes(int.MaxValue)); Write("Max long", long.MaxValue, BitConverter.GetBytes(long.MaxValue)); Write("Zero int", 0, BitConverter.GetBytes(0)); Write("Min int", int.MinValue, BitConverter.GetBytes(int.MinValue)); Write("Max double", double.MaxValue, BitConverter.GetBytes(double.MaxValue)); Write("Zero double", 0d, BitConverter.GetBytes(0d)); Write("1 double", 1d, BitConverter.GetBytes(1d)); var b = BitConverter.GetBytes(int.MaxValue); b[sizeof(int) - 1] = (byte)(b[sizeof(int) - 1] - 1); Write("Max int - 1", int.MaxValue - 1, b); } void Write(string label, object val, byte[] data) { Console.Write(label); Console.Write(" "); Console.Write(val); Console.Write(": "); foreach(var bit in data) { Console.Write(bit + ","); } Console.Write(" ({0} bytes)", data.Length); Console.WriteLine(); } } }
28.428571
89
0.49942
[ "MIT" ]
roberino/linqinfer
tests/LinqInfer.UnitTests/Maths/RandomTests.cs
2,589
C#
//----------------------------------------------------------------------- // <copyright file="DfpMeasureSourceFixture.cs" company="Rare Crowds Inc"> // Copyright 2012-2013 Rare Crowds, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> //----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Linq; using DataAccessLayer; using DynamicAllocation; using DynamicAllocationUtilities; using EntityTestUtilities; using GoogleDfpActivities.Measures; using Microsoft.VisualStudio.TestTools.UnitTesting; using Newtonsoft.Json; using Utilities.Storage; using Utilities.Storage.Testing; namespace GoogleDfpActivitiesUnitTests { /// <summary>Tests for the Google DFP MeasureSource classes</summary> [TestClass] public class DfpMeasureSourceFixture { /// <summary>Per-test initialization</summary> [TestInitialize] public void TestInitialize() { SimulatedPersistentDictionaryFactory.Initialize(); } /// <summary> /// Test creating DFP measure sources using the dfp measure provider /// with entities that do not have custom measure maps or configs. /// </summary> /// <remarks> /// The primary purpose of this test is to ensure all measure sources /// have a constructor that take the expected arguments. /// </remarks> [TestMethod] public void GetMeasureSourcesFromProviderWithoutEntitySources() { var companyEntity = EntityTestHelpers.CreateTestCompanyEntity( new EntityId().ToString(), Guid.NewGuid().ToString("N")); var campaignEntity = EntityTestHelpers.CreateTestCampaignEntity( new EntityId().ToString(), Guid.NewGuid().ToString("N"), 123456, DateTime.UtcNow, DateTime.UtcNow.AddDays(30), "???"); // Create the measure source provider and get sources using // test entities that do not have their own measure maps. var dfpMeasureSourceProvider = new DfpMeasureSourceProvider(); var measureSourcesEnumerable = dfpMeasureSourceProvider.GetMeasureSources( companyEntity, campaignEntity); // Force Linq evaluation using ToArray var measureSources = measureSourcesEnumerable.ToArray(); // Verify there are measure sources and that they all derive from DfpMeasureSourceBase Assert.IsTrue(measureSources.Count() > 0); Assert.IsTrue(measureSources.All(source => typeof(DfpMeasureSourceBase).IsAssignableFrom(source.GetType()))); } /// <summary>Test creating DFP measure sources using the provider</summary> [TestMethod] public void GetMeasureSourcesFromProviderWithEntitySources() { // Setup entities with custom measure maps var companyName = Guid.NewGuid().ToString("N"); var companyEntity = EntityTestHelpers.CreateTestCompanyEntity( new EntityId().ToString(), companyName); var companyMeasureMapJson = JsonConvert.SerializeObject( new Dictionary<long, IDictionary<string, object>> { { 1, new Dictionary<string, object> { { "displayName", companyName } } } }); companyEntity.SetPropertyValueByName( DynamicAllocationEntityProperties.MeasureMap, new PropertyValue(PropertyType.String, companyMeasureMapJson)); var campaignName = Guid.NewGuid().ToString("N"); var campaignEntity = EntityTestHelpers.CreateTestCampaignEntity( new EntityId().ToString(), campaignName, 123456, DateTime.UtcNow, DateTime.UtcNow.AddDays(30), "???"); var campaignMeasureMapJson = JsonConvert.SerializeObject( new Dictionary<long, IDictionary<string, object>> { { 1, new Dictionary<string, object> { { "displayName", campaignName } } } }); companyEntity.SetPropertyValueByName( DynamicAllocationEntityProperties.MeasureMap, new PropertyValue(PropertyType.String, companyMeasureMapJson)); // Create the measure source provider and get sources using // test entities that have their own measure maps. var dfpMeasureSourceProvider = new DfpMeasureSourceProvider(); var measureSourcesEnumerable = dfpMeasureSourceProvider.GetMeasureSources( companyEntity, campaignEntity); // Force Linq evaluation using ToArray var measureSources = measureSourcesEnumerable.ToArray(); // Verify there are measure sources and that they all derive from DfpMeasureSourceBase Assert.IsTrue(measureSources.Count() > 0); Assert.IsTrue(measureSources.All(source => typeof(DfpMeasureSourceBase).IsAssignableFrom(source.GetType()) || typeof(EntityMeasureSource).IsAssignableFrom(source.GetType()))); Assert.IsTrue(measureSources.OfType<DfpMeasureSourceBase>().Count() > 0); Assert.IsTrue(measureSources.OfType<EntityMeasureSource>().Count() > 0); // Verify the expected entity measures are present var entityMeasures = measureSources .OfType<EntityMeasureSource>() .SelectMany(source => source.Measures); Assert.IsNotNull(entityMeasures.SingleOrDefault(m => (string)m.Value["displayName"] == companyName)); Assert.IsNotNull(entityMeasures.SingleOrDefault(m => (string)m.Value["displayName"] == campaignName)); } /// <summary>Test creating a DFP measure source</summary> [TestMethod] public void CreateDfpMeasureSource() { var uniqueId = Guid.NewGuid().ToString("N").Left(10); var configJson = JsonConvert.SerializeObject( new Dictionary<string, object> { { "GoogleDfp.NetworkId", uniqueId } }); var companyEntity = EntityTestHelpers.CreateTestCompanyEntity( new EntityId().ToString(), Guid.NewGuid().ToString()); companyEntity.SetEntityProperty( new EntityProperty("CONFIG", new PropertyValue(PropertyType.String, configJson), PropertyFilter.System)); var campaignEntity = EntityTestHelpers.CreateTestCampaignEntity( new EntityId().ToString(), Guid.NewGuid().ToString("N"), 12345, DateTime.UtcNow, DateTime.UtcNow.AddDays(30), "???"); var source = new TestDfpMeasureSource(companyEntity, campaignEntity); Assert.AreEqual(299000000000000000, source.BaseMeasureId); Assert.AreEqual(299999999999999999, source.MaxMeasureId); var expectedSourceId = "NETWORK:0299:dfp-test-" + uniqueId; Assert.AreEqual(expectedSourceId, source.SourceId); } /// <summary> /// Test the method used to create browser technology measure display names /// </summary> [TestMethod] public void GetBrowserTechnologyMeasureDisplayName() { var majorMinorVersionRow = new Dictionary<string, object> { { "browsername", "Browser" }, { "majorversion", "0" }, { "minorversion", "1" }, }; var majorMinorVersionName = TechnologyMeasureSource.GetBrowserVersionDisplayName(majorMinorVersionRow); Assert.AreEqual("Browser 0.1", majorMinorVersionName); var majorAnyVersionRow = new Dictionary<string, object> { { "browsername", "Browser" }, { "majorversion", "0" }, { "minorversion", "Any" }, }; var majorAnyVersionName = TechnologyMeasureSource.GetBrowserVersionDisplayName(majorAnyVersionRow); Assert.AreEqual("Browser 0.*", majorAnyVersionName); var anyAnyVersionRow = new Dictionary<string, object> { { "browsername", "Browser" }, { "majorversion", "Any" }, { "minorversion", "any" }, }; var anyAnyVersionName = TechnologyMeasureSource.GetBrowserVersionDisplayName(anyAnyVersionRow); Assert.AreEqual("Browser *.*", anyAnyVersionName); var majorOtherVersionRow = new Dictionary<string, object> { { "browsername", "Browser" }, { "majorversion", "0" }, { "minorversion", "Other" }, }; var majorOtherVersionName = TechnologyMeasureSource.GetBrowserVersionDisplayName(majorOtherVersionRow); Assert.AreEqual("Browser 0 (Other)", majorOtherVersionName); var otherOtherVersionRow = new Dictionary<string, object> { { "browsername", "Browser" }, { "majorversion", "Other" }, { "minorversion", "other" }, }; var otherOtherVersionName = TechnologyMeasureSource.GetBrowserVersionDisplayName(otherOtherVersionRow); Assert.AreEqual("Browser (Other)", otherOtherVersionName); } /// <summary>Derived class for testing DfpMeasureSourceBase</summary> private class TestDfpMeasureSource : DfpMeasureSourceBase, IMeasureSource { /// <summary>Initializes a new instance of the TestDfpMeasureSource class</summary> /// <param name="companyEntity">CompanyEntity (for config)</param> /// <param name="campaignEntity">CampaignEntity (for config)</param> public TestDfpMeasureSource(CompanyEntity companyEntity, CampaignEntity campaignEntity) : base(99, "test", companyEntity, campaignEntity, PersistentDictionaryType.Memory) { } /// <summary>Gets or sets the test MeasureMapCacheEntry</summary> public MeasureMapCacheEntry TestMeasureMapCacheEntry { get; set; } /// <summary>Gets the category display name</summary> protected override string CategoryDisplayName { get { return "Test Measure"; } } /// <summary>Gets the measure type</summary> protected override string MeasureType { get { return "test"; } } /// <summary>Fetch the latest AdUnit measure map</summary> /// <returns>The latest MeasureMap</returns> protected override MeasureMapCacheEntry FetchLatestMeasureMap() { return this.TestMeasureMapCacheEntry; } } } }
43.29927
121
0.594909
[ "Apache-2.0" ]
chinnurtb/OpenAdStack
GoogleDfpActivities/GoogleDfpActitityUnitTests/DfpMeasureSourceFixture.cs
11,866
C#
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Cloud.BigQuery.DataTransfer.V1.Snippets { using Google.Cloud.BigQuery.DataTransfer.V1; using System.Threading.Tasks; public sealed partial class GeneratedDataTransferServiceClientStandaloneSnippets { /// <summary>Snippet for CheckValidCredsAsync</summary> /// <remarks> /// This snippet has been automatically generated for illustrative purposes only. /// It may require modifications to work in your environment. /// </remarks> public async Task CheckValidCredsResourceNamesAsync() { // Create client DataTransferServiceClient dataTransferServiceClient = await DataTransferServiceClient.CreateAsync(); // Initialize request argument(s) DataSourceName name = DataSourceName.FromProjectDataSource("[PROJECT]", "[DATA_SOURCE]"); // Make the request CheckValidCredsResponse response = await dataTransferServiceClient.CheckValidCredsAsync(name); } } }
41.1
112
0.711679
[ "Apache-2.0" ]
googleapis/googleapis-gen
google/cloud/bigquery/datatransfer/v1/google-cloud-bigquery-datatransfer-v1-csharp/Google.Cloud.BigQuery.DataTransfer.V1.StandaloneSnippets/DataTransferServiceClient.CheckValidCredsResourceNamesAsyncSnippet.g.cs
1,644
C#
using System.Collections; using System.Collections.Generic; using UnityEngine.SceneManagement; using UnityEngine; public class AvengerShipFight : MonoBehaviour { Seek seek; Flee flee; StateMachine stateMachine; GameObject[] leviathans; public GameObject seekLeviathan; int whichLeviathan; int bullets = 7; public GameObject bulletPrefab; public LayerMask leviathanMask; public class TargetLeviathan : State { public override void Enter() { owner.GetComponent<AvengerShipFight>().flee.enabled = false; owner.GetComponent<AvengerShipFight>().seek.enabled = true; owner.GetComponent<AvengerShipFight>().leviathans = GameObject.FindGameObjectsWithTag("leviathan"); if(owner.GetComponent<AvengerShipFight>().leviathans.Length > 0) { owner.GetComponent<AvengerShipFight>().whichLeviathan = Random.Range(0, owner.GetComponent<AvengerShipFight>().leviathans.Length); owner.GetComponent<AvengerShipFight>().seekLeviathan = owner.GetComponent<AvengerShipFight>().leviathans[owner.GetComponent<AvengerShipFight>().whichLeviathan].gameObject; owner.GetComponent<AvengerShipFight>().seek.target = owner.GetComponent<AvengerShipFight>().seekLeviathan.transform.position; } } public override void Think() { if(owner.GetComponent<AvengerShipFight>().seekLeviathan == null) { owner.GetComponent<AvengerShipFight>().leviathans = GameObject.FindGameObjectsWithTag("leviathan"); if(owner.GetComponent<AvengerShipFight>().leviathans.Length > 0) { owner.GetComponent<AvengerShipFight>().whichLeviathan = Random.Range(0, owner.GetComponent<AvengerShipFight>().leviathans.Length); owner.GetComponent<AvengerShipFight>().seekLeviathan = owner.GetComponent<AvengerShipFight>().leviathans[owner.GetComponent<AvengerShipFight>().whichLeviathan].gameObject; owner.GetComponent<AvengerShipFight>().seek.target = owner.GetComponent<AvengerShipFight>().seekLeviathan.transform.position; } } else if(Vector3.Distance(owner.GetComponent<AvengerShipFight>().transform.position, owner.GetComponent<AvengerShipFight>().seek.target) < 80f) { owner.GetComponent<AvengerShipFight>().stateMachine.ChangeState(new FleeLeviathan()); } else { owner.GetComponent<AvengerShipFight>().seek.target = owner.GetComponent<AvengerShipFight>().seekLeviathan.transform.position; } Collider[] visibleLeviathans = Physics.OverlapSphere(owner.GetComponent<AvengerShipFight>().transform.position, 500f, owner.GetComponent<AvengerShipFight>().leviathanMask); if(visibleLeviathans.Length > 0) { Vector3 closestLeviathan = Vector3.zero; for(int i = 0; i < visibleLeviathans.Length; i++) { if(closestLeviathan == Vector3.zero) { closestLeviathan = visibleLeviathans[i].gameObject.transform.position; owner.GetComponent<AvengerShipFight>().seek.target = closestLeviathan; } else if(Vector3.Distance(owner.transform.position, visibleLeviathans[i].gameObject.transform.position) < Vector3.Distance(owner.transform.position, closestLeviathan)) { closestLeviathan = visibleLeviathans[i].gameObject.transform.position; owner.GetComponent<AvengerShipFight>().seek.target = closestLeviathan; } if(owner.GetComponent<AvengerShipFight>().seekLeviathan == null) { owner.GetComponent<AvengerShipFight>().leviathans = GameObject.FindGameObjectsWithTag("leviathan"); owner.GetComponent<AvengerShipFight>().whichLeviathan = Random.Range(0, owner.GetComponent<AvengerShipFight>().leviathans.Length); owner.GetComponent<AvengerShipFight>().seekLeviathan = owner.GetComponent<AvengerShipFight>().leviathans[owner.GetComponent<AvengerShipFight>().whichLeviathan].transform.GetChild(0).gameObject; owner.GetComponent<AvengerShipFight>().seek.target = owner.GetComponent<AvengerShipFight>().seekLeviathan.transform.position; } else if(Vector3.Distance(owner.GetComponent<AvengerShipFight>().transform.position, owner.GetComponent<AvengerShipFight>().seekLeviathan.transform.position) < 200f) { Vector3 dirToLeviathan = (visibleLeviathans[i].gameObject.transform.position - owner.GetComponent<AvengerShipFight>().transform.position).normalized; if(Vector3.Angle(owner.GetComponent<AvengerShipFight>().transform.forward, dirToLeviathan) < 90f) { if(owner.GetComponent<AvengerShipFight>().bullets > 0) { Instantiate(owner.GetComponent<AvengerShipFight>().bulletPrefab, owner.GetComponent<AvengerShipFight>().transform.position, owner.GetComponent<AvengerShipFight>().transform.rotation); owner.GetComponent<AvengerShipFight>().bullets--; } } } } } } } public class FleeLeviathan : State { public override void Enter() { owner.GetComponent<AvengerShipFight>().flee.enabled = true; owner.GetComponent<AvengerShipFight>().seek.enabled = false; owner.GetComponent<AvengerShipFight>().flee.target = owner.GetComponent<AvengerShipFight>().seekLeviathan.transform.position; owner.GetComponent<AvengerShipFight>().bullets = 10; } public override void Think() { if(owner.GetComponent<AvengerShipFight>().seekLeviathan == null) { owner.GetComponent<AvengerShipFight>().leviathans = GameObject.FindGameObjectsWithTag("leviathan"); if(owner.GetComponent<AvengerShipFight>().leviathans.Length > 0) { owner.GetComponent<AvengerShipFight>().whichLeviathan = Random.Range(0, owner.GetComponent<AvengerShipFight>().leviathans.Length); // owner.GetComponent<AvengerShipFight>().seekLeviathan = owner.GetComponent<AvengerShipFight>().leviathans[owner.GetComponent<AvengerShipFight>().whichLeviathan].transform.GetChild(0).gameObject; owner.GetComponent<AvengerShipFight>().seekLeviathan = owner.GetComponent<AvengerShipFight>().leviathans[owner.GetComponent<AvengerShipFight>().whichLeviathan].gameObject; owner.GetComponent<AvengerShipFight>().seek.target = owner.GetComponent<AvengerShipFight>().seekLeviathan.transform.position; } } else if(Vector3.Distance(owner.GetComponent<AvengerShipFight>().transform.position, owner.GetComponent<AvengerShipFight>().seekLeviathan.transform.position) > 100f) { owner.GetComponent<AvengerShipFight>().stateMachine.ChangeState(new TargetLeviathan()); } else { owner.GetComponent<AvengerShipFight>().flee.target = owner.GetComponent<AvengerShipFight>().seekLeviathan.transform.position; } } } // Start is called before the first frame update void Start() { seek = GetComponent<Seek>(); flee = GetComponent<Flee>(); leviathans = GameObject.FindGameObjectsWithTag("leviathan"); stateMachine = GetComponent<StateMachine>(); stateMachine.ChangeState(new TargetLeviathan()); } // Update is called once per frame void Update() { leviathans = GameObject.FindGameObjectsWithTag("leviathan"); if(leviathans.Length == 0) { int avengerShipICount = GameObject.FindGameObjectsWithTag("avengershipI").Length; int avengerShipIICount = GameObject.FindGameObjectsWithTag("avengershipII").Length; PlayerPrefs.SetInt("avengerShipICount", avengerShipICount); PlayerPrefs.SetInt("avengerShipIICount", avengerShipIICount); SceneManager.LoadScene(sceneName: "13SanctuaryII"); } } }
51.497041
217
0.636217
[ "MIT" ]
bibeezi/GamesEngines2
Assets/Scripts/AvengerShipFight.cs
8,703
C#
using QFSW.QC.QGUI; using UnityEditor; using UnityEngine; namespace QFSW.QC.Editor { [CustomPropertyDrawer(typeof(ModifierKeyCombo), true)] public class ModifierKeyComboEditor : PropertyDrawer { private readonly GUIContent _shiftLabel = new GUIContent("shift"); private readonly GUIContent _altLabel = new GUIContent("alt"); private readonly GUIContent _ctrlLabel = new GUIContent("ctrl"); public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) { LayoutController layout = new LayoutController(position); EditorGUI.BeginProperty(layout.CurrentRect, label, property); const float boolWidth = 10; bool enableState = GUI.enabled; float boolLabelWidth = QGUILayout.GetMaxContentSize(EditorStyles.label, _shiftLabel, _altLabel, _ctrlLabel).x; SerializedProperty key = property.FindPropertyRelative("Key"); SerializedProperty ctrl = property.FindPropertyRelative("Ctrl"); SerializedProperty alt = property.FindPropertyRelative("Alt"); SerializedProperty shift = property.FindPropertyRelative("Shift"); GUI.enabled &= ((KeyCode)key.enumValueIndex) != KeyCode.None; EditorGUI.LabelField(layout.ReserveHorizontalReversed(boolLabelWidth), _shiftLabel); EditorGUI.PropertyField(layout.ReserveHorizontalReversed(boolWidth), shift, GUIContent.none); EditorGUI.LabelField(layout.ReserveHorizontalReversed(boolLabelWidth), _altLabel); EditorGUI.PropertyField(layout.ReserveHorizontalReversed(boolWidth), alt, GUIContent.none); EditorGUI.LabelField(layout.ReserveHorizontalReversed(boolLabelWidth), _ctrlLabel); EditorGUI.PropertyField(layout.ReserveHorizontalReversed(boolWidth), ctrl, GUIContent.none); GUI.enabled = enableState; EditorGUI.PropertyField(layout.CurrentRect, key, label); EditorGUI.EndProperty(); } } }
49.47619
123
0.694418
[ "MIT" ]
Momonyaro/Usurper
Usurper/Assets/Plugins/QFSW/Quantum Console/Source/Editor/ModifierKeyComboEditor.cs
2,080
C#
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Cloud.Retail.V2.Snippets { // [START retail_v2_generated_ProductService_AddLocalInventories_async] using Google.Cloud.Retail.V2; using Google.LongRunning; using Google.Protobuf.WellKnownTypes; using System.Threading.Tasks; public sealed partial class GeneratedProductServiceClientSnippets { /// <summary>Snippet for AddLocalInventoriesAsync</summary> /// <remarks> /// This snippet has been automatically generated for illustrative purposes only. /// It may require modifications to work in your environment. /// </remarks> public async Task AddLocalInventoriesRequestObjectAsync() { // Create client ProductServiceClient productServiceClient = await ProductServiceClient.CreateAsync(); // Initialize request argument(s) AddLocalInventoriesRequest request = new AddLocalInventoriesRequest { ProductAsProductName = ProductName.FromProjectLocationCatalogBranchProduct("[PROJECT]", "[LOCATION]", "[CATALOG]", "[BRANCH]", "[PRODUCT]"), LocalInventories = { new LocalInventory(), }, AddMask = new FieldMask(), AddTime = new Timestamp(), AllowMissing = false, }; // Make the request Operation<AddLocalInventoriesResponse, AddLocalInventoriesMetadata> response = await productServiceClient.AddLocalInventoriesAsync(request); // Poll until the returned long-running operation is complete Operation<AddLocalInventoriesResponse, AddLocalInventoriesMetadata> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result AddLocalInventoriesResponse result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<AddLocalInventoriesResponse, AddLocalInventoriesMetadata> retrievedResponse = await productServiceClient.PollOnceAddLocalInventoriesAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result AddLocalInventoriesResponse retrievedResult = retrievedResponse.Result; } } } // [END retail_v2_generated_ProductService_AddLocalInventories_async] }
46.728571
175
0.682054
[ "Apache-2.0" ]
AlexandrTrf/google-cloud-dotnet
apis/Google.Cloud.Retail.V2/Google.Cloud.Retail.V2.GeneratedSnippets/ProductServiceClient.AddLocalInventoriesRequestObjectAsyncSnippet.g.cs
3,271
C#
#region License(Apache Version 2.0) /****************************************** * Copyright ®2017-Now WangHuaiSheng. * 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. * Detail: https://github.com/WangHuaiSheng/WitsWay/LICENSE * ***************************************/ #endregion #region ChangeLog /****************************************** * 2017-10-7 OutMan Create * * ***************************************/ #endregion using System.Reflection; using WitsWay.Utilities.FastReflection.Property; namespace WitsWay.Utilities.FastReflection.Cache { /// <summary> /// 属性存取器缓存 /// </summary> public class PropertyAccessorCache : FastReflectionCache<PropertyInfo, IPropertyAccessor> { /// <summary> /// 创建IPropertyAccessor接口实例 /// </summary> /// <param name="key">PropertyInfo</param> /// <returns>IPropertyAccessor接口实例</returns> protected override IPropertyAccessor Create(PropertyInfo key) { return new PropertyAccessor(key); } } }
36.452381
93
0.630307
[ "Apache-2.0" ]
wanghuaisheng/WitsWay
Solutions/AppUtilities/Utilities/FastReflection/Cache/PropertyAccessorCache.cs
1,568
C#
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.Aws.WafV2.Outputs { [OutputType] public sealed class WebAclRuleStatementRateBasedStatementScopeDownStatementNotStatementStatementOrStatementStatement { /// <summary> /// A rule statement that defines a string match search for AWS WAF to apply to web requests. See Byte Match Statement below for details. /// </summary> public readonly Outputs.WebAclRuleStatementRateBasedStatementScopeDownStatementNotStatementStatementOrStatementStatementByteMatchStatement? ByteMatchStatement; /// <summary> /// A rule statement used to identify web requests based on country of origin. See GEO Match Statement below for details. /// </summary> public readonly Outputs.WebAclRuleStatementRateBasedStatementScopeDownStatementNotStatementStatementOrStatementStatementGeoMatchStatement? GeoMatchStatement; /// <summary> /// A rule statement used to detect web requests coming from particular IP addresses or address ranges. See IP Set Reference Statement below for details. /// </summary> public readonly Outputs.WebAclRuleStatementRateBasedStatementScopeDownStatementNotStatementStatementOrStatementStatementIpSetReferenceStatement? IpSetReferenceStatement; /// <summary> /// A rule statement used to search web request components for matches with regular expressions. See Regex Pattern Set Reference Statement below for details. /// </summary> public readonly Outputs.WebAclRuleStatementRateBasedStatementScopeDownStatementNotStatementStatementOrStatementStatementRegexPatternSetReferenceStatement? RegexPatternSetReferenceStatement; /// <summary> /// A rule statement that compares a number of bytes against the size of a request component, using a comparison operator, such as greater than (&gt;) or less than (&lt;). See Size Constraint Statement below for more details. /// </summary> public readonly Outputs.WebAclRuleStatementRateBasedStatementScopeDownStatementNotStatementStatementOrStatementStatementSizeConstraintStatement? SizeConstraintStatement; /// <summary> /// An SQL injection match condition identifies the part of web requests, such as the URI or the query string, that you want AWS WAF to inspect. See SQL Injection Match Statement below for details. /// </summary> public readonly Outputs.WebAclRuleStatementRateBasedStatementScopeDownStatementNotStatementStatementOrStatementStatementSqliMatchStatement? SqliMatchStatement; /// <summary> /// A rule statement that defines a cross-site scripting (XSS) match search for AWS WAF to apply to web requests. See XSS Match Statement below for details. /// </summary> public readonly Outputs.WebAclRuleStatementRateBasedStatementScopeDownStatementNotStatementStatementOrStatementStatementXssMatchStatement? XssMatchStatement; [OutputConstructor] private WebAclRuleStatementRateBasedStatementScopeDownStatementNotStatementStatementOrStatementStatement( Outputs.WebAclRuleStatementRateBasedStatementScopeDownStatementNotStatementStatementOrStatementStatementByteMatchStatement? byteMatchStatement, Outputs.WebAclRuleStatementRateBasedStatementScopeDownStatementNotStatementStatementOrStatementStatementGeoMatchStatement? geoMatchStatement, Outputs.WebAclRuleStatementRateBasedStatementScopeDownStatementNotStatementStatementOrStatementStatementIpSetReferenceStatement? ipSetReferenceStatement, Outputs.WebAclRuleStatementRateBasedStatementScopeDownStatementNotStatementStatementOrStatementStatementRegexPatternSetReferenceStatement? regexPatternSetReferenceStatement, Outputs.WebAclRuleStatementRateBasedStatementScopeDownStatementNotStatementStatementOrStatementStatementSizeConstraintStatement? sizeConstraintStatement, Outputs.WebAclRuleStatementRateBasedStatementScopeDownStatementNotStatementStatementOrStatementStatementSqliMatchStatement? sqliMatchStatement, Outputs.WebAclRuleStatementRateBasedStatementScopeDownStatementNotStatementStatementOrStatementStatementXssMatchStatement? xssMatchStatement) { ByteMatchStatement = byteMatchStatement; GeoMatchStatement = geoMatchStatement; IpSetReferenceStatement = ipSetReferenceStatement; RegexPatternSetReferenceStatement = regexPatternSetReferenceStatement; SizeConstraintStatement = sizeConstraintStatement; SqliMatchStatement = sqliMatchStatement; XssMatchStatement = xssMatchStatement; } } }
70.070423
233
0.79397
[ "ECL-2.0", "Apache-2.0" ]
Otanikotani/pulumi-aws
sdk/dotnet/WafV2/Outputs/WebAclRuleStatementRateBasedStatementScopeDownStatementNotStatementStatementOrStatementStatement.cs
4,975
C#
// <auto-generated> // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Microsoft.Azure.Management.Logic.Models { using Microsoft.Rest; using Newtonsoft.Json; using System.Linq; /// <summary> /// The sku type. /// </summary> public partial class Sku { /// <summary> /// Initializes a new instance of the Sku class. /// </summary> public Sku() { CustomInit(); } /// <summary> /// Initializes a new instance of the Sku class. /// </summary> /// <param name="name">The name. Possible values include: /// 'NotSpecified', 'Free', 'Shared', 'Basic', 'Standard', /// 'Premium'</param> /// <param name="plan">The reference to plan.</param> public Sku(string name, ResourceReference plan = default(ResourceReference)) { Name = name; Plan = plan; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// Gets or sets the name. Possible values include: 'NotSpecified', /// 'Free', 'Shared', 'Basic', 'Standard', 'Premium' /// </summary> [JsonProperty(PropertyName = "name")] public string Name { get; set; } /// <summary> /// Gets or sets the reference to plan. /// </summary> [JsonProperty(PropertyName = "plan")] public ResourceReference Plan { get; set; } /// <summary> /// Validate the object. /// </summary> /// <exception cref="ValidationException"> /// Thrown if validation fails /// </exception> public virtual void Validate() { if (Name == null) { throw new ValidationException(ValidationRules.CannotBeNull, "Name"); } } } }
29.766234
90
0.556283
[ "MIT" ]
0rland0Wats0n/azure-sdk-for-net
sdk/logic/Microsoft.Azure.Management.Logic/src/Generated/Models/Sku.cs
2,292
C#
using System; using Force.DeepCloner.Tests.Objects; using NUnit.Framework; namespace Force.DeepCloner.Tests { #if !NETSTANDARD [TestFixture(false)] #endif [TestFixture(true)] public class ShallowClonerSpec : BaseTest { public ShallowClonerSpec(bool isSafeInit) : base(isSafeInit) { } [Test] public void SimpleObject_Should_Be_Cloned() { var obj = new TestObject1 { Int = 42, Byte = 42, Short = 42, Long = 42, DateTime = new DateTime(2001, 01, 01), Char = 'X', Decimal = 1.2m, Double = 1.3, Float = 1.4f, String = "test1", UInt = 42, ULong = 42, UShort = 42, Bool = true, IntPtr = new IntPtr(42), UIntPtr = new UIntPtr(42), Enum = AttributeTargets.Delegate }; var cloned = obj.ShallowClone(); Assert.That(cloned.Byte, Is.EqualTo(42)); Assert.That(cloned.Short, Is.EqualTo(42)); Assert.That(cloned.UShort, Is.EqualTo(42)); Assert.That(cloned.Int, Is.EqualTo(42)); Assert.That(cloned.UInt, Is.EqualTo(42)); Assert.That(cloned.Long, Is.EqualTo(42)); Assert.That(cloned.ULong, Is.EqualTo(42)); Assert.That(cloned.Decimal, Is.EqualTo(1.2)); Assert.That(cloned.Double, Is.EqualTo(1.3)); Assert.That(cloned.Float, Is.EqualTo(1.4f)); Assert.That(cloned.Char, Is.EqualTo('X')); Assert.That(cloned.String, Is.EqualTo("test1")); Assert.That(cloned.DateTime, Is.EqualTo(new DateTime(2001, 1, 1))); Assert.That(cloned.Bool, Is.EqualTo(true)); Assert.That(cloned.IntPtr, Is.EqualTo(new IntPtr(42))); Assert.That(cloned.UIntPtr, Is.EqualTo(new UIntPtr(42))); Assert.That(cloned.Enum, Is.EqualTo(AttributeTargets.Delegate)); } private class C1 { public object X { get; set; } } [Test] public void Reference_Should_Not_Be_Copied() { var c1 = new C1(); c1.X = new object(); var clone = c1.ShallowClone(); Assert.That(clone.X, Is.EqualTo(c1.X)); } private struct S1 : IDisposable { public int X; public void Dispose() { } } [Test] public void Struct_Should_Be_Cloned() { var c1 = new S1(); c1.X = 1; var clone = c1.ShallowClone(); c1.X = 2; Assert.That(clone.X, Is.EqualTo(1)); } [Test] public void Struct_As_Object_Should_Be_Cloned() { var c1 = new S1(); c1.X = 1; var clone = (S1)((IDisposable)c1).ShallowClone(); c1.X = 2; Assert.That(clone.X, Is.EqualTo(1)); } [Test] public void Struct_As_Interface_Should_Be_Cloned() { var c1 = new DoableStruct1() as IDoable; Assert.That(c1.Do(), Is.EqualTo(1)); Assert.That(c1.Do(), Is.EqualTo(2)); var clone = c1.ShallowClone(); Assert.That(c1.Do(), Is.EqualTo(3)); Assert.That(clone.Do(), Is.EqualTo(3)); } [Test] public void Primitive_Should_Be_Cloned() { Assert.That(((object)null).ShallowClone(), Is.Null); Assert.That(3.ShallowClone(), Is.EqualTo(3)); } [Test] public void Array_Should_Be_Cloned() { var a = new[] { 3, 4 }; var clone = a.ShallowClone(); Assert.That(clone.Length, Is.EqualTo(2)); Assert.That(clone[0], Is.EqualTo(3)); Assert.That(clone[1], Is.EqualTo(4)); } } }
26.111111
324
0.654664
[ "MIT" ]
ELEMENTSECM/DeepCloner
DeepCloner.Tests/ShallowClonerSpec.cs
3,057
C#
using System; using System.Collections.Generic; using System.Reflection; using GraphQL.Conventions.Attributes; using GraphQL.Conventions.Attributes.Collectors; using GraphQL.Conventions.Attributes.MetaData; using GraphQL.Conventions.Tests.Templates; using GraphQL.Conventions.Tests.Templates.Extensions; namespace GraphQL.Conventions.Tests.Attributes.Collectors { public class AttributeCollectorTests : TestBase { private readonly AttributeCollector<IAttribute> _collector = new AttributeCollector<IAttribute>(); [Test] public void Can_Find_Default_Attributes() { var attributes = _collector .CollectAttributes(typeof(TypeWithDefaultAttribute).GetTypeInfo()) .ExcludeExecutionFilters(); attributes.Count.ShouldEqual(2); attributes[0].GetType().ShouldEqual(typeof(CoreAttribute)); attributes[1].GetType().ShouldEqual(typeof(NameAttribute)); } [Test] public void Can_Find_Explicit_Attributes() { var attributes = _collector .CollectAttributes(typeof(TypeWithExplicitAttribute).GetTypeInfo()) .ExcludeExecutionFilters(); attributes.Count.ShouldEqual(3); attributes[0].GetType().ShouldEqual(typeof(CoreAttribute)); attributes[1].GetType().ShouldEqual(typeof(NameAttribute)); attributes[2].GetType().ShouldEqual(typeof(TestAttribute)); ((TestAttribute)attributes[2]).Identifier.ShouldEqual(1); } [Test] public void Can_Find_Explicit_Attributes_On_Derived_Types() { var attributes = _collector .CollectAttributes(typeof(DerivedTypeWithExplicitAttribute).GetTypeInfo()) .ExcludeExecutionFilters(); attributes.Count.ShouldEqual(5); attributes[0].GetType().ShouldEqual(typeof(CoreAttribute)); attributes[1].GetType().ShouldEqual(typeof(NameAttribute)); attributes[2].GetType().ShouldEqual(typeof(TestAttribute)); ((TestAttribute)attributes[2]).Identifier.ShouldEqual(1); attributes[3].GetType().ShouldEqual(typeof(TestAttribute)); ((TestAttribute)attributes[3]).Identifier.ShouldEqual(2); attributes[4].GetType().ShouldEqual(typeof(TestAttribute)); ((TestAttribute)attributes[4]).Identifier.ShouldEqual(3); } [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] class TestAttribute : Attribute, IAttribute { public List<IAttribute> AssociatedAttributes => new List<IAttribute>(); public int ApplicationOrder => 0; public AttributeApplicationPhase Phase => AttributeApplicationPhase.MetaDataDerivation; public int Identifier { get; set; } } class TypeWithDefaultAttribute { } [Test(Identifier = 1)] class TypeWithExplicitAttribute { } [Test(Identifier = 3)] [Test(Identifier = 2)] class DerivedTypeWithExplicitAttribute : TypeWithExplicitAttribute { } } }
37.564706
106
0.65393
[ "MIT" ]
BilyachenkoOY/conventions
test/GraphQL.Conventions.Tests/Attributes/Collectors/AttributeCollectorTests.cs
3,193
C#
#if !NETSTANDARD13 /* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the monitoring-2010-08-01.normal.json service model. */ using Amazon.CloudWatch; using Amazon.CloudWatch.Model; using Moq; using System; using System.Linq; using AWSSDK_DotNet35.UnitTests.TestTools; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace AWSSDK_DotNet35.UnitTests.PaginatorTests { [TestClass] public class CloudWatchPaginatorTests { private static Mock<AmazonCloudWatchClient> _mockClient; [ClassInitialize()] public static void ClassInitialize(TestContext a) { _mockClient = new Mock<AmazonCloudWatchClient>("access key", "secret", Amazon.RegionEndpoint.USEast1); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("CloudWatch")] public void DescribeAlarmHistoryTest_TwoPages() { var request = InstantiateClassGenerator.Execute<DescribeAlarmHistoryRequest>(); var firstResponse = InstantiateClassGenerator.Execute<DescribeAlarmHistoryResponse>(); var secondResponse = InstantiateClassGenerator.Execute<DescribeAlarmHistoryResponse>(); secondResponse.NextToken = null; _mockClient.SetupSequence(x => x.DescribeAlarmHistory(request)).Returns(firstResponse).Returns(secondResponse); var paginator = _mockClient.Object.Paginators.DescribeAlarmHistory(request); Assert.AreEqual(2, paginator.Responses.ToList().Count); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("CloudWatch")] [ExpectedException(typeof(System.InvalidOperationException), "Paginator has already been consumed and cannot be reused. Please create a new instance.")] public void DescribeAlarmHistoryTest__OnlyUsedOnce() { var request = InstantiateClassGenerator.Execute<DescribeAlarmHistoryRequest>(); var response = InstantiateClassGenerator.Execute<DescribeAlarmHistoryResponse>(); response.NextToken = null; _mockClient.Setup(x => x.DescribeAlarmHistory(request)).Returns(response); var paginator = _mockClient.Object.Paginators.DescribeAlarmHistory(request); // Should work the first time paginator.Responses.ToList(); // Second time should throw an exception paginator.Responses.ToList(); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("CloudWatch")] public void DescribeAlarmsTest_TwoPages() { var request = InstantiateClassGenerator.Execute<DescribeAlarmsRequest>(); var firstResponse = InstantiateClassGenerator.Execute<DescribeAlarmsResponse>(); var secondResponse = InstantiateClassGenerator.Execute<DescribeAlarmsResponse>(); secondResponse.NextToken = null; _mockClient.SetupSequence(x => x.DescribeAlarms(request)).Returns(firstResponse).Returns(secondResponse); var paginator = _mockClient.Object.Paginators.DescribeAlarms(request); Assert.AreEqual(2, paginator.Responses.ToList().Count); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("CloudWatch")] [ExpectedException(typeof(System.InvalidOperationException), "Paginator has already been consumed and cannot be reused. Please create a new instance.")] public void DescribeAlarmsTest__OnlyUsedOnce() { var request = InstantiateClassGenerator.Execute<DescribeAlarmsRequest>(); var response = InstantiateClassGenerator.Execute<DescribeAlarmsResponse>(); response.NextToken = null; _mockClient.Setup(x => x.DescribeAlarms(request)).Returns(response); var paginator = _mockClient.Object.Paginators.DescribeAlarms(request); // Should work the first time paginator.Responses.ToList(); // Second time should throw an exception paginator.Responses.ToList(); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("CloudWatch")] public void DescribeInsightRulesTest_TwoPages() { var request = InstantiateClassGenerator.Execute<DescribeInsightRulesRequest>(); var firstResponse = InstantiateClassGenerator.Execute<DescribeInsightRulesResponse>(); var secondResponse = InstantiateClassGenerator.Execute<DescribeInsightRulesResponse>(); secondResponse.NextToken = null; _mockClient.SetupSequence(x => x.DescribeInsightRules(request)).Returns(firstResponse).Returns(secondResponse); var paginator = _mockClient.Object.Paginators.DescribeInsightRules(request); Assert.AreEqual(2, paginator.Responses.ToList().Count); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("CloudWatch")] [ExpectedException(typeof(System.InvalidOperationException), "Paginator has already been consumed and cannot be reused. Please create a new instance.")] public void DescribeInsightRulesTest__OnlyUsedOnce() { var request = InstantiateClassGenerator.Execute<DescribeInsightRulesRequest>(); var response = InstantiateClassGenerator.Execute<DescribeInsightRulesResponse>(); response.NextToken = null; _mockClient.Setup(x => x.DescribeInsightRules(request)).Returns(response); var paginator = _mockClient.Object.Paginators.DescribeInsightRules(request); // Should work the first time paginator.Responses.ToList(); // Second time should throw an exception paginator.Responses.ToList(); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("CloudWatch")] public void GetMetricDataTest_TwoPages() { var request = InstantiateClassGenerator.Execute<GetMetricDataRequest>(); var firstResponse = InstantiateClassGenerator.Execute<GetMetricDataResponse>(); var secondResponse = InstantiateClassGenerator.Execute<GetMetricDataResponse>(); secondResponse.NextToken = null; _mockClient.SetupSequence(x => x.GetMetricData(request)).Returns(firstResponse).Returns(secondResponse); var paginator = _mockClient.Object.Paginators.GetMetricData(request); Assert.AreEqual(2, paginator.Responses.ToList().Count); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("CloudWatch")] [ExpectedException(typeof(System.InvalidOperationException), "Paginator has already been consumed and cannot be reused. Please create a new instance.")] public void GetMetricDataTest__OnlyUsedOnce() { var request = InstantiateClassGenerator.Execute<GetMetricDataRequest>(); var response = InstantiateClassGenerator.Execute<GetMetricDataResponse>(); response.NextToken = null; _mockClient.Setup(x => x.GetMetricData(request)).Returns(response); var paginator = _mockClient.Object.Paginators.GetMetricData(request); // Should work the first time paginator.Responses.ToList(); // Second time should throw an exception paginator.Responses.ToList(); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("CloudWatch")] public void ListDashboardsTest_TwoPages() { var request = InstantiateClassGenerator.Execute<ListDashboardsRequest>(); var firstResponse = InstantiateClassGenerator.Execute<ListDashboardsResponse>(); var secondResponse = InstantiateClassGenerator.Execute<ListDashboardsResponse>(); secondResponse.NextToken = null; _mockClient.SetupSequence(x => x.ListDashboards(request)).Returns(firstResponse).Returns(secondResponse); var paginator = _mockClient.Object.Paginators.ListDashboards(request); Assert.AreEqual(2, paginator.Responses.ToList().Count); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("CloudWatch")] [ExpectedException(typeof(System.InvalidOperationException), "Paginator has already been consumed and cannot be reused. Please create a new instance.")] public void ListDashboardsTest__OnlyUsedOnce() { var request = InstantiateClassGenerator.Execute<ListDashboardsRequest>(); var response = InstantiateClassGenerator.Execute<ListDashboardsResponse>(); response.NextToken = null; _mockClient.Setup(x => x.ListDashboards(request)).Returns(response); var paginator = _mockClient.Object.Paginators.ListDashboards(request); // Should work the first time paginator.Responses.ToList(); // Second time should throw an exception paginator.Responses.ToList(); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("CloudWatch")] public void ListMetricsTest_TwoPages() { var request = InstantiateClassGenerator.Execute<ListMetricsRequest>(); var firstResponse = InstantiateClassGenerator.Execute<ListMetricsResponse>(); var secondResponse = InstantiateClassGenerator.Execute<ListMetricsResponse>(); secondResponse.NextToken = null; _mockClient.SetupSequence(x => x.ListMetrics(request)).Returns(firstResponse).Returns(secondResponse); var paginator = _mockClient.Object.Paginators.ListMetrics(request); Assert.AreEqual(2, paginator.Responses.ToList().Count); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("CloudWatch")] [ExpectedException(typeof(System.InvalidOperationException), "Paginator has already been consumed and cannot be reused. Please create a new instance.")] public void ListMetricsTest__OnlyUsedOnce() { var request = InstantiateClassGenerator.Execute<ListMetricsRequest>(); var response = InstantiateClassGenerator.Execute<ListMetricsResponse>(); response.NextToken = null; _mockClient.Setup(x => x.ListMetrics(request)).Returns(response); var paginator = _mockClient.Object.Paginators.ListMetrics(request); // Should work the first time paginator.Responses.ToList(); // Second time should throw an exception paginator.Responses.ToList(); } } } #endif
40.863309
160
0.672711
[ "Apache-2.0" ]
PureKrome/aws-sdk-net
sdk/test/Services/CloudWatch/UnitTests/Generated/_bcl45+netstandard/Paginators/CloudWatchPaginatorTests.cs
11,360
C#
using Game.Gameplay.Teleports; using Game.Gameplay.World; using Leopotam.Ecs; using UnityEngine; namespace Game.Gameplay.Players { public sealed class PlayerDeathSystem : IEcsRunSystem { private readonly EcsFilter<PlayerComponent, PlayerDeathRequest> requests = null; public void Run() { foreach (var i in requests) { var playerEntity = requests.GetEntity(i); ref var deadPlayer = ref requests.Get1(i); var spawnPosition = deadPlayer.spawnPosition; if (--deadPlayer.lives <= 0) { deadPlayer.isDead = true; spawnPosition = Vector2Int.zero; playerEntity.Get<WorldObjectDestroyedEvent>(); } playerEntity.Get<TeleportToPositionRequest>().newPosition = spawnPosition; playerEntity.Get<PlayerScoreChangedEvent>(); } } } }
35.111111
90
0.600211
[ "MIT" ]
SH42913/pacmanecs
Assets/Game.Gameplay/Players/Systems/PlayerDeathSystem.cs
950
C#
using System; using System.Diagnostics; using System.Windows.Forms; using Hg.DoomHistory.Utilities; namespace Hg.DoomHistory.Controls { public partial class SlotControl : UserControl { #region Members public SlotControl() { InitializeComponent(); } private void pictureBoxScreenshot_DoubleClick(object sender, EventArgs e) { if (!string.IsNullOrEmpty(pictureBoxScreenshot.ImageLocation)) { try { Process.Start(pictureBoxScreenshot.ImageLocation); } catch (Exception ex) { Logger.Log("pictureBoxScreenshot_DoubleClick: Exception: " + ex.Message, LogLevel.Debug); Logger.LogException(ex); } } } #endregion } }
25.485714
109
0.544843
[ "MIT" ]
HgAlexx/Hg.DoomHistory
Hg.DoomHistory/Controls/SlotControl.cs
894
C#
#region License // // Copyright (c) 2007-2009, Sean Chambers <schambers80@gmail.com> // // 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; using System.Collections.Generic; using System.Linq; using System.Text; using FluentMigrator.Infrastructure.Extensions; using FluentMigrator.Model; using FluentMigrator.VersionTableInfo; namespace FluentMigrator.Infrastructure { public static class DefaultMigrationConventions { public static string GetPrimaryKeyName(string tableName) { return "PK_" + tableName; } public static string GetForeignKeyName(ForeignKeyDefinition foreignKey) { var sb = new StringBuilder(); sb.Append("FK_"); sb.Append(foreignKey.ForeignTable); foreach (string foreignColumn in foreignKey.ForeignColumns) { sb.Append("_"); sb.Append(foreignColumn); } sb.Append("_"); sb.Append(foreignKey.PrimaryTable); foreach (string primaryColumn in foreignKey.PrimaryColumns) { sb.Append("_"); sb.Append(primaryColumn); } return sb.ToString(); } public static string GetIndexName(IndexDefinition index) { var sb = new StringBuilder(); sb.Append("IX_"); sb.Append(index.TableName); foreach (IndexColumnDefinition column in index.Columns) { sb.Append("_"); sb.Append(column.Name); } return sb.ToString(); } public static bool TypeIsMigration(Type type) { return typeof(IMigration).IsAssignableFrom(type) && type.HasAttribute<MigrationAttribute>(); } public static bool TypeIsProfile(Type type) { return typeof(IMigration).IsAssignableFrom(type) && type.HasAttribute<ProfileAttribute>(); } public static bool TypeIsVersionTableMetaData(Type type) { return typeof(IVersionTableMetaData).IsAssignableFrom(type) && type.HasAttribute<VersionTableMetaDataAttribute>(); } public static MigrationMetadata GetMetadataForMigration(Type type) { var migrationAttribute = type.GetOneAttribute<MigrationAttribute>(); var metadata = new MigrationMetadata { Type = type, Version = migrationAttribute.Version }; foreach (MigrationTraitAttribute traitAttribute in type.GetAllAttributes<MigrationTraitAttribute>()) metadata.AddTrait(traitAttribute.Name, traitAttribute.Value); return metadata; } public static string GetWorkingDirectory() { return Environment.CurrentDirectory; } public static string GetConstraintName(ConstraintDefinition expression) { StringBuilder sb = new StringBuilder(); if (expression.IsPrimaryKeyConstraint) { sb.Append("PK_"); } else { sb.Append("UC_"); } sb.Append(expression.TableName); foreach (var column in expression.Columns) { sb.Append("_" + column); } return sb.ToString(); } public static bool TypeHasTags(Type type) { return type.GetOneAttribute<TagsAttribute>() != null; } public static bool TypeHasMatchingTags(Type type, IEnumerable<string> tagsToMatch) { var tags = type.GetAllAttributes<TagsAttribute>().SelectMany(x => x.TagNames).ToArray(); return tags.Any() && tagsToMatch.All(t => tags.Any(t.Equals)); } } }
30.822695
126
0.608376
[ "Apache-2.0" ]
robertmircea/fluentmigrator
src/FluentMigrator/Infrastructure/DefaultMigrationConventions.cs
4,346
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the ecr-public-2020-10-30.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.ECRPublic.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.ECRPublic.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for DescribeImages operation /// </summary> public class DescribeImagesResponseUnmarshaller : JsonResponseUnmarshaller { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context) { DescribeImagesResponse response = new DescribeImagesResponse(); context.Read(); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { if (context.TestExpression("imageDetails", targetDepth)) { var unmarshaller = new ListUnmarshaller<ImageDetail, ImageDetailUnmarshaller>(ImageDetailUnmarshaller.Instance); response.ImageDetails = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("nextToken", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; response.NextToken = unmarshaller.Unmarshall(context); continue; } } return response; } /// <summary> /// Unmarshaller error response to exception. /// </summary> /// <param name="context"></param> /// <param name="innerException"></param> /// <param name="statusCode"></param> /// <returns></returns> public override AmazonServiceException UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode) { var errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context); errorResponse.InnerException = innerException; errorResponse.StatusCode = statusCode; var responseBodyBytes = context.GetResponseBodyBytes(); using (var streamCopy = new MemoryStream(responseBodyBytes)) using (var contextCopy = new JsonUnmarshallerContext(streamCopy, false, null)) { if (errorResponse.Code != null && errorResponse.Code.Equals("ImageNotFoundException")) { return ImageNotFoundExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidParameterException")) { return InvalidParameterExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("RepositoryNotFoundException")) { return RepositoryNotFoundExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("ServerException")) { return ServerExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } } return new AmazonECRPublicException(errorResponse.Message, errorResponse.InnerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode); } private static DescribeImagesResponseUnmarshaller _instance = new DescribeImagesResponseUnmarshaller(); internal static DescribeImagesResponseUnmarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static DescribeImagesResponseUnmarshaller Instance { get { return _instance; } } } }
40.976563
193
0.622116
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/ECRPublic/Generated/Model/Internal/MarshallTransformations/DescribeImagesResponseUnmarshaller.cs
5,245
C#
using Troschuetz.Random; namespace GoRogue.DiceNotation.Terms { /// <summary> /// Term representing the addition operator -- adds two terms together. /// </summary> public class AddTerm : ITerm { /// <summary> /// Constructor. Takes the two terms to add. /// </summary> /// <param name="term1">Left-hand side.</param> /// <param name="term2">Right-hand side.</param> public AddTerm(ITerm term1, ITerm term2) { Term1 = term1; Term2 = term2; } /// <summary> /// First term (left-hand side). /// </summary> public ITerm Term1 { get; private set; } /// <summary> /// Second term (right-hand side). /// </summary> public ITerm Term2 { get; private set; } /// <summary> /// Adds its two terms together, evaluating those two terms as necessary. /// </summary> /// <param name="rng">The rng to use, passed to other terms.</param> /// <returns>The result of adding <see cref="Term1"/> and <see cref="Term2"/>.</returns> public int GetResult(IGenerator rng) { return Term1.GetResult(rng) + Term2.GetResult(rng); } /// <summary> /// Converts to a parenthesized string. /// </summary> /// <returns>A parenthesized string representing the term.</returns> public override string ToString() { return "(" + Term1 + "+" + Term2 + ")"; } } }
26.18
90
0.630252
[ "MIT" ]
Chris3606/GoRogue
GoRogue/DiceNotation/Terms/AddTerm.cs
1,311
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.ServiceBus.Models { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Azure.Management.ServiceBus; using Microsoft.Rest; /// <summary> /// Exception thrown for an invalid response with ErrorResponse /// information. /// </summary> public class ErrorResponseException : RestException { /// <summary> /// Gets information about the associated HTTP request. /// </summary> public HttpRequestMessageWrapper Request { get; set; } /// <summary> /// Gets information about the associated HTTP response. /// </summary> public HttpResponseMessageWrapper Response { get; set; } /// <summary> /// Gets or sets the body object. /// </summary> public ErrorResponse Body { get; set; } /// <summary> /// Initializes a new instance of the ErrorResponseException class. /// </summary> public ErrorResponseException() { } /// <summary> /// Initializes a new instance of the ErrorResponseException class. /// </summary> /// <param name="message">The exception message.</param> public ErrorResponseException(string message) : this(message, null) { } /// <summary> /// Initializes a new instance of the ErrorResponseException class. /// </summary> /// <param name="message">The exception message.</param> /// <param name="innerException">Inner exception.</param> public ErrorResponseException(string message, System.Exception innerException) : base(message, innerException) { } } }
32.359375
86
0.624819
[ "MIT" ]
azure-keyvault/azure-sdk-for-net
src/SDKs/ServiceBus/Management.ServiceBus/Generated/Models/ErrorResponseException.cs
2,071
C#
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using OrchardCore.Infrastructure.Html; using Xunit; namespace OrchardCore.Tests.Html { public class HtmlSanitizerTests { private static readonly HtmlSanitizerService _sanitizer = new HtmlSanitizerService(Options.Create(new HtmlSanitizerOptions())); [Theory] [InlineData("<script>alert('xss')</script><div onload=\"alert('xss')\">Test<img src=\"test.gif\" style=\"background-image: url(javascript:alert('xss')); margin: 10px\"></div>", "<div>Test<img src=\"test.gif\" style=\"margin: 10px\"></div>")] [InlineData("<IMG SRC=javascript:alert(\"XSS\")>", @"<img>")] [InlineData("<a href=\"javascript: alert('xss')\">Click me</a>", @"<a>Click me</a>")] [InlineData("<a href=\"[locale 'en']javascript: alert('xss')[/locale]\">Click me</a>", @"<a>Click me</a>")] public void ShouldSanitizeHTML(string html, string sanitized) { // Setup var output = _sanitizer.Sanitize(html); // Test Assert.Equal(output, sanitized); } [Fact] public void ShouldConfigureSanitizer() { var services = new ServiceCollection(); services.AddOptions<HtmlSanitizerOptions>(); services.ConfigureHtmlSanitizer((sanitizer) => { sanitizer.AllowedAttributes.Add("class"); }); services.AddScoped<IHtmlSanitizerService, HtmlSanitizerService>(); var sanitizer = services.BuildServiceProvider().GetService<IHtmlSanitizerService>(); var input = @"<a href=""bar"" class=""foo"">baz</a>"; var sanitized = sanitizer.Sanitize(input); Assert.Equal(input, sanitized); } [Fact] public void ShouldReconfigureSanitizer() { // Setup. With defaults. var services = new ServiceCollection(); services.AddOptions<HtmlSanitizerOptions>(); services.ConfigureHtmlSanitizer((sanitizer) => { sanitizer.AllowedAttributes.Add("class"); }); // Act. Reconfigure to remove defaults. services.Configure<HtmlSanitizerOptions>(o => { o.Configure.Clear(); }); // Test. services.AddScoped<IHtmlSanitizerService, HtmlSanitizerService>(); var sanitizer = services.BuildServiceProvider().GetService<IHtmlSanitizerService>(); var input = @"<a href=""bar"" class=""foo"">baz</a>"; var sanitized = sanitizer.Sanitize(input); Assert.Equal(@"<a href=""bar"">baz</a>", sanitized); } } }
37.808219
249
0.588043
[ "BSD-3-Clause" ]
1051324354/OrchardCore
test/OrchardCore.Tests/Html/HtmlSanitizerTests.cs
2,760
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 waf-regional-2016-11-28.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.WAFRegional.Model { /// <summary> /// This is the response object from the ListSizeConstraintSets operation. /// </summary> public partial class ListSizeConstraintSetsResponse : AmazonWebServiceResponse { private string _nextMarker; private List<SizeConstraintSetSummary> _sizeConstraintSets = new List<SizeConstraintSetSummary>(); /// <summary> /// Gets and sets the property NextMarker. /// <para> /// If you have more <code>SizeConstraintSet</code> objects than the number that you specified /// for <code>Limit</code> in the request, the response includes a <code>NextMarker</code> /// value. To list more <code>SizeConstraintSet</code> objects, submit another <code>ListSizeConstraintSets</code> /// request, and specify the <code>NextMarker</code> value from the response in the <code>NextMarker</code> /// value in the next request. /// </para> /// </summary> public string NextMarker { get { return this._nextMarker; } set { this._nextMarker = value; } } // Check to see if NextMarker property is set internal bool IsSetNextMarker() { return this._nextMarker != null; } /// <summary> /// Gets and sets the property SizeConstraintSets. /// <para> /// An array of <a>SizeConstraintSetSummary</a> objects. /// </para> /// </summary> public List<SizeConstraintSetSummary> SizeConstraintSets { get { return this._sizeConstraintSets; } set { this._sizeConstraintSets = value; } } // Check to see if SizeConstraintSets property is set internal bool IsSetSizeConstraintSets() { return this._sizeConstraintSets != null && this._sizeConstraintSets.Count > 0; } } }
35.658228
122
0.653887
[ "Apache-2.0" ]
Bio2hazard/aws-sdk-net
sdk/src/Services/WAFRegional/Generated/Model/ListSizeConstraintSetsResponse.cs
2,817
C#
using System; using System.Collections.Generic; using System.Text; namespace SoftJail.Data.Models { public class Cell { public Cell() { this.Prisoners = new HashSet<Prisoner>(); } public int Id { get; set; } public int CellNumber { get; set; } public bool HasWindow { get; set; } public int DepartmentId { get; set; } public virtual Department Department { get; set; } public virtual ICollection<Prisoner> Prisoners { get; set; } } } //• Id – integer, Primary Key //• CellNumber – integer in the range [1, 1000] (required) //• HasWindow – bool(required) //• DepartmentId - integer, foreign key(required) //• Department – the cell's department (required) //• Prisoners - collection of type Prisoner
23.617647
68
0.627646
[ "MIT" ]
NikolayLutakov/Entity-Framework-Core
Exam Preps/02 C# DB Advanced Retake Exam Last Resolve 14 August 2020/SoftJail/Data/Models/Cell.cs
825
C#
using System; using System.Collections.Generic; using RestSharp; namespace EasyPost { public class Webhook : Resource { public string id { get; set; } public string mode { get; set; } public string url { get; set; } public DateTime? disabled_at { get; set; } /// <summary> /// Get a list of scan forms. /// </summary> /// <returns>List of EasyPost.Webhook insteances.</returns> public static List<Webhook> List(Dictionary<string, object> parameters = null) { Request request = new Request("webhooks"); WebhookList webhookList = request.Execute<WebhookList>(); return webhookList.webhooks; } /// <summary> /// Retrieve a Webhook from its id. /// </summary> /// <param name="id">String representing a webhook. Starts with "hook_".</param> /// <returns>EasyPost.User instance.</returns> public static Webhook Retrieve(string id) { Request request = new Request("webhooks/{id}"); request.AddUrlSegment("id", id); return request.Execute<Webhook>(); } /// <summary> /// Create a Webhook. /// </summary> /// <param name="parameters"> /// Dictionary containing parameters to create the carrier account with. Valid pairs: /// * { "url", string } Url of the webhook that events will be sent to. /// All invalid keys will be ignored. /// </param> /// <returns>EasyPost.Webhook instance.</returns> public static Webhook Create(Dictionary<string, object> parameters) { Request request = new Request("webhooks", Method.POST); request.AddBody(parameters, "webhook"); return request.Execute<Webhook>(); } /// <summary> /// Enable a Webhook that has been disabled previously. /// </summary> public void Update() { Request request = new Request("webhooks/{id}", Method.PUT); request.AddUrlSegment("id", id); Merge(request.Execute<Webhook>()); } public void Destroy() { Request request = new Request("webhooks/{id}", Method.DELETE); request.AddUrlSegment("id", id); request.Execute(); } } }
34.115942
93
0.569669
[ "MIT" ]
j6967chen/easypost-csharp
EasyPost/Webhook.cs
2,356
C#
using System; using System.IO; using System.Diagnostics; using System.ComponentModel; using System.Collections.Generic; using Nikki.Utils; using Nikki.Reflection.Enum; using Nikki.Reflection.Enum.CP; using Nikki.Reflection.Abstract; using Nikki.Reflection.Attributes; using Nikki.Support.Shared.Parts.CarParts; using CoreExtensions.IO; using CoreExtensions.Conversions; namespace Nikki.Support.Prostreet.Attributes { /// <summary> /// A <see cref="CPAttribute"/> with a string value represented as a binary key. /// </summary> [DebuggerDisplay("Attribute: {AttribType} | Type: {Type} | Value: {Value}")] public class KeyAttribute : CPAttribute { /// <summary> /// <see cref="CarPartAttribType"/> type of this <see cref="KeyAttribute"/>. /// </summary> [Category("Main")] public override CarPartAttribType AttribType => CarPartAttribType.Key; /// <summary> /// Type of this <see cref="KeyAttribute"/>. /// </summary> [AccessModifiable()] [Category("Main")] public eAttribKey Type { get; set; } /// <summary> /// Key of the part to which this <see cref="CPAttribute"/> belongs to. /// </summary> [ReadOnly(true)] [TypeConverter(typeof(HexConverter))] [Category("Main")] public override uint Key { get => (uint)this.Type; set => this.Type = (eAttribKey)value; } /// <summary> /// Attribute value. /// </summary> [AccessModifiable()] [Category("Main")] public string Value { get; set; } /// <summary> /// Initializes new instance of <see cref="KeyAttribute"/>. /// </summary> public KeyAttribute() { } /// <summary> /// Initializes new instance of <see cref="KeyAttribute"/> with value provided. /// </summary> /// <param name="value">Value to set.</param> public KeyAttribute(object value) { try { this.Value = (string)value.ReinterpretCast(typeof(string)); } catch (Exception) { this.Value = String.Empty; } } /// <summary> /// Initializes new instance of <see cref="KeyAttribute"/> by reading data using /// <see cref="BinaryReader"/> provided. /// </summary> /// <param name="br"><see cref="BinaryReader"/> to read with.</param> /// <param name="key">Key of the attribute's group.</param> public KeyAttribute(BinaryReader br, uint key) { this.Key = key; this.Disassemble(br, null); } /// <summary> /// Disassembles byte array into <see cref="KeyAttribute"/> using <see cref="BinaryReader"/> /// provided. /// </summary> /// <param name="br"><see cref="BinaryReader"/> to read with.</param> /// <param name="str_reader"><see cref="BinaryReader"/> to read strings with. /// Since it is an Integer Attribute, this value can be <see langword="null"/>.</param> public override void Disassemble(BinaryReader br, BinaryReader str_reader) => this.Value = br.ReadUInt32().BinString(LookupReturn.EMPTY); /// <summary> /// Assembles <see cref="KeyAttribute"/> and writes it using <see cref="BinaryWriter"/> /// provided. /// </summary> /// <param name="bw"><see cref="BinaryWriter"/> to write with.</param> /// <param name="string_dict">Dictionary of string HashCodes and their offsets. /// Since it is an Integer Attribute, this value can be <see langword="null"/>.</param> public override void Assemble(BinaryWriter bw, Dictionary<int, int> string_dict) { bw.Write(this.Key); bw.Write(String.IsNullOrEmpty(this.Value) ? 0xFFFFFFFF : this.Value.BinHash()); } /// <summary> /// Returns attribute part label and its type as a string value. /// </summary> /// <returns>String value.</returns> public override string ToString() => this.Type.ToString(); /// <summary> /// Determines whether this instance and a specified object, which must also be a /// <see cref="KeyAttribute"/> object, have the same value. /// </summary> /// <param name="obj">The <see cref="KeyAttribute"/> to compare to this instance.</param> /// <returns>True if obj is a <see cref="KeyAttribute"/> and its value is the same as /// this instance; false otherwise. If obj is null, the method returns false. /// </returns> public override bool Equals(object obj) => obj is KeyAttribute attribute && this == attribute; /// <summary> /// Returns the hash code for this <see cref="KeyAttribute"/>. /// </summary> /// <returns>A 32-bit signed integer hash code.</returns> public override int GetHashCode() => Tuple.Create(this.Key, this.Value.BinHash()).GetHashCode(); /// <summary> /// Determines whether two specified <see cref="KeyAttribute"/> have the same value. /// </summary> /// <param name="at1">The first <see cref="KeyAttribute"/> to compare, or null.</param> /// <param name="at2">The second <see cref="KeyAttribute"/> to compare, or null.</param> /// <returns>True if the value of c1 is the same as the value of c2; false otherwise.</returns> public static bool operator ==(KeyAttribute at1, KeyAttribute at2) { if (at1 is null) return at2 is null; else if (at2 is null) return false; var key1 = at1.Value.BinHash(); var key2 = at2.Value.BinHash(); return at1.Key == at2.Key && key1 == key2; } /// <summary> /// Determines whether two specified <see cref="KeyAttribute"/> have different values. /// </summary> /// <param name="at1">The first <see cref="KeyAttribute"/> to compare, or null.</param> /// <param name="at2">The second <see cref="KeyAttribute"/> to compare, or null.</param> /// <returns>True if the value of c1 is different from the value of c2; false otherwise.</returns> public static bool operator !=(KeyAttribute at1, KeyAttribute at2) => !(at1 == at2); /// <summary> /// Creates a plain copy of the objects that contains same values. /// </summary> /// <returns>Exact plain copy of the object.</returns> public override SubPart PlainCopy() { var result = new KeyAttribute { Type = this.Type, Value = this.Value }; return result; } /// <summary> /// Converts this <see cref="KeyAttribute"/> to an attribute of type provided. /// </summary> /// <param name="type">Type of a new attribute.</param> /// <returns>New <see cref="CPAttribute"/>.</returns> public override CPAttribute ConvertTo(CarPartAttribType type) => type switch { CarPartAttribType.Boolean => new BoolAttribute(this.Value), CarPartAttribType.Floating => new FloatAttribute(this.Value), CarPartAttribType.Integer => new IntAttribute(this.Value), CarPartAttribType.String => new StringAttribute(this.Value), CarPartAttribType.TwoString => new TwoStringAttribute(this.Value), CarPartAttribType.Color => new ColorAttribute(this.Value), CarPartAttribType.CarPartID => new PartIDAttribute(this.Value), CarPartAttribType.ModelTable => new ModelTableAttribute(this.Value), _ => this }; /// <summary> /// Serializes instance into a byte array and stores it in the file provided. /// </summary> public override void Serialize(BinaryWriter bw) { bw.Write(this.Key); bw.WriteNullTermUTF8(this.Value); } /// <summary> /// Deserializes byte array into an instance by loading data from the file provided. /// </summary> public override void Deserialize(BinaryReader br) => this.Value = br.ReadNullTermUTF8(); } }
33.962617
100
0.674188
[ "MIT" ]
SpeedReflect/Nikki
Nikki/Support.Prostreet/Attributes/KeyAttribute.cs
7,270
C#
/* _BEGIN_TEMPLATE_ { "id": "EX1_614t", "name": [ "萨维亚萨特", "Xavian Satyr" ], "text": [ null, null ], "cardClass": "NEUTRAL", "type": "MINION", "cost": 1, "rarity": null, "set": "EXPERT1", "collectible": null, "dbfId": 1751 } _END_TEMPLATE_ */ namespace HREngine.Bots { class Sim_EX1_614t : SimTemplate //flameofazzinoth { // } }
12.766667
54
0.550914
[ "MIT" ]
chi-rei-den/Silverfish
cards/EXPERT1/EX1/Sim_EX1_614t.cs
393
C#
using UnityEngine; namespace Kontrol { public class CameraMovement : MonoBehaviour { public Vector2 startPosition; public Vector2 moveSpeed; public bool isStartingAtStartPosition; public bool isMoving; void Start() { if (isStartingAtStartPosition) transform.position = new Vector3(startPosition.x, startPosition.y, transform.position.z); } void FixedUpdate() { if (isMoving) { transform.Translate(moveSpeed); } } } }
21.178571
105
0.559865
[ "MIT" ]
MarcusBoay/Kontrol
SpaceShooter2/Assets/My Assets/Scripts/Camera/CameraMovement.cs
593
C#