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
namespace Singelton { public sealed class LazyLoad { public static int InitCount = 0; private static LazyLoad instance = null; private LazyLoad() { } public static LazyLoad GetInstance() { if (instance == null) { InitCount++; instance = new LazyLoad(); } return instance; } } }
19.181818
48
0.481043
[ "Apache-2.0" ]
ali515/desing-patterns
01-Creator/01-Singelton/Singelton/LazyLoad.cs
424
C#
using System.Collections.Generic; using SparkyStudios.TrakLibrary.Model.Games; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace SparkyStudios.TrakLibrary.Controls.Games { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class AgeRatingControl { public static readonly BindableProperty AgeRatingsProperty = BindableProperty.Create(nameof(AgeRatings), typeof(IEnumerable<AgeRating>), typeof(AgeRatingControl)); public AgeRatingControl() { InitializeComponent(); } public IEnumerable<AgeRating> AgeRatings { get => (IEnumerable<AgeRating>)GetValue(AgeRatingsProperty); set => SetValue(AgeRatingsProperty, value); } } }
31.16
114
0.680359
[ "Apache-2.0" ]
TheLordBritish/trak-app
SparkyStudios.TrakLibrary/Controls/Games/AgeRatingControl.xaml.cs
781
C#
 namespace iTin.Core.ComponentModel.Patterns { using System; using System.Diagnostics; /// <summary> /// /// </summary> /// <typeparam name="T"></typeparam> public class ExpressionSpecification<T> : CompositeSpecification<T> { [DebuggerBrowsable(DebuggerBrowsableState.Never)] private readonly Func<T, bool> _expression; /// <summary> /// /// </summary> /// <param name="expression"></param> public ExpressionSpecification(Func<T, bool> expression) => _expression = expression ?? throw new ArgumentNullException(); /// <summary> /// /// </summary> /// <param name="candidate"></param> /// <returns></returns> public override bool IsSatisfiedBy(T candidate) => _expression(candidate); } }
27.833333
130
0.591617
[ "MIT" ]
iAJTin/iCPUID
src/lib/net/iTin.Core/iTin.Core/ComponentModel/Patterns/Specification/ExpressionSpecification.cs
837
C#
using Microsoft.eShopWeb.ApplicationCore.Entities; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Microsoft.eShopWeb.Infrastructure.Data { public class CatalogContextSeed { public static async Task SeedAsync(CatalogContext catalogContext, ILoggerFactory loggerFactory, int? retry = 0) { catalogContext.Database.EnsureCreated(); int retryForAvailability = retry.Value; try { // TODO: Only run this if using a real database // context.Database.Migrate(); if (!catalogContext.CatalogBrands.Any()) { catalogContext.CatalogBrands.AddRange( GetPreconfiguredCatalogBrands()); await catalogContext.SaveChangesAsync(); } if (!catalogContext.CatalogTypes.Any()) { catalogContext.CatalogTypes.AddRange( GetPreconfiguredCatalogTypes()); await catalogContext.SaveChangesAsync(); } if (!catalogContext.CatalogItems.Any()) { catalogContext.CatalogItems.AddRange( GetPreconfiguredItems()); await catalogContext.SaveChangesAsync(); } } catch (Exception ex) { if (retryForAvailability < 10) { retryForAvailability++; var log = loggerFactory.CreateLogger<CatalogContextSeed>(); log.LogError(ex.Message); await SeedAsync(catalogContext, loggerFactory, retryForAvailability); } } } static IEnumerable<CatalogBrand> GetPreconfiguredCatalogBrands() { return new List<CatalogBrand>() { new CatalogBrand() { Brand = "Azure"}, new CatalogBrand() { Brand = ".NET" }, new CatalogBrand() { Brand = "Visual Studio" }, new CatalogBrand() { Brand = "SQL Server" }, new CatalogBrand() { Brand = "Other" } }; } static IEnumerable<CatalogType> GetPreconfiguredCatalogTypes() { return new List<CatalogType>() { new CatalogType() { Type = "Mug"}, new CatalogType() { Type = "T-Shirt" }, new CatalogType() { Type = "Sheet" }, new CatalogType() { Type = "USB Memory Stick" } }; } static IEnumerable<CatalogItem> GetPreconfiguredItems() { return new List<CatalogItem>() { new CatalogItem() { CatalogTypeId=2,CatalogBrandId=2, Description = ".NET Bot Black Sweatshirt", Name = ".NET Bot Black Sweatshirt", Price = 19.5M, PictureUri = "http://catalogbaseurltobereplaced/images/products/1.png" }, new CatalogItem() { CatalogTypeId=1,CatalogBrandId=2, Description = ".NET Black & White Mug", Name = ".NET Black & White Mug", Price= 8.50M, PictureUri = "http://catalogbaseurltobereplaced/images/products/2.png" }, new CatalogItem() { CatalogTypeId=2,CatalogBrandId=5, Description = "Prism White T-Shirt", Name = "Prism White T-Shirt", Price = 12, PictureUri = "http://catalogbaseurltobereplaced/images/products/3.png" }, new CatalogItem() { CatalogTypeId=2,CatalogBrandId=2, Description = ".NET Foundation Sweatshirt", Name = ".NET Foundation Sweatshirt", Price = 12, PictureUri = "http://catalogbaseurltobereplaced/images/products/4.png" }, new CatalogItem() { CatalogTypeId=3,CatalogBrandId=5, Description = "Roslyn Red Sheet", Name = "Roslyn Red Sheet", Price = 8.5M, PictureUri = "http://catalogbaseurltobereplaced/images/products/5.png" }, new CatalogItem() { CatalogTypeId=2,CatalogBrandId=2, Description = ".NET Blue Sweatshirt", Name = ".NET Blue Sweatshirt", Price = 12, PictureUri = "http://catalogbaseurltobereplaced/images/products/6.png" }, new CatalogItem() { CatalogTypeId=2,CatalogBrandId=5, Description = "Roslyn Red T-Shirt", Name = "Roslyn Red T-Shirt", Price = 12, PictureUri = "http://catalogbaseurltobereplaced/images/products/7.png" }, new CatalogItem() { CatalogTypeId=2,CatalogBrandId=5, Description = "Kudu Purple Sweatshirt", Name = "Kudu Purple Sweatshirt", Price = 8.5M, PictureUri = "http://catalogbaseurltobereplaced/images/products/8.png" }, new CatalogItem() { CatalogTypeId=1,CatalogBrandId=5, Description = "Cup<T> White Mug", Name = "Cup<T> White Mug", Price = 12, PictureUri = "http://catalogbaseurltobereplaced/images/products/9.png" }, new CatalogItem() { CatalogTypeId=3,CatalogBrandId=2, Description = ".NET Foundation Sheet", Name = ".NET Foundation Sheet", Price = 12, PictureUri = "http://catalogbaseurltobereplaced/images/products/10.png" }, new CatalogItem() { CatalogTypeId=3,CatalogBrandId=2, Description = "Cup<T> Sheet", Name = "Cup<T> Sheet", Price = 8.5M, PictureUri = "http://catalogbaseurltobereplaced/images/products/11.png" }, new CatalogItem() { CatalogTypeId=2,CatalogBrandId=5, Description = "Prism White TShirt", Name = "Prism White TShirt", Price = 12, PictureUri = "http://catalogbaseurltobereplaced/images/products/12.png" } }; } } }
55.60396
237
0.600249
[ "MIT" ]
andyhopp/eShopOnWeb
src/Infrastructure/Data/CatalogContextSeed.cs
5,616
C#
using System; using System.Collections.Generic; using System.Linq; using System.IO; using System.Reflection; using System.Xml; using System.Drawing; using System.Security.Principal; using System.Threading; using System.Threading.Tasks; using System.Globalization; using System.Diagnostics; using Sensorit.Base; using System.Windows.Input; namespace DS4Windows { [Flags] public enum DS4KeyType : byte { None = 0, ScanCode = 1, Toggle = 2, Unbound = 4, Macro = 8, HoldMacro = 16, RepeatMacro = 32 }; // Increment by exponents of 2*, starting at 2^0 public enum Ds3PadId : byte { None = 0xFF, One = 0x00, Two = 0x01, Three = 0x02, Four = 0x03, All = 0x04 }; public enum DS4Controls : byte { None, LXNeg, LXPos, LYNeg, LYPos, RXNeg, RXPos, RYNeg, RYPos, L1, L2, L3, R1, R2, R3, Square, Triangle, Circle, Cross, DpadUp, DpadRight, DpadDown, DpadLeft, PS, TouchLeft, TouchUpper, TouchMulti, TouchRight, Share, Options, GyroXPos, GyroXNeg, GyroZPos, GyroZNeg, SwipeLeft, SwipeRight, SwipeUp, SwipeDown }; public enum X360Controls : byte { None, LXNeg, LXPos, LYNeg, LYPos, RXNeg, RXPos, RYNeg, RYPos, LB, LT, LS, RB, RT, RS, X, Y, B, A, DpadUp, DpadRight, DpadDown, DpadLeft, Guide, Back, Start, TouchpadClick, LeftMouse, RightMouse, MiddleMouse, FourthMouse, FifthMouse, WUP, WDOWN, MouseUp, MouseDown, MouseLeft, MouseRight, Unbound }; public enum SASteeringWheelEmulationAxisType: byte { None = 0, LX, LY, RX, RY, L2R2, VJoy1X, VJoy1Y, VJoy1Z, VJoy2X, VJoy2Y, VJoy2Z }; public enum OutContType : uint { None = 0, X360, DS4 } public enum GyroOutMode : uint { None, Controls, Mouse, MouseJoystick, } public enum TouchpadOutMode : uint { None, Mouse, Controls, AbsoluteMouse, } public enum TrayIconChoice : uint { Default, Colored, White, Black, } public enum AppThemeChoice : uint { Default, Dark, } public class DS4ControlSettings { public DS4Controls control; public string extras = null; public DS4KeyType keyType = DS4KeyType.None; public enum ActionType : byte { Default, Key, Button, Macro }; public ActionType actionType = ActionType.Default; public object action = null; public ActionType shiftActionType = ActionType.Default; public object shiftAction = null; public int shiftTrigger = 0; public string shiftExtras = null; public DS4KeyType shiftKeyType = DS4KeyType.None; public DS4ControlSettings(DS4Controls ctrl) { control = ctrl; } public void Reset() { extras = null; keyType = DS4KeyType.None; actionType = ActionType.Default; action = null; shiftActionType = ActionType.Default; shiftAction = null; shiftTrigger = 0; shiftExtras = null; shiftKeyType = DS4KeyType.None; } internal void UpdateSettings(bool shift, object act, string exts, DS4KeyType kt, int trigger = 0) { if (!shift) { if (act is int || act is ushort) actionType = ActionType.Key; else if (act is string || act is X360Controls) actionType = ActionType.Button; else if (act is int[]) actionType = ActionType.Macro; else actionType = ActionType.Default; action = act; extras = exts; keyType = kt; } else { if (act is int || act is ushort) shiftActionType = ActionType.Key; else if (act is string || act is X360Controls) shiftActionType = ActionType.Button; else if (act is int[]) shiftActionType = ActionType.Macro; else shiftActionType = ActionType.Default; shiftAction = act; shiftExtras = exts; shiftKeyType = kt; shiftTrigger = trigger; } } } public class ControlSettingsGroup { public List<DS4ControlSettings> LS = new List<DS4ControlSettings>(); public List<DS4ControlSettings> RS = new List<DS4ControlSettings>(); public DS4ControlSettings L2; public DS4ControlSettings R2; public List<DS4ControlSettings> ControlButtons = new List<DS4ControlSettings>(); public ControlSettingsGroup(List<DS4ControlSettings> settingsList) { for (int i = (int)DS4Controls.LXNeg; i <= (int)DS4Controls.LYPos; i++) { LS.Add(settingsList[i-1]); } for (int i = (int)DS4Controls.RXNeg; i <= (int)DS4Controls.RYPos; i++) { RS.Add(settingsList[i-1]); } L2 = settingsList[(int)DS4Controls.L2-1]; R2 = settingsList[(int)DS4Controls.R2-1]; ControlButtons.Add(settingsList[(int)DS4Controls.L1-1]); ControlButtons.Add(settingsList[(int)DS4Controls.L3-1]); ControlButtons.Add(settingsList[(int)DS4Controls.R1-1]); ControlButtons.Add(settingsList[(int)DS4Controls.R3-1]); for (int i = (int)DS4Controls.Square; i <= (int)DS4Controls.SwipeDown; i++) { ControlButtons.Add(settingsList[i-1]); } } } public class DebugEventArgs : EventArgs { protected DateTime m_Time = DateTime.Now; protected string m_Data = string.Empty; protected bool warning = false; protected bool temporary = false; public DebugEventArgs(string Data, bool warn, bool temporary = false) { m_Data = Data; warning = warn; this.temporary = temporary; } public DateTime Time => m_Time; public string Data => m_Data; public bool Warning => warning; public bool Temporary => temporary; } public class MappingDoneEventArgs : EventArgs { protected int deviceNum = -1; public MappingDoneEventArgs(int DeviceID) { deviceNum = DeviceID; } public int DeviceID => deviceNum; } public class ReportEventArgs : EventArgs { protected Ds3PadId m_Pad = Ds3PadId.None; protected byte[] m_Report = new byte[64]; public ReportEventArgs() { } public ReportEventArgs(Ds3PadId Pad) { m_Pad = Pad; } public Ds3PadId Pad { get { return m_Pad; } set { m_Pad = value; } } public Byte[] Report { get { return m_Report; } } } public class BatteryReportArgs : EventArgs { private int index; private int level; private bool charging; public BatteryReportArgs(int index, int level, bool charging) { this.index = index; this.level = level; this.charging = charging; } public int getIndex() { return index; } public int getLevel() { return level; } public bool isCharging() { return charging; } } public class ControllerRemovedArgs : EventArgs { private int index; public ControllerRemovedArgs(int index) { this.index = index; } public int getIndex() { return this.index; } } public class DeviceStatusChangeEventArgs : EventArgs { private int index; public DeviceStatusChangeEventArgs(int index) { this.index = index; } public int getIndex() { return index; } } public class SerialChangeArgs : EventArgs { private int index; private string serial; public SerialChangeArgs(int index, string serial) { this.index = index; this.serial = serial; } public int getIndex() { return index; } public string getSerial() { return serial; } } public class OneEuroFilterPair { public const double DEFAULT_WHEEL_CUTOFF = 0.1; public const double DEFAULT_WHEEL_BETA = 0.1; public OneEuroFilter axis1Filter = new OneEuroFilter(minCutoff: DEFAULT_WHEEL_CUTOFF, beta: DEFAULT_WHEEL_BETA); public OneEuroFilter axis2Filter = new OneEuroFilter(minCutoff: DEFAULT_WHEEL_CUTOFF, beta: DEFAULT_WHEEL_BETA); } public class OneEuroFilter3D { public const double DEFAULT_WHEEL_CUTOFF = 0.4; public const double DEFAULT_WHEEL_BETA = 0.2; public OneEuroFilter axis1Filter = new OneEuroFilter(minCutoff: DEFAULT_WHEEL_CUTOFF, beta: DEFAULT_WHEEL_BETA); public OneEuroFilter axis2Filter = new OneEuroFilter(minCutoff: DEFAULT_WHEEL_CUTOFF, beta: DEFAULT_WHEEL_BETA); public OneEuroFilter axis3Filter = new OneEuroFilter(minCutoff: DEFAULT_WHEEL_CUTOFF, beta: DEFAULT_WHEEL_BETA); public void SetFilterAttrs(double minCutoff, double beta) { axis1Filter.MinCutoff = axis2Filter.MinCutoff = axis3Filter.MinCutoff = minCutoff; axis1Filter.Beta = axis2Filter.Beta = axis3Filter.Beta = beta; } } public class Global { public const int MAX_DS4_CONTROLLER_COUNT = 8; public const int TEST_PROFILE_ITEM_COUNT = MAX_DS4_CONTROLLER_COUNT + 1; public const int TEST_PROFILE_INDEX = TEST_PROFILE_ITEM_COUNT - 1; public const int OLD_XINPUT_CONTROLLER_COUNT = 4; protected static BackingStore m_Config = new BackingStore(); protected static Int32 m_IdleTimeout = 600000; public static string exelocation = Assembly.GetExecutingAssembly().Location; public static string exedirpath = Directory.GetParent(exelocation).FullName; public static string exeFileName = Path.GetFileName(exelocation); public static FileVersionInfo fileVersion = FileVersionInfo.GetVersionInfo(exelocation); public static string exeversion = fileVersion.ProductVersion; public static ulong exeversionLong = (ulong)fileVersion.ProductMajorPart << 48 | (ulong)fileVersion.ProductMinorPart << 32 | (ulong)fileVersion.ProductBuildPart << 16; public static ulong fullExeVersionLong = exeversionLong | (ushort)fileVersion.ProductPrivatePart; public static bool IsWin8OrGreater() { bool result = false; if (Environment.OSVersion.Version.Major > 6) { result = true; } else if (Environment.OSVersion.Version.Major == 6 && Environment.OSVersion.Version.Minor >= 2) { result = true; } return result; } public static string appdatapath; public static bool firstRun = false; public static bool multisavespots = false; public static string appDataPpath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\DS4Windows"; public static bool runHotPlug = false; public static string[] tempprofilename = new string[TEST_PROFILE_ITEM_COUNT] { string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty }; public static bool[] useTempProfile = new bool[TEST_PROFILE_ITEM_COUNT] { false, false, false, false, false, false, false, false, false }; public static bool[] tempprofileDistance = new bool[TEST_PROFILE_ITEM_COUNT] { false, false, false, false, false, false, false, false, false }; public static bool[] useDInputOnly = new bool[TEST_PROFILE_ITEM_COUNT] { true, true, true, true, true, true, true, true, true }; public static bool[] linkedProfileCheck = new bool[MAX_DS4_CONTROLLER_COUNT] { false, false, false, false, false, false, false, false }; public static bool[] touchpadActive = new bool[TEST_PROFILE_ITEM_COUNT] { true, true, true, true, true, true, true, true, true }; // Used to hold device type desired from Profile Editor public static OutContType[] outDevTypeTemp = new OutContType[TEST_PROFILE_ITEM_COUNT] { DS4Windows.OutContType.X360, DS4Windows.OutContType.X360, DS4Windows.OutContType.X360, DS4Windows.OutContType.X360, DS4Windows.OutContType.X360, DS4Windows.OutContType.X360, DS4Windows.OutContType.X360, DS4Windows.OutContType.X360, DS4Windows.OutContType.X360}; // Used to hold the currently active controller output type in use for a slot public static OutContType[] activeOutDevType = new OutContType[TEST_PROFILE_ITEM_COUNT] { DS4Windows.OutContType.None, DS4Windows.OutContType.None, DS4Windows.OutContType.None, DS4Windows.OutContType.None, DS4Windows.OutContType.None, DS4Windows.OutContType.None, DS4Windows.OutContType.None, DS4Windows.OutContType.None, DS4Windows.OutContType.None}; public static bool vigemInstalled = IsViGEmBusInstalled(); public static bool hidguardInstalled = IsHidGuardianInstalled(); public static string vigembusVersion = ViGEmBusVersion(); public const int CONFIG_VERSION = 5; public const int APP_CONFIG_VERSION = 2; public const string ASSEMBLY_RESOURCE_PREFIX = "pack://application:,,,/DS4Windows;"; public const string CUSTOM_EXE_CONFIG_FILENAME = "custom_exe_name.txt"; public const string XML_EXTENSION = ".xml"; public static X360Controls[] defaultButtonMapping = { X360Controls.None, X360Controls.LXNeg, X360Controls.LXPos, X360Controls.LYNeg, X360Controls.LYPos, X360Controls.RXNeg, X360Controls.RXPos, X360Controls.RYNeg, X360Controls.RYPos, X360Controls.LB, X360Controls.LT, X360Controls.LS, X360Controls.RB, X360Controls.RT, X360Controls.RS, X360Controls.X, X360Controls.Y, X360Controls.B, X360Controls.A, X360Controls.DpadUp, X360Controls.DpadRight, X360Controls.DpadDown, X360Controls.DpadLeft, X360Controls.Guide, X360Controls.LeftMouse, X360Controls.MiddleMouse, X360Controls.RightMouse, X360Controls.LeftMouse, X360Controls.Back, X360Controls.Start, X360Controls.None, X360Controls.None, X360Controls.None, X360Controls.None, X360Controls.None, X360Controls.None, X360Controls.None, X360Controls.None }; // Create mapping array at runtime public static DS4Controls[] reverseX360ButtonMapping = new Func<DS4Controls[]>(() => { DS4Controls[] temp = new DS4Controls[defaultButtonMapping.Length]; for (int i = 0, arlen = defaultButtonMapping.Length; i < arlen; i++) { X360Controls mapping = defaultButtonMapping[i]; if (mapping != X360Controls.None) { temp[(int)mapping] = (DS4Controls)i; } } return temp; })(); public static Dictionary<X360Controls, string> xboxDefaultNames = new Dictionary<X360Controls, string>() { [X360Controls.LXNeg] = "Left X-Axis-", [X360Controls.LXPos] = "Left X-Axis+", [X360Controls.LYNeg] = "Left Y-Axis-", [X360Controls.LYPos] = "Left Y-Axis+", [X360Controls.RXNeg] = "Right X-Axis-", [X360Controls.RXPos] = "Right X-Axis+", [X360Controls.RYNeg] = "Right Y-Axis-", [X360Controls.RYPos] = "Right Y-Axis+", [X360Controls.LB] = "Left Bumper", [X360Controls.LT] = "Left Trigger", [X360Controls.LS] = "Left Stick", [X360Controls.RB] = "Right Bumper", [X360Controls.RT] = "Right Trigger", [X360Controls.RS] = "Right Stick", [X360Controls.X] = "X Button", [X360Controls.Y] = "Y Button", [X360Controls.B] = "B Button", [X360Controls.A] = "A Button", [X360Controls.DpadUp] = "Up Button", [X360Controls.DpadRight] = "Right Button", [X360Controls.DpadDown] = "Down Button", [X360Controls.DpadLeft] = "Left Button", [X360Controls.Guide] = "Guide", [X360Controls.Back] = "Back", [X360Controls.Start] = "Start", [X360Controls.TouchpadClick] = "Touchpad Click", [X360Controls.LeftMouse] = "Left Mouse Button", [X360Controls.RightMouse] = "Right Mouse Button", [X360Controls.MiddleMouse] = "Middle Mouse Button", [X360Controls.FourthMouse] = "4th Mouse Button", [X360Controls.FifthMouse] = "5th Mouse Button", [X360Controls.WUP] = "Mouse Wheel Up", [X360Controls.WDOWN] = "Mouse Wheel Down", [X360Controls.MouseUp] = "Mouse Up", [X360Controls.MouseDown] = "Mouse Down", [X360Controls.MouseLeft] = "Mouse Left", [X360Controls.MouseRight] = "Mouse Right", [X360Controls.Unbound] = "Unbound", }; public static Dictionary<X360Controls, string> ds4DefaultNames = new Dictionary<X360Controls, string>() { [X360Controls.LXNeg] = "Left X-Axis-", [X360Controls.LXPos] = "Left X-Axis+", [X360Controls.LYNeg] = "Left Y-Axis-", [X360Controls.LYPos] = "Left Y-Axis+", [X360Controls.RXNeg] = "Right X-Axis-", [X360Controls.RXPos] = "Right X-Axis+", [X360Controls.RYNeg] = "Right Y-Axis-", [X360Controls.RYPos] = "Right Y-Axis+", [X360Controls.LB] = "L1", [X360Controls.LT] = "L2", [X360Controls.LS] = "L3", [X360Controls.RB] = "R1", [X360Controls.RT] = "R2", [X360Controls.RS] = "R3", [X360Controls.X] = "Square", [X360Controls.Y] = "Triangle", [X360Controls.B] = "Circle", [X360Controls.A] = "Cross", [X360Controls.DpadUp] = "Dpad Up", [X360Controls.DpadRight] = "Dpad Right", [X360Controls.DpadDown] = "Dpad Down", [X360Controls.DpadLeft] = "Dpad Left", [X360Controls.Guide] = "PS", [X360Controls.Back] = "Share", [X360Controls.Start] = "Options", [X360Controls.TouchpadClick] = "Touchpad Click", [X360Controls.LeftMouse] = "Left Mouse Button", [X360Controls.RightMouse] = "Right Mouse Button", [X360Controls.MiddleMouse] = "Middle Mouse Button", [X360Controls.FourthMouse] = "4th Mouse Button", [X360Controls.FifthMouse] = "5th Mouse Button", [X360Controls.WUP] = "Mouse Wheel Up", [X360Controls.WDOWN] = "Mouse Wheel Down", [X360Controls.MouseUp] = "Mouse Up", [X360Controls.MouseDown] = "Mouse Down", [X360Controls.MouseLeft] = "Mouse Left", [X360Controls.MouseRight] = "Mouse Right", [X360Controls.Unbound] = "Unbound", }; public static string getX360ControlString(X360Controls key, OutContType conType) { string result = string.Empty; if (conType == DS4Windows.OutContType.X360) { xboxDefaultNames.TryGetValue(key, out result); } else if (conType == DS4Windows.OutContType.DS4) { ds4DefaultNames.TryGetValue(key, out result); } return result; } public static Dictionary<DS4Controls, string> ds4inputNames = new Dictionary<DS4Controls, string>() { [DS4Controls.LXNeg] = "Left X-Axis-", [DS4Controls.LXPos] = "Left X-Axis+", [DS4Controls.LYNeg] = "Left Y-Axis-", [DS4Controls.LYPos] = "Left Y-Axis+", [DS4Controls.RXNeg] = "Right X-Axis-", [DS4Controls.RXPos] = "Right X-Axis+", [DS4Controls.RYNeg] = "Right Y-Axis-", [DS4Controls.RYPos] = "Right Y-Axis+", [DS4Controls.L1] = "L1", [DS4Controls.L2] = "L2", [DS4Controls.L3] = "L3", [DS4Controls.R1] = "R1", [DS4Controls.R2] = "R2", [DS4Controls.R3] = "R3", [DS4Controls.Square] = "Square", [DS4Controls.Triangle] = "Triangle", [DS4Controls.Circle] = "Circle", [DS4Controls.Cross] = "Cross", [DS4Controls.DpadUp] = "Dpad Up", [DS4Controls.DpadRight] = "Dpad Right", [DS4Controls.DpadDown] = "Dpad Down", [DS4Controls.DpadLeft] = "Dpad Left", [DS4Controls.PS] = "PS", [DS4Controls.Share] = "Share", [DS4Controls.Options] = "Options", [DS4Controls.TouchLeft] = "Left Touch", [DS4Controls.TouchUpper] = "Upper Touch", [DS4Controls.TouchMulti] = "Multitouch", [DS4Controls.TouchRight] = "Right Touch", [DS4Controls.GyroXPos] = "Gyro X+", [DS4Controls.GyroXNeg] = "Gyro X-", [DS4Controls.GyroZPos] = "Gyro Z+", [DS4Controls.GyroZNeg] = "Gyro Z-", [DS4Controls.SwipeLeft] = "Swipe Left", [DS4Controls.SwipeRight] = "Swipe Right", [DS4Controls.SwipeUp] = "Swipe Up", [DS4Controls.SwipeDown] = "Swipe Down", }; public static Dictionary<DS4Controls, int> macroDS4Values = new Dictionary<DS4Controls, int>() { [DS4Controls.Cross] = 261, [DS4Controls.Circle] = 262, [DS4Controls.Square] = 263, [DS4Controls.Triangle] = 264, [DS4Controls.Options] = 265, [DS4Controls.Share] = 266, [DS4Controls.DpadUp] = 267, [DS4Controls.DpadDown] = 268, [DS4Controls.DpadLeft] = 269, [DS4Controls.DpadRight] = 270, [DS4Controls.PS] = 271, [DS4Controls.L1] = 272, [DS4Controls.R1] = 273, [DS4Controls.L2] = 274, [DS4Controls.R2] = 275, [DS4Controls.L3] = 276, [DS4Controls.R3] = 277, [DS4Controls.LXPos] = 278, [DS4Controls.LXNeg] = 279, [DS4Controls.LYPos] = 280, [DS4Controls.LYNeg] = 281, [DS4Controls.RXPos] = 282, [DS4Controls.RXNeg] = 283, [DS4Controls.RYPos] = 284, [DS4Controls.RYNeg] = 285, }; public static Dictionary<TrayIconChoice, string> iconChoiceResources = new Dictionary<TrayIconChoice, string> { [TrayIconChoice.Default] = "/DS4Windows;component/Resources/DS4W.ico", [TrayIconChoice.Colored] = "/DS4Windows;component/Resources/DS4W.ico", [TrayIconChoice.White] = "/DS4Windows;component/Resources/DS4W - White.ico", [TrayIconChoice.Black] = "/DS4Windows;component/Resources/DS4W - Black.ico", }; public static void SaveWhere(string path) { appdatapath = path; m_Config.m_Profile = appdatapath + "\\Profiles.xml"; m_Config.m_Actions = appdatapath + "\\Actions.xml"; m_Config.m_linkedProfiles = Global.appdatapath + "\\LinkedProfiles.xml"; m_Config.m_controllerConfigs = Global.appdatapath + "\\ControllerConfigs.xml"; } public static bool SaveDefault(string path) { Boolean Saved = true; XmlDocument m_Xdoc = new XmlDocument(); try { XmlNode Node; m_Xdoc.RemoveAll(); Node = m_Xdoc.CreateXmlDeclaration("1.0", "utf-8", String.Empty); m_Xdoc.AppendChild(Node); Node = m_Xdoc.CreateComment(string.Format(" Profile Configuration Data. {0} ", DateTime.Now)); m_Xdoc.AppendChild(Node); Node = m_Xdoc.CreateWhitespace("\r\n"); m_Xdoc.AppendChild(Node); Node = m_Xdoc.CreateNode(XmlNodeType.Element, "Profile", null); m_Xdoc.AppendChild(Node); m_Xdoc.Save(path); } catch { Saved = false; } return Saved; } /// <summary> /// Check if Admin Rights are needed to write in Appliplation Directory /// </summary> /// <returns></returns> public static bool AdminNeeded() { try { File.WriteAllText(exedirpath + "\\test.txt", "test"); File.Delete(exedirpath + "\\test.txt"); return false; } catch (UnauthorizedAccessException) { return true; } } public static bool IsAdministrator() { var identity = WindowsIdentity.GetCurrent(); var principal = new WindowsPrincipal(identity); return principal.IsInRole(WindowsBuiltInRole.Administrator); } public static bool CheckForDevice(string guid) { bool result = false; Guid deviceGuid = Guid.Parse(guid); NativeMethods.SP_DEVINFO_DATA deviceInfoData = new NativeMethods.SP_DEVINFO_DATA(); deviceInfoData.cbSize = System.Runtime.InteropServices.Marshal.SizeOf(deviceInfoData); IntPtr deviceInfoSet = NativeMethods.SetupDiGetClassDevs(ref deviceGuid, null, 0, NativeMethods.DIGCF_DEVICEINTERFACE); result = NativeMethods.SetupDiEnumDeviceInfo(deviceInfoSet, 0, ref deviceInfoData); if (deviceInfoSet.ToInt64() != NativeMethods.INVALID_HANDLE_VALUE) { NativeMethods.SetupDiDestroyDeviceInfoList(deviceInfoSet); } return result; } private static bool CheckForSysDevice(string searchHardwareId) { bool result = false; Guid sysGuid = Guid.Parse("{4d36e97d-e325-11ce-bfc1-08002be10318}"); NativeMethods.SP_DEVINFO_DATA deviceInfoData = new NativeMethods.SP_DEVINFO_DATA(); deviceInfoData.cbSize = System.Runtime.InteropServices.Marshal.SizeOf(deviceInfoData); var dataBuffer = new byte[4096]; ulong propertyType = 0; var requiredSize = 0; IntPtr deviceInfoSet = NativeMethods.SetupDiGetClassDevs(ref sysGuid, null, 0, 0); for (int i = 0; !result && NativeMethods.SetupDiEnumDeviceInfo(deviceInfoSet, i, ref deviceInfoData); i++) { if (NativeMethods.SetupDiGetDeviceProperty(deviceInfoSet, ref deviceInfoData, ref NativeMethods.DEVPKEY_Device_HardwareIds, ref propertyType, dataBuffer, dataBuffer.Length, ref requiredSize, 0)) { string hardwareId = dataBuffer.ToUTF16String(); //if (hardwareIds.Contains("Virtual Gamepad Emulation Bus")) // result = true; if (hardwareId.Equals(searchHardwareId)) result = true; } } if (deviceInfoSet.ToInt64() != NativeMethods.INVALID_HANDLE_VALUE) { NativeMethods.SetupDiDestroyDeviceInfoList(deviceInfoSet); } return result; } internal static string GetDeviceProperty(string deviceInstanceId, NativeMethods.DEVPROPKEY prop) { string result = string.Empty; NativeMethods.SP_DEVINFO_DATA deviceInfoData = new NativeMethods.SP_DEVINFO_DATA(); deviceInfoData.cbSize = System.Runtime.InteropServices.Marshal.SizeOf(deviceInfoData); var dataBuffer = new byte[4096]; ulong propertyType = 0; var requiredSize = 0; Guid hidGuid = new Guid(); NativeMethods.HidD_GetHidGuid(ref hidGuid); IntPtr deviceInfoSet = NativeMethods.SetupDiGetClassDevs(ref hidGuid, deviceInstanceId, 0, NativeMethods.DIGCF_PRESENT | NativeMethods.DIGCF_DEVICEINTERFACE); NativeMethods.SetupDiEnumDeviceInfo(deviceInfoSet, 0, ref deviceInfoData); if (NativeMethods.SetupDiGetDeviceProperty(deviceInfoSet, ref deviceInfoData, ref prop, ref propertyType, dataBuffer, dataBuffer.Length, ref requiredSize, 0)) { result = dataBuffer.ToUTF16String(); } if (deviceInfoSet.ToInt64() != NativeMethods.INVALID_HANDLE_VALUE) { NativeMethods.SetupDiDestroyDeviceInfoList(deviceInfoSet); } return result; } private static string GetViGEmDriverProperty(NativeMethods.DEVPROPKEY prop) { string result = string.Empty; Guid deviceGuid = Guid.Parse(VIGEMBUS_GUID); NativeMethods.SP_DEVINFO_DATA deviceInfoData = new NativeMethods.SP_DEVINFO_DATA(); deviceInfoData.cbSize = System.Runtime.InteropServices.Marshal.SizeOf(deviceInfoData); var dataBuffer = new byte[4096]; ulong propertyType = 0; var requiredSize = 0; IntPtr deviceInfoSet = NativeMethods.SetupDiGetClassDevs(ref deviceGuid, null, 0, NativeMethods.DIGCF_DEVICEINTERFACE); NativeMethods.SetupDiEnumDeviceInfo(deviceInfoSet, 0, ref deviceInfoData); if (NativeMethods.SetupDiGetDeviceProperty(deviceInfoSet, ref deviceInfoData, ref prop, ref propertyType, dataBuffer, dataBuffer.Length, ref requiredSize, 0)) { result = dataBuffer.ToUTF16String(); } if (deviceInfoSet.ToInt64() != NativeMethods.INVALID_HANDLE_VALUE) { NativeMethods.SetupDiDestroyDeviceInfoList(deviceInfoSet); } return result; } public static bool CheckAffectedStatus(string deviceInstanceId, HashSet<string> affectedDevs, HashSet<string> exemptedDevices, bool force=false) { bool result = false; List<string> hardwareIdList = GrabDeviceHardwareIds(deviceInstanceId); bool foundExempt = false; foreach(string hardwareId in hardwareIdList) { foundExempt = foundExempt || exemptedDevices.Contains(hardwareId); } if (!foundExempt) { if (force) { result = true; } else { foreach (string hardwareId in hardwareIdList) { result = result || affectedDevs.Contains(hardwareId); } } } else { result = false; } return result; } private static List<string> GrabDeviceHardwareIds(string deviceInstanceId) { bool success; List<string> hardwareIds = new List<string>(); Guid hidGuid = HidDevices.HidClassGuid; IntPtr deviceInfoSet = NativeMethods.SetupDiGetClassDevs(ref hidGuid, deviceInstanceId, 0, NativeMethods.DIGCF_PRESENT | NativeMethods.DIGCF_DEVICEINTERFACE); if (deviceInfoSet.ToInt64() != NativeMethods.INVALID_HANDLE_VALUE) { NativeMethods.SP_DEVINFO_DATA deviceInfoData = new NativeMethods.SP_DEVINFO_DATA(); deviceInfoData.cbSize = System.Runtime.InteropServices.Marshal.SizeOf(deviceInfoData); success = NativeMethods.SetupDiEnumDeviceInfo(deviceInfoSet, 0, ref deviceInfoData); var requiredSize = 0; ulong propertyType = 0; NativeMethods.SetupDiGetDeviceProperty(deviceInfoSet, ref deviceInfoData, ref NativeMethods.DEVPKEY_Device_HardwareIds, ref propertyType, null, 0, ref requiredSize, 0); if (requiredSize > 0) { var descriptionBuffer = new byte[requiredSize]; NativeMethods.SetupDiGetDeviceProperty(deviceInfoSet, ref deviceInfoData, ref NativeMethods.DEVPKEY_Device_HardwareIds, ref propertyType, descriptionBuffer, descriptionBuffer.Length, ref requiredSize, 0); string tmpitnow = System.Text.Encoding.Unicode.GetString(descriptionBuffer); string tempStrip = tmpitnow.Remove(tmpitnow.IndexOf("\0\0")); string[] tmparray = tempStrip.Split((char)0); hardwareIds.AddRange(tmparray); } NativeMethods.SetupDiDestroyDeviceInfoList(deviceInfoSet); } return hardwareIds; } public static bool IsHidGuardianInstalled() { return CheckForSysDevice(@"Root\HidGuardian"); } const string VIGEMBUS_GUID = "{96E42B22-F5E9-42F8-B043-ED0F932F014F}"; public static bool IsViGEmBusInstalled() { return CheckForDevice(VIGEMBUS_GUID); } public static string ViGEmBusVersion() { return GetViGEmDriverProperty(NativeMethods.DEVPKEY_Device_DriverVersion); } public static void FindConfigLocation() { if (File.Exists(exedirpath + "\\Auto Profiles.xml") && File.Exists(appDataPpath + "\\Auto Profiles.xml")) { Global.firstRun = true; Global.multisavespots = true; } else if (File.Exists(exedirpath + "\\Auto Profiles.xml")) SaveWhere(exedirpath); else if (File.Exists(appDataPpath + "\\Auto Profiles.xml")) SaveWhere(appDataPpath); else if (!File.Exists(exedirpath + "\\Auto Profiles.xml") && !File.Exists(appDataPpath + "\\Auto Profiles.xml")) { Global.firstRun = true; Global.multisavespots = false; } } public static void SetCulture(string culture) { try { Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(culture); CultureInfo.DefaultThreadCurrentUICulture = CultureInfo.GetCultureInfo(culture); } catch { /* Skip setting culture that we cannot set */ } } public static void CreateStdActions() { XmlDocument xDoc = new XmlDocument(); try { string[] profiles = Directory.GetFiles(appdatapath + @"\Profiles\"); string s = string.Empty; //foreach (string s in profiles) for (int i = 0, proflen = profiles.Length; i < proflen; i++) { s = profiles[i]; if (Path.GetExtension(s) == ".xml") { xDoc.Load(s); XmlNode el = xDoc.SelectSingleNode("DS4Windows/ProfileActions"); if (el != null) { if (string.IsNullOrEmpty(el.InnerText)) el.InnerText = "Disconnect Controller"; else el.InnerText += "/Disconnect Controller"; } else { XmlNode Node = xDoc.SelectSingleNode("DS4Windows"); el = xDoc.CreateElement("ProfileActions"); el.InnerText = "Disconnect Controller"; Node.AppendChild(el); } xDoc.Save(s); LoadActions(); } } } catch { } } public static bool CreateAutoProfiles(string m_Profile) { bool Saved = true; try { XmlNode Node; XmlDocument doc = new XmlDocument(); Node = doc.CreateXmlDeclaration("1.0", "utf-8", String.Empty); doc.AppendChild(Node); Node = doc.CreateComment(string.Format(" Auto-Profile Configuration Data. {0} ", DateTime.Now)); doc.AppendChild(Node); Node = doc.CreateWhitespace("\r\n"); doc.AppendChild(Node); Node = doc.CreateNode(XmlNodeType.Element, "Programs", ""); doc.AppendChild(Node); doc.Save(m_Profile); } catch { Saved = false; } return Saved; } public static event EventHandler<EventArgs> ControllerStatusChange; // called when a controller is added/removed/battery or touchpad mode changes/etc. public static void ControllerStatusChanged(object sender) { if (ControllerStatusChange != null) ControllerStatusChange(sender, EventArgs.Empty); } public static event EventHandler<BatteryReportArgs> BatteryStatusChange; public static void OnBatteryStatusChange(object sender, int index, int level, bool charging) { if (BatteryStatusChange != null) { BatteryReportArgs args = new BatteryReportArgs(index, level, charging); BatteryStatusChange(sender, args); } } public static event EventHandler<ControllerRemovedArgs> ControllerRemoved; public static void OnControllerRemoved(object sender, int index) { if (ControllerRemoved != null) { ControllerRemovedArgs args = new ControllerRemovedArgs(index); ControllerRemoved(sender, args); } } public static event EventHandler<DeviceStatusChangeEventArgs> DeviceStatusChange; public static void OnDeviceStatusChanged(object sender, int index) { if (DeviceStatusChange != null) { DeviceStatusChangeEventArgs args = new DeviceStatusChangeEventArgs(index); DeviceStatusChange(sender, args); } } public static event EventHandler<SerialChangeArgs> DeviceSerialChange; public static void OnDeviceSerialChange(object sender, int index, string serial) { if (DeviceSerialChange != null) { SerialChangeArgs args = new SerialChangeArgs(index, serial); DeviceSerialChange(sender, args); } } public static ulong CompileVersionNumberFromString(string versionStr) { ulong result = 0; try { Version tmpVersion = new Version(versionStr); result = CompileVersionNumber(tmpVersion.Major, tmpVersion.Minor, tmpVersion.Build, tmpVersion.Revision); } catch (Exception) { } return result; } public static ulong CompileVersionNumber(int majorPart, int minorPart, int buildPart, int privatePart) { ulong result = (ulong)majorPart << 48 | (ulong)minorPart << 32 | (ulong)buildPart << 16 | (ushort)privatePart; return result; } // general values // -- Re-Enable Exclusive Mode Starts Here -- public static bool UseExclusiveMode { set { m_Config.useExclusiveMode = value; } get { return m_Config.useExclusiveMode; } } // -- Re-Enable Ex Mode Ends here public static bool getUseExclusiveMode() { return m_Config.useExclusiveMode; } public static DateTime LastChecked { set { m_Config.lastChecked = value; } get { return m_Config.lastChecked; } } public static int CheckWhen { set { m_Config.CheckWhen = value; } get { return m_Config.CheckWhen; } } public static string LastVersionChecked { get { return m_Config.lastVersionChecked; } set { m_Config.lastVersionChecked = value; m_Config.lastVersionCheckedNum = CompileVersionNumberFromString(value); } } public static ulong LastVersionCheckedNum { get { return m_Config.lastVersionCheckedNum; } } public static int Notifications { set { m_Config.notifications = value; } get { return m_Config.notifications; } } public static bool DCBTatStop { set { m_Config.disconnectBTAtStop = value; } get { return m_Config.disconnectBTAtStop; } } public static bool SwipeProfiles { set { m_Config.swipeProfiles = value; } get { return m_Config.swipeProfiles; } } public static bool DS4Mapping { set { m_Config.ds4Mapping = value; } get { return m_Config.ds4Mapping; } } public static bool QuickCharge { set { m_Config.quickCharge = value; } get { return m_Config.quickCharge; } } public static bool getQuickCharge() { return m_Config.quickCharge; } public static bool CloseMini { set { m_Config.closeMini = value; } get { return m_Config.closeMini; } } public static bool StartMinimized { set { m_Config.startMinimized = value; } get { return m_Config.startMinimized; } } public static bool MinToTaskbar { set { m_Config.minToTaskbar = value; } get { return m_Config.minToTaskbar; } } public static bool GetMinToTaskbar() { return m_Config.minToTaskbar; } public static int FormWidth { set { m_Config.formWidth = value; } get { return m_Config.formWidth; } } public static int FormHeight { set { m_Config.formHeight = value; } get { return m_Config.formHeight; } } public static int FormLocationX { set { m_Config.formLocationX = value; } get { return m_Config.formLocationX; } } public static int FormLocationY { set { m_Config.formLocationY = value; } get { return m_Config.formLocationY; } } public static string UseLang { set { m_Config.useLang = value; } get { return m_Config.useLang; } } public static bool DownloadLang { set { m_Config.downloadLang = value; } get { return m_Config.downloadLang; } } public static bool FlashWhenLate { set { m_Config.flashWhenLate = value; } get { return m_Config.flashWhenLate; } } public static bool getFlashWhenLate() { return m_Config.flashWhenLate; } public static int FlashWhenLateAt { set { m_Config.flashWhenLateAt = value; } get { return m_Config.flashWhenLateAt; } } public static int getFlashWhenLateAt() { return m_Config.flashWhenLateAt; } public static bool isUsingUDPServer() { return m_Config.useUDPServ; } public static void setUsingUDPServer(bool state) { m_Config.useUDPServ = state; } public static int getUDPServerPortNum() { return m_Config.udpServPort; } public static void setUDPServerPort(int value) { m_Config.udpServPort = value; } public static string getUDPServerListenAddress() { return m_Config.udpServListenAddress; } public static void setUDPServerListenAddress(string value) { m_Config.udpServListenAddress = value.Trim(); } public static bool UseUDPSeverSmoothing { get => m_Config.useUdpSmoothing; set => m_Config.useUdpSmoothing = value; } public static bool IsUsingUDPServerSmoothing() { return m_Config.useUdpSmoothing; } public static double UDPServerSmoothingMincutoff { get => m_Config.udpSmoothingMincutoff; set { double temp = m_Config.udpSmoothingMincutoff; if (temp == value) return; m_Config.udpSmoothingMincutoff = value; UDPServerSmoothingMincutoffChanged?.Invoke(null, EventArgs.Empty); } } public static event EventHandler UDPServerSmoothingMincutoffChanged; public static double UDPServerSmoothingBeta { get => m_Config.udpSmoothingBeta; set { double temp = m_Config.udpSmoothingBeta; if (temp == value) return; m_Config.udpSmoothingBeta = value; UDPServerSmoothingBetaChanged?.Invoke(null, EventArgs.Empty); } } public static event EventHandler UDPServerSmoothingBetaChanged; public static TrayIconChoice UseIconChoice { get => m_Config.useIconChoice; set => m_Config.useIconChoice = value; } public static AppThemeChoice UseCurrentTheme { get => m_Config.useCurrentTheme; set => m_Config.useCurrentTheme = value; } public static bool UseCustomSteamFolder { set { m_Config.useCustomSteamFolder = value; } get { return m_Config.useCustomSteamFolder; } } public static string CustomSteamFolder { set { m_Config.customSteamFolder = value; } get { return m_Config.customSteamFolder; } } public static bool AutoProfileRevertDefaultProfile { set { m_Config.autoProfileRevertDefaultProfile = value; } get { return m_Config.autoProfileRevertDefaultProfile; } } /// <summary> /// Fake name used for user copy of DS4Windows.exe /// </summary> public static string FakeExeName { get { return m_Config.fakeExeFileName; } set { bool valid = !(value.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0); if (valid) { m_Config.fakeExeFileName = value; } } } // controller/profile specfic values public static ButtonMouseInfo[] ButtonMouseInfos => m_Config.buttonMouseInfos; public static byte[] RumbleBoost => m_Config.rumble; public static byte getRumbleBoost(int index) { return m_Config.rumble[index]; } public static void setRumbleAutostopTime(int index, int value) { m_Config.rumbleAutostopTime[index] = value; DS4Device tempDev = Program.rootHub.DS4Controllers[index]; if (tempDev != null && tempDev.isSynced()) tempDev.RumbleAutostopTime = value; } public static int getRumbleAutostopTime(int index) { return m_Config.rumbleAutostopTime[index]; } public static bool[] EnableTouchToggle => m_Config.enableTouchToggle; public static bool getEnableTouchToggle(int index) { return m_Config.enableTouchToggle[index]; } public static int[] IdleDisconnectTimeout => m_Config.idleDisconnectTimeout; public static int getIdleDisconnectTimeout(int index) { return m_Config.idleDisconnectTimeout[index]; } public static bool[] EnableOutputDataToDS4 => m_Config.enableOutputDataToDS4; public static bool getEnableOutputDataToDS4(int index) { return m_Config.enableOutputDataToDS4[index]; } public static byte[] TouchSensitivity => m_Config.touchSensitivity; public static byte[] getTouchSensitivity() { return m_Config.touchSensitivity; } public static byte getTouchSensitivity(int index) { return m_Config.touchSensitivity[index]; } public static bool[] TouchActive => touchpadActive; public static bool GetTouchActive(int index) { return touchpadActive[index]; } public static LightbarSettingInfo[] LightbarSettingsInfo => m_Config.lightbarSettingInfo; public static LightbarSettingInfo getLightbarSettingsInfo(int index) { return m_Config.lightbarSettingInfo[index]; } public static bool[] DinputOnly => m_Config.dinputOnly; public static bool getDInputOnly(int index) { return m_Config.dinputOnly[index]; } public static bool[] StartTouchpadOff => m_Config.startTouchpadOff; public static bool IsUsingTouchpadForControls(int index) { return m_Config.touchOutMode[index] == TouchpadOutMode.Controls; } public static TouchpadOutMode[] TouchOutMode = m_Config.touchOutMode; public static bool IsUsingSAForControls(int index) { return m_Config.gyroOutMode[index] == GyroOutMode.Controls; } public static string[] SATriggers => m_Config.sATriggers; public static string getSATriggers(int index) { return m_Config.sATriggers[index]; } public static bool[] SATriggerCond => m_Config.sATriggerCond; public static bool getSATriggerCond(int index) { return m_Config.sATriggerCond[index]; } public static void SetSaTriggerCond(int index, string text) { m_Config.SetSaTriggerCond(index, text); } public static GyroOutMode[] GyroOutputMode => m_Config.gyroOutMode; public static GyroOutMode GetGyroOutMode(int device) { return m_Config.gyroOutMode[device]; } public static string[] SAMousestickTriggers => m_Config.sAMouseStickTriggers; public static string GetSAMouseStickTriggers(int device) { return m_Config.sAMouseStickTriggers[device]; } public static bool[] SAMouseStickTriggerCond => m_Config.sAMouseStickTriggerCond; public static bool GetSAMouseStickTriggerCond(int device) { return m_Config.sAMouseStickTriggerCond[device]; } public static void SetSaMouseStickTriggerCond(int index, string text) { m_Config.SetSaMouseStickTriggerCond(index, text); } public static bool[] GyroMouseStickTriggerTurns = m_Config.gyroMouseStickTriggerTurns; public static bool GetGyroMouseStickTriggerTurns(int device) { return m_Config.gyroMouseStickTriggerTurns[device]; } public static int[] GyroMouseStickHorizontalAxis => m_Config.gyroMouseStickHorizontalAxis; public static int getGyroMouseStickHorizontalAxis(int index) { return m_Config.gyroMouseStickHorizontalAxis[index]; } public static GyroMouseStickInfo[] GyroMouseStickInf => m_Config.gyroMStickInfo; public static GyroMouseStickInfo GetGyroMouseStickInfo(int device) { return m_Config.gyroMStickInfo[device]; } public static bool[] GyroMouseStickToggle => m_Config.gyroMouseStickToggle; public static void SetGyroMouseStickToggle(int index, bool value, ControlService control) => m_Config.SetGyroMouseStickToggle(index, value, control); public static SASteeringWheelEmulationAxisType[] SASteeringWheelEmulationAxis => m_Config.sASteeringWheelEmulationAxis; public static SASteeringWheelEmulationAxisType GetSASteeringWheelEmulationAxis(int index) { return m_Config.sASteeringWheelEmulationAxis[index]; } public static int[] SASteeringWheelEmulationRange => m_Config.sASteeringWheelEmulationRange; public static int GetSASteeringWheelEmulationRange(int index) { return m_Config.sASteeringWheelEmulationRange[index]; } public static int[][] TouchDisInvertTriggers => m_Config.touchDisInvertTriggers; public static int[] getTouchDisInvertTriggers(int index) { return m_Config.touchDisInvertTriggers[index]; } public static int[] GyroSensitivity => m_Config.gyroSensitivity; public static int getGyroSensitivity(int index) { return m_Config.gyroSensitivity[index]; } public static int[] GyroSensVerticalScale => m_Config.gyroSensVerticalScale; public static int getGyroSensVerticalScale(int index) { return m_Config.gyroSensVerticalScale[index]; } public static int[] GyroInvert => m_Config.gyroInvert; public static int getGyroInvert(int index) { return m_Config.gyroInvert[index]; } public static bool[] GyroTriggerTurns => m_Config.gyroTriggerTurns; public static bool getGyroTriggerTurns(int index) { return m_Config.gyroTriggerTurns[index]; } public static int[] GyroMouseHorizontalAxis => m_Config.gyroMouseHorizontalAxis; public static int getGyroMouseHorizontalAxis(int index) { return m_Config.gyroMouseHorizontalAxis[index]; } public static int[] GyroMouseDeadZone => m_Config.gyroMouseDZ; public static int GetGyroMouseDeadZone(int index) { return m_Config.gyroMouseDZ[index]; } public static void SetGyroMouseDeadZone(int index, int value, ControlService control) { m_Config.SetGyroMouseDZ(index, value, control); } public static bool[] GyroMouseToggle => m_Config.gyroMouseToggle; public static void SetGyroMouseToggle(int index, bool value, ControlService control) => m_Config.SetGyroMouseToggle(index, value, control); public static GyroMouseInfo[] GyroMouseInfo => m_Config.gyroMouseInfo; public static SteeringWheelSmoothingInfo[] WheelSmoothInfo => m_Config.wheelSmoothInfo; public static int[] SAWheelFuzzValues => m_Config.saWheelFuzzValues; //public static DS4Color[] MainColor => m_Config.m_Leds; public static ref DS4Color getMainColor(int index) { return ref m_Config.lightbarSettingInfo[index].ds4winSettings.m_Led; //return ref m_Config.m_Leds[index]; } //public static DS4Color[] LowColor => m_Config.m_LowLeds; public static ref DS4Color getLowColor(int index) { return ref m_Config.lightbarSettingInfo[index].ds4winSettings.m_LowLed; //return ref m_Config.m_LowLeds[index]; } //public static DS4Color[] ChargingColor => m_Config.m_ChargingLeds; public static ref DS4Color getChargingColor(int index) { return ref m_Config.lightbarSettingInfo[index].ds4winSettings.m_ChargingLed; //return ref m_Config.m_ChargingLeds[index]; } //public static DS4Color[] CustomColor => m_Config.m_CustomLeds; public static ref DS4Color getCustomColor(int index) { return ref m_Config.lightbarSettingInfo[index].ds4winSettings.m_CustomLed; //return ref m_Config.m_CustomLeds[index]; } //public static bool[] UseCustomLed => m_Config.useCustomLeds; public static bool getUseCustomLed(int index) { return m_Config.lightbarSettingInfo[index].ds4winSettings.useCustomLed; //return m_Config.useCustomLeds[index]; } //public static DS4Color[] FlashColor => m_Config.m_FlashLeds; public static ref DS4Color getFlashColor(int index) { return ref m_Config.lightbarSettingInfo[index].ds4winSettings.m_FlashLed; //return ref m_Config.m_FlashLeds[index]; } public static byte[] TapSensitivity => m_Config.tapSensitivity; public static byte getTapSensitivity(int index) { return m_Config.tapSensitivity[index]; } public static bool[] DoubleTap => m_Config.doubleTap; public static bool getDoubleTap(int index) { return m_Config.doubleTap[index]; } public static int[] ScrollSensitivity => m_Config.scrollSensitivity; public static int[] getScrollSensitivity() { return m_Config.scrollSensitivity; } public static int getScrollSensitivity(int index) { return m_Config.scrollSensitivity[index]; } public static bool[] LowerRCOn => m_Config.lowerRCOn; public static bool[] TouchpadJitterCompensation => m_Config.touchpadJitterCompensation; public static bool getTouchpadJitterCompensation(int index) { return m_Config.touchpadJitterCompensation[index]; } public static int[] TouchpadInvert => m_Config.touchpadInvert; public static int getTouchpadInvert(int index) { return m_Config.touchpadInvert[index]; } public static TriggerDeadZoneZInfo[] L2ModInfo => m_Config.l2ModInfo; public static TriggerDeadZoneZInfo GetL2ModInfo(int index) { return m_Config.l2ModInfo[index]; } //public static byte[] L2Deadzone => m_Config.l2Deadzone; public static byte getL2Deadzone(int index) { return m_Config.l2ModInfo[index].deadZone; //return m_Config.l2Deadzone[index]; } public static TriggerDeadZoneZInfo[] R2ModInfo => m_Config.r2ModInfo; public static TriggerDeadZoneZInfo GetR2ModInfo(int index) { return m_Config.r2ModInfo[index]; } //public static byte[] R2Deadzone => m_Config.r2Deadzone; public static byte getR2Deadzone(int index) { return m_Config.r2ModInfo[index].deadZone; //return m_Config.r2Deadzone[index]; } public static double[] SXDeadzone => m_Config.SXDeadzone; public static double getSXDeadzone(int index) { return m_Config.SXDeadzone[index]; } public static double[] SZDeadzone => m_Config.SZDeadzone; public static double getSZDeadzone(int index) { return m_Config.SZDeadzone[index]; } //public static int[] LSDeadzone => m_Config.LSDeadzone; public static int getLSDeadzone(int index) { return m_Config.lsModInfo[index].deadZone; //return m_Config.LSDeadzone[index]; } //public static int[] RSDeadzone => m_Config.RSDeadzone; public static int getRSDeadzone(int index) { return m_Config.rsModInfo[index].deadZone; //return m_Config.RSDeadzone[index]; } //public static int[] LSAntiDeadzone => m_Config.LSAntiDeadzone; public static int getLSAntiDeadzone(int index) { return m_Config.lsModInfo[index].antiDeadZone; //return m_Config.LSAntiDeadzone[index]; } //public static int[] RSAntiDeadzone => m_Config.RSAntiDeadzone; public static int getRSAntiDeadzone(int index) { return m_Config.rsModInfo[index].antiDeadZone; //return m_Config.RSAntiDeadzone[index]; } public static StickDeadZoneInfo[] LSModInfo => m_Config.lsModInfo; public static StickDeadZoneInfo GetLSDeadInfo(int index) { return m_Config.lsModInfo[index]; } public static StickDeadZoneInfo[] RSModInfo => m_Config.rsModInfo; public static StickDeadZoneInfo GetRSDeadInfo(int index) { return m_Config.rsModInfo[index]; } public static double[] SXAntiDeadzone => m_Config.SXAntiDeadzone; public static double getSXAntiDeadzone(int index) { return m_Config.SXAntiDeadzone[index]; } public static double[] SZAntiDeadzone => m_Config.SZAntiDeadzone; public static double getSZAntiDeadzone(int index) { return m_Config.SZAntiDeadzone[index]; } //public static int[] LSMaxzone => m_Config.LSMaxzone; public static int getLSMaxzone(int index) { return m_Config.lsModInfo[index].maxZone; //return m_Config.LSMaxzone[index]; } //public static int[] RSMaxzone => m_Config.RSMaxzone; public static int getRSMaxzone(int index) { return m_Config.rsModInfo[index].maxZone; //return m_Config.RSMaxzone[index]; } public static double[] SXMaxzone => m_Config.SXMaxzone; public static double getSXMaxzone(int index) { return m_Config.SXMaxzone[index]; } public static double[] SZMaxzone => m_Config.SZMaxzone; public static double getSZMaxzone(int index) { return m_Config.SZMaxzone[index]; } //public static int[] L2AntiDeadzone => m_Config.l2AntiDeadzone; public static int getL2AntiDeadzone(int index) { return m_Config.l2ModInfo[index].antiDeadZone; //return m_Config.l2AntiDeadzone[index]; } //public static int[] R2AntiDeadzone => m_Config.r2AntiDeadzone; public static int getR2AntiDeadzone(int index) { return m_Config.r2ModInfo[index].antiDeadZone; //return m_Config.r2AntiDeadzone[index]; } //public static int[] L2Maxzone => m_Config.l2Maxzone; public static int getL2Maxzone(int index) { return m_Config.l2ModInfo[index].maxZone; //return m_Config.l2Maxzone[index]; } //public static int[] R2Maxzone => m_Config.r2Maxzone; public static int getR2Maxzone(int index) { return m_Config.r2ModInfo[index].maxZone; //return m_Config.r2Maxzone[index]; } public static int[] LSCurve => m_Config.lsCurve; public static int getLSCurve(int index) { return m_Config.lsCurve[index]; } public static int[] RSCurve => m_Config.rsCurve; public static int getRSCurve(int index) { return m_Config.rsCurve[index]; } public static double[] LSRotation => m_Config.LSRotation; public static double getLSRotation(int index) { return m_Config.LSRotation[index]; } public static double[] RSRotation => m_Config.RSRotation; public static double getRSRotation(int index) { return m_Config.RSRotation[index]; } public static double[] L2Sens => m_Config.l2Sens; public static double getL2Sens(int index) { return m_Config.l2Sens[index]; } public static double[] R2Sens => m_Config.r2Sens; public static double getR2Sens(int index) { return m_Config.r2Sens[index]; } public static double[] SXSens => m_Config.SXSens; public static double getSXSens(int index) { return m_Config.SXSens[index]; } public static double[] SZSens => m_Config.SZSens; public static double getSZSens(int index) { return m_Config.SZSens[index]; } public static double[] LSSens => m_Config.LSSens; public static double getLSSens(int index) { return m_Config.LSSens[index]; } public static double[] RSSens => m_Config.RSSens; public static double getRSSens(int index) { return m_Config.RSSens[index]; } public static int[] BTPollRate => m_Config.btPollRate; public static int getBTPollRate(int index) { return m_Config.btPollRate[index]; } public static SquareStickInfo[] SquStickInfo => m_Config.squStickInfo; public static SquareStickInfo GetSquareStickInfo(int device) { return m_Config.squStickInfo[device]; } public static StickOutputSetting[] LSOutputSettings => m_Config.lsOutputSettings; public static StickOutputSetting[] RSOutputSettings => m_Config.rsOutputSettings; public static void setLsOutCurveMode(int index, int value) { m_Config.setLsOutCurveMode(index, value); } public static int getLsOutCurveMode(int index) { return m_Config.getLsOutCurveMode(index); } public static BezierCurve[] lsOutBezierCurveObj => m_Config.lsOutBezierCurveObj; public static void setRsOutCurveMode(int index, int value) { m_Config.setRsOutCurveMode(index, value); } public static int getRsOutCurveMode(int index) { return m_Config.getRsOutCurveMode(index); } public static BezierCurve[] rsOutBezierCurveObj => m_Config.rsOutBezierCurveObj; public static void setL2OutCurveMode(int index, int value) { m_Config.setL2OutCurveMode(index, value); } public static int getL2OutCurveMode(int index) { return m_Config.getL2OutCurveMode(index); } public static BezierCurve[] l2OutBezierCurveObj => m_Config.l2OutBezierCurveObj; public static void setR2OutCurveMode(int index, int value) { m_Config.setR2OutCurveMode(index, value); } public static int getR2OutCurveMode(int index) { return m_Config.getR2OutCurveMode(index); } public static BezierCurve[] r2OutBezierCurveObj => m_Config.r2OutBezierCurveObj; public static void setSXOutCurveMode(int index, int value) { m_Config.setSXOutCurveMode(index, value); } public static int getSXOutCurveMode(int index) { return m_Config.getSXOutCurveMode(index); } public static BezierCurve[] sxOutBezierCurveObj => m_Config.sxOutBezierCurveObj; public static void setSZOutCurveMode(int index, int value) { m_Config.setSZOutCurveMode(index, value); } public static int getSZOutCurveMode(int index) { return m_Config.getSZOutCurveMode(index); } public static BezierCurve[] szOutBezierCurveObj => m_Config.szOutBezierCurveObj; public static bool[] TrackballMode => m_Config.trackballMode; public static bool getTrackballMode(int index) { return m_Config.trackballMode[index]; } public static double[] TrackballFriction => m_Config.trackballFriction; public static double getTrackballFriction(int index) { return m_Config.trackballFriction[index]; } public static TouchpadAbsMouseSettings[] TouchAbsMouse => m_Config.touchpadAbsMouse; public static TouchpadRelMouseSettings[] TouchRelMouse => m_Config.touchpadRelMouse; public static OutContType[] OutContType => m_Config.outputDevType; public static string[] LaunchProgram => m_Config.launchProgram; public static string[] ProfilePath => m_Config.profilePath; public static string[] OlderProfilePath => m_Config.olderProfilePath; public static bool[] DistanceProfiles = m_Config.distanceProfiles; public static List<string>[] ProfileActions => m_Config.profileActions; public static int getProfileActionCount(int index) { return m_Config.profileActionCount[index]; } public static void CalculateProfileActionCount(int index) { m_Config.CalculateProfileActionCount(index); } public static List<string> getProfileActions(int index) { return m_Config.profileActions[index]; } public static void UpdateDS4CSetting (int deviceNum, string buttonName, bool shift, object action, string exts, DS4KeyType kt, int trigger = 0) { m_Config.UpdateDS4CSetting(deviceNum, buttonName, shift, action, exts, kt, trigger); m_Config.containsCustomAction[deviceNum] = m_Config.HasCustomActions(deviceNum); m_Config.containsCustomExtras[deviceNum] = m_Config.HasCustomExtras(deviceNum); } public static void UpdateDS4Extra(int deviceNum, string buttonName, bool shift, string exts) { m_Config.UpdateDS4CExtra(deviceNum, buttonName, shift, exts); m_Config.containsCustomAction[deviceNum] = m_Config.HasCustomActions(deviceNum); m_Config.containsCustomExtras[deviceNum] = m_Config.HasCustomExtras(deviceNum); } public static object GetDS4Action(int deviceNum, string buttonName, bool shift) => m_Config.GetDS4Action(deviceNum, buttonName, shift); public static object GetDS4Action(int deviceNum, DS4Controls control, bool shift) => m_Config.GetDS4Action(deviceNum, control, shift); public static DS4KeyType GetDS4KeyType(int deviceNum, string buttonName, bool shift) => m_Config.GetDS4KeyType(deviceNum, buttonName, shift); public static string GetDS4Extra(int deviceNum, string buttonName, bool shift) => m_Config.GetDS4Extra(deviceNum, buttonName, shift); public static int GetDS4STrigger(int deviceNum, string buttonName) => m_Config.GetDS4STrigger(deviceNum, buttonName); public static int GetDS4STrigger(int deviceNum, DS4Controls control) => m_Config.GetDS4STrigger(deviceNum, control); public static List<DS4ControlSettings> getDS4CSettings(int device) => m_Config.ds4settings[device]; public static DS4ControlSettings getDS4CSetting(int deviceNum, string control) => m_Config.getDS4CSetting(deviceNum, control); public static DS4ControlSettings getDS4CSetting(int deviceNum, DS4Controls control) => m_Config.getDS4CSetting(deviceNum, control); public static ControlSettingsGroup GetControlSettingsGroup(int deviceNum) => m_Config.ds4controlSettings[deviceNum]; public static bool HasCustomActions(int deviceNum) => m_Config.HasCustomActions(deviceNum); public static bool HasCustomExtras(int deviceNum) => m_Config.HasCustomExtras(deviceNum); public static bool containsCustomAction(int deviceNum) { return m_Config.containsCustomAction[deviceNum]; } public static bool containsCustomExtras(int deviceNum) { return m_Config.containsCustomExtras[deviceNum]; } public static void SaveAction(string name, string controls, int mode, string details, bool edit, string extras = "") { m_Config.SaveAction(name, controls, mode, details, edit, extras); Mapping.actionDone.Add(new Mapping.ActionState()); } public static void RemoveAction(string name) { m_Config.RemoveAction(name); } public static bool LoadActions() => m_Config.LoadActions(); public static List<SpecialAction> GetActions() => m_Config.actions; public static int GetActionIndexOf(string name) { return m_Config.GetActionIndexOf(name); } public static int GetProfileActionIndexOf(int device, string name) { int index = -1; m_Config.profileActionIndexDict[device].TryGetValue(name, out index); return index; } public static SpecialAction GetAction(string name) { return m_Config.GetAction(name); } public static SpecialAction GetProfileAction(int device, string name) { SpecialAction sA = null; m_Config.profileActionDict[device].TryGetValue(name, out sA); return sA; } public static void CalculateProfileActionDicts(int device) { m_Config.CalculateProfileActionDicts(device); } public static void CacheProfileCustomsFlags(int device) { m_Config.CacheProfileCustomsFlags(device); } public static void CacheExtraProfileInfo(int device) { m_Config.CacheExtraProfileInfo(device); } public static X360Controls getX360ControlsByName(string key) { return m_Config.getX360ControlsByName(key); } public static string getX360ControlString(X360Controls key) { return m_Config.getX360ControlString(key); } public static DS4Controls getDS4ControlsByName(string key) { return m_Config.getDS4ControlsByName(key); } public static X360Controls getDefaultX360ControlBinding(DS4Controls dc) { return defaultButtonMapping[(int)dc]; } public static bool containsLinkedProfile(string serial) { string tempSerial = serial.Replace(":", string.Empty); return m_Config.linkedProfiles.ContainsKey(tempSerial); } public static string getLinkedProfile(string serial) { string temp = string.Empty; string tempSerial = serial.Replace(":", string.Empty); if (m_Config.linkedProfiles.ContainsKey(tempSerial)) { temp = m_Config.linkedProfiles[tempSerial]; } return temp; } public static void changeLinkedProfile(string serial, string profile) { string tempSerial = serial.Replace(":", string.Empty); m_Config.linkedProfiles[tempSerial] = profile; } public static void removeLinkedProfile(string serial) { string tempSerial = serial.Replace(":", string.Empty); if (m_Config.linkedProfiles.ContainsKey(tempSerial)) { m_Config.linkedProfiles.Remove(tempSerial); } } public static bool Load() => m_Config.Load(); public static void LoadProfile(int device, bool launchprogram, ControlService control, bool xinputChange = true, bool postLoad = true) { m_Config.LoadProfile(device, launchprogram, control, "", xinputChange, postLoad); tempprofilename[device] = string.Empty; useTempProfile[device] = false; tempprofileDistance[device] = false; } public static void LoadTempProfile(int device, string name, bool launchprogram, ControlService control, bool xinputChange = true) { m_Config.LoadProfile(device, launchprogram, control, appdatapath + @"\Profiles\" + name + ".xml"); tempprofilename[device] = name; useTempProfile[device] = true; tempprofileDistance[device] = name.ToLower().Contains("distance"); } public static void LoadBlankDevProfile(int device, bool launchprogram, ControlService control, bool xinputChange = true, bool postLoad = true) { m_Config.LoadBlankProfile(device, launchprogram, control, "", xinputChange, postLoad); m_Config.EstablishDefaultSpecialActions(device); m_Config.CacheExtraProfileInfo(device); tempprofilename[device] = string.Empty; useTempProfile[device] = false; tempprofileDistance[device] = false; } public static void LoadDefaultGamepadGyroProfile(int device, bool launchprogram, ControlService control, bool xinputChange = true, bool postLoad = true) { m_Config.LoadDefaultGamepadGyroProfile(device, launchprogram, control, "", xinputChange, postLoad); m_Config.EstablishDefaultSpecialActions(device); m_Config.CacheExtraProfileInfo(device); tempprofilename[device] = string.Empty; useTempProfile[device] = false; tempprofileDistance[device] = false; } public static void LoadDefaultMixedControlsProfile(int device, bool launchprogram, ControlService control, bool xinputChange = true, bool postLoad = true) { m_Config.LoadDefaultMixedControlsProfile(device, launchprogram, control, "", xinputChange, postLoad); m_Config.EstablishDefaultSpecialActions(device); m_Config.CacheExtraProfileInfo(device); tempprofilename[device] = string.Empty; useTempProfile[device] = false; tempprofileDistance[device] = false; } public static void LoadDefaultMixedGyroMouseProfile(int device, bool launchprogram, ControlService control, bool xinputChange = true, bool postLoad = true) { m_Config.LoadDefaultMixedGyroMouseProfile(device, launchprogram, control, "", xinputChange, postLoad); m_Config.EstablishDefaultSpecialActions(device); m_Config.CacheExtraProfileInfo(device); tempprofilename[device] = string.Empty; useTempProfile[device] = false; tempprofileDistance[device] = false; } public static void LoadDefaultKBMProfile(int device, bool launchprogram, ControlService control, bool xinputChange = true, bool postLoad = true) { m_Config.LoadDefaultKBMProfile(device, launchprogram, control, "", xinputChange, postLoad); m_Config.EstablishDefaultSpecialActions(device); m_Config.CacheExtraProfileInfo(device); tempprofilename[device] = string.Empty; useTempProfile[device] = false; tempprofileDistance[device] = false; } public static void LoadDefaultKBMGyroMouseProfile(int device, bool launchprogram, ControlService control, bool xinputChange = true, bool postLoad = true) { m_Config.LoadDefaultKBMGyroMouseProfile(device, launchprogram, control, "", xinputChange, postLoad); m_Config.EstablishDefaultSpecialActions(device); m_Config.CacheExtraProfileInfo(device); tempprofilename[device] = string.Empty; useTempProfile[device] = false; tempprofileDistance[device] = false; } public static bool Save() { return m_Config.Save(); } public static void SaveProfile(int device, string proName) { m_Config.SaveProfile(device, proName); } public static void SaveAsNewProfile(int device, string propath) { m_Config.SaveAsNewProfile(device, propath); } public static bool SaveLinkedProfiles() { return m_Config.SaveLinkedProfiles(); } public static bool LoadLinkedProfiles() { return m_Config.LoadLinkedProfiles(); } public static bool SaveControllerConfigs(DS4Device device = null) { if (device != null) return m_Config.SaveControllerConfigsForDevice(device); for (int idx = 0; idx < ControlService.MAX_DS4_CONTROLLER_COUNT; idx++) if (Program.rootHub.DS4Controllers[idx] != null) m_Config.SaveControllerConfigsForDevice(Program.rootHub.DS4Controllers[idx]); return true; } public static bool LoadControllerConfigs(DS4Device device = null) { if (device != null) return m_Config.LoadControllerConfigsForDevice(device); for (int idx = 0; idx < ControlService.MAX_DS4_CONTROLLER_COUNT; idx++) if (Program.rootHub.DS4Controllers[idx] != null) m_Config.LoadControllerConfigsForDevice(Program.rootHub.DS4Controllers[idx]); return true; } private static byte applyRatio(byte b1, byte b2, double r) { if (r > 100.0) r = 100.0; else if (r < 0.0) r = 0.0; r *= 0.01; return (byte)Math.Round((b1 * (1 - r)) + b2 * r, 0); } public static DS4Color getTransitionedColor(ref DS4Color c1, ref DS4Color c2, double ratio) { //Color cs = Color.FromArgb(c1.red, c1.green, c1.blue); DS4Color cs = new DS4Color { red = applyRatio(c1.red, c2.red, ratio), green = applyRatio(c1.green, c2.green, ratio), blue = applyRatio(c1.blue, c2.blue, ratio) }; return cs; } private static Color applyRatio(Color c1, Color c2, uint r) { float ratio = r / 100f; float hue1 = c1.GetHue(); float hue2 = c2.GetHue(); float bri1 = c1.GetBrightness(); float bri2 = c2.GetBrightness(); float sat1 = c1.GetSaturation(); float sat2 = c2.GetSaturation(); float hr = hue2 - hue1; float br = bri2 - bri1; float sr = sat2 - sat1; Color csR; if (bri1 == 0) csR = HuetoRGB(hue2,sat2,bri2 - br*ratio); else csR = HuetoRGB(hue2 - hr * ratio, sat2 - sr * ratio, bri2 - br * ratio); return csR; } public static Color HuetoRGB(float hue, float sat, float bri) { float C = (1-Math.Abs(2*bri)-1)* sat; float X = C * (1 - Math.Abs((hue / 60) % 2 - 1)); float m = bri - C / 2; float R, G, B; if (0 <= hue && hue < 60) { R = C; G = X; B = 0; } else if (60 <= hue && hue < 120) { R = X; G = C; B = 0; } else if (120 <= hue && hue < 180) { R = 0; G = C; B = X; } else if (180 <= hue && hue < 240) { R = 0; G = X; B = C; } else if (240 <= hue && hue < 300) { R = X; G = 0; B = C; } else if (300 <= hue && hue < 360) { R = C; G = 0; B = X; } else { R = 255; G = 0; B = 0; } R += m; G += m; B += m; R *= 255.0f; G *= 255.0f; B *= 255.0f; return Color.FromArgb((int)R, (int)G, (int)B); } public static double Clamp(double min, double value, double max) { return (value < min) ? min : (value > max) ? max : value; } private static int ClampInt(int min, int value, int max) { return (value < min) ? min : (value > max) ? max : value; } } public class BackingStore { public const double DEFAULT_UDP_SMOOTH_MINCUTOFF = 0.4; public const double DEFAULT_UDP_SMOOTH_BETA = 0.2; //public String m_Profile = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\DS4Tool" + "\\Profiles.xml"; public String m_Profile = Directory.GetParent(Assembly.GetExecutingAssembly().Location).FullName + "\\Profiles.xml"; public String m_Actions = Global.appdatapath + "\\Actions.xml"; public string m_linkedProfiles = Global.appdatapath + "\\LinkedProfiles.xml"; public string m_controllerConfigs = Global.appdatapath + "\\ControllerConfigs.xml"; protected XmlDocument m_Xdoc = new XmlDocument(); // ninth (fifth in old builds) value used for options, not last controller public ButtonMouseInfo[] buttonMouseInfos = new ButtonMouseInfo[Global.TEST_PROFILE_ITEM_COUNT] { new ButtonMouseInfo(), new ButtonMouseInfo(), new ButtonMouseInfo(), new ButtonMouseInfo(), new ButtonMouseInfo(), new ButtonMouseInfo(), new ButtonMouseInfo(), new ButtonMouseInfo(), new ButtonMouseInfo(), }; public bool[] enableTouchToggle = new bool[Global.TEST_PROFILE_ITEM_COUNT] { true, true, true, true, true, true, true, true, true }; public int[] idleDisconnectTimeout = new int[Global.TEST_PROFILE_ITEM_COUNT] { 0, 0, 0, 0, 0, 0, 0, 0, 0 }; public bool[] enableOutputDataToDS4 = new bool[Global.TEST_PROFILE_ITEM_COUNT] { true, true, true, true, true, true, true, true, true }; public bool[] touchpadJitterCompensation = new bool[Global.TEST_PROFILE_ITEM_COUNT] { true, true, true, true, true, true, true, true, true }; public bool[] lowerRCOn = new bool[Global.TEST_PROFILE_ITEM_COUNT] { false, false, false, false, false, false, false, false, false }; public string[] profilePath = new string[Global.TEST_PROFILE_ITEM_COUNT] { string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty }; public string[] olderProfilePath = new string[Global.TEST_PROFILE_ITEM_COUNT] { string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty }; public Dictionary<string, string> linkedProfiles = new Dictionary<string, string>(); // Cache properties instead of performing a string comparison every frame public bool[] distanceProfiles = new bool[Global.TEST_PROFILE_ITEM_COUNT] { false, false, false, false, false, false, false, false, false }; public Byte[] rumble = new Byte[Global.TEST_PROFILE_ITEM_COUNT] { 100, 100, 100, 100, 100, 100, 100, 100, 100 }; public int[] rumbleAutostopTime = new int[Global.TEST_PROFILE_ITEM_COUNT] { 0, 0, 0, 0, 0, 0, 0, 0, 0 }; // Value in milliseconds (0=autustop timer disabled) public Byte[] touchSensitivity = new Byte[Global.TEST_PROFILE_ITEM_COUNT] { 100, 100, 100, 100, 100, 100, 100, 100, 100 }; public StickDeadZoneInfo[] lsModInfo = new StickDeadZoneInfo[Global.TEST_PROFILE_ITEM_COUNT] { new StickDeadZoneInfo(), new StickDeadZoneInfo(), new StickDeadZoneInfo(), new StickDeadZoneInfo(), new StickDeadZoneInfo(), new StickDeadZoneInfo(), new StickDeadZoneInfo(), new StickDeadZoneInfo(), new StickDeadZoneInfo(), }; public StickDeadZoneInfo[] rsModInfo = new StickDeadZoneInfo[Global.TEST_PROFILE_ITEM_COUNT] { new StickDeadZoneInfo(), new StickDeadZoneInfo(), new StickDeadZoneInfo(), new StickDeadZoneInfo(), new StickDeadZoneInfo(), new StickDeadZoneInfo(), new StickDeadZoneInfo(), new StickDeadZoneInfo(), new StickDeadZoneInfo(), }; public TriggerDeadZoneZInfo[] l2ModInfo = new TriggerDeadZoneZInfo[Global.TEST_PROFILE_ITEM_COUNT] { new TriggerDeadZoneZInfo(), new TriggerDeadZoneZInfo(), new TriggerDeadZoneZInfo(), new TriggerDeadZoneZInfo(), new TriggerDeadZoneZInfo(), new TriggerDeadZoneZInfo(), new TriggerDeadZoneZInfo(), new TriggerDeadZoneZInfo(), new TriggerDeadZoneZInfo(), }; public TriggerDeadZoneZInfo[] r2ModInfo = new TriggerDeadZoneZInfo[Global.TEST_PROFILE_ITEM_COUNT] { new TriggerDeadZoneZInfo(), new TriggerDeadZoneZInfo(), new TriggerDeadZoneZInfo(), new TriggerDeadZoneZInfo(), new TriggerDeadZoneZInfo(), new TriggerDeadZoneZInfo(), new TriggerDeadZoneZInfo(), new TriggerDeadZoneZInfo(), new TriggerDeadZoneZInfo(), }; public double[] LSRotation = new double[Global.TEST_PROFILE_ITEM_COUNT] { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 }, RSRotation = new double[Global.TEST_PROFILE_ITEM_COUNT] { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 }; public double[] SXDeadzone = new double[Global.TEST_PROFILE_ITEM_COUNT] { 0.25, 0.25, 0.25, 0.25, 0.25, 0.25, 0.25, 0.25, 0.25 }, SZDeadzone = new double[Global.TEST_PROFILE_ITEM_COUNT] { 0.25, 0.25, 0.25, 0.25, 0.25, 0.25, 0.25, 0.25, 0.25 }; public double[] SXMaxzone = new double[Global.TEST_PROFILE_ITEM_COUNT] { 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0 }, SZMaxzone = new double[Global.TEST_PROFILE_ITEM_COUNT] { 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0 }; public double[] SXAntiDeadzone = new double[Global.TEST_PROFILE_ITEM_COUNT] { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 }, SZAntiDeadzone = new double[Global.TEST_PROFILE_ITEM_COUNT] { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 }; public double[] l2Sens = new double[Global.TEST_PROFILE_ITEM_COUNT] { 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0 }, r2Sens = new double[Global.TEST_PROFILE_ITEM_COUNT] { 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0 }; public double[] LSSens = new double[Global.TEST_PROFILE_ITEM_COUNT] { 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0 }, RSSens = new double[Global.TEST_PROFILE_ITEM_COUNT] { 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0 }; public double[] SXSens = new double[Global.TEST_PROFILE_ITEM_COUNT] { 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0 }, SZSens = new double[Global.TEST_PROFILE_ITEM_COUNT] { 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0 }; public Byte[] tapSensitivity = new Byte[Global.TEST_PROFILE_ITEM_COUNT] { 0, 0, 0, 0, 0, 0, 0, 0, 0 }; public bool[] doubleTap = new bool[Global.TEST_PROFILE_ITEM_COUNT] { false, false, false, false, false, false, false, false, false }; public int[] scrollSensitivity = new int[Global.TEST_PROFILE_ITEM_COUNT] { 0, 0, 0, 0, 0, 0, 0, 0, 0 }; public int[] touchpadInvert = new int[Global.TEST_PROFILE_ITEM_COUNT] { 0, 0, 0, 0, 0, 0, 0, 0, 0 }; public int[] btPollRate = new int[Global.TEST_PROFILE_ITEM_COUNT] { 4, 4, 4, 4, 4, 4, 4, 4, 4 }; public int[] gyroMouseDZ = new int[Global.TEST_PROFILE_ITEM_COUNT] { MouseCursor.GYRO_MOUSE_DEADZONE, MouseCursor.GYRO_MOUSE_DEADZONE, MouseCursor.GYRO_MOUSE_DEADZONE, MouseCursor.GYRO_MOUSE_DEADZONE, MouseCursor.GYRO_MOUSE_DEADZONE, MouseCursor.GYRO_MOUSE_DEADZONE, MouseCursor.GYRO_MOUSE_DEADZONE,MouseCursor.GYRO_MOUSE_DEADZONE, MouseCursor.GYRO_MOUSE_DEADZONE,}; public bool[] gyroMouseToggle = new bool[Global.TEST_PROFILE_ITEM_COUNT] { false, false, false, false, false, false, false, false, false }; public SquareStickInfo[] squStickInfo = new SquareStickInfo[Global.TEST_PROFILE_ITEM_COUNT] { new SquareStickInfo(), new SquareStickInfo(), new SquareStickInfo(), new SquareStickInfo(), new SquareStickInfo(), new SquareStickInfo(), new SquareStickInfo(), new SquareStickInfo(), new SquareStickInfo(), }; public StickOutputSetting[] lsOutputSettings = new StickOutputSetting[Global.TEST_PROFILE_ITEM_COUNT] { new StickOutputSetting(), new StickOutputSetting(), new StickOutputSetting(), new StickOutputSetting(), new StickOutputSetting(), new StickOutputSetting(), new StickOutputSetting(), new StickOutputSetting(), new StickOutputSetting(), }; public StickOutputSetting[] rsOutputSettings = new StickOutputSetting[Global.TEST_PROFILE_ITEM_COUNT] { new StickOutputSetting(), new StickOutputSetting(), new StickOutputSetting(), new StickOutputSetting(), new StickOutputSetting(), new StickOutputSetting(), new StickOutputSetting(), new StickOutputSetting(), new StickOutputSetting(), }; public SteeringWheelSmoothingInfo[] wheelSmoothInfo = new SteeringWheelSmoothingInfo[Global.TEST_PROFILE_ITEM_COUNT] { new SteeringWheelSmoothingInfo(), new SteeringWheelSmoothingInfo(), new SteeringWheelSmoothingInfo(), new SteeringWheelSmoothingInfo(), new SteeringWheelSmoothingInfo(), new SteeringWheelSmoothingInfo(), new SteeringWheelSmoothingInfo(), new SteeringWheelSmoothingInfo(), new SteeringWheelSmoothingInfo(), }; public int[] saWheelFuzzValues = new int[Global.TEST_PROFILE_ITEM_COUNT]; private void setOutBezierCurveObjArrayItem(BezierCurve[] bezierCurveArray, int device, int curveOptionValue, BezierCurve.AxisType axisType) { // Set bezier curve obj of axis. 0=Linear (no curve mapping), 1-5=Pre-defined curves, 6=User supplied custom curve string value of a profile (comma separated list of 4 decimal numbers) switch (curveOptionValue) { // Commented out case 1..5 because Mapping.cs:SetCurveAndDeadzone function has the original IF-THEN-ELSE code logic for those original 1..5 output curve mappings (ie. no need to initialize the lookup result table). // Only the new bezier custom curve option 6 uses the lookup result table (initialized in BezierCurve class based on an input curve definition). //case 1: bezierCurveArray[device].InitBezierCurve(99.0, 91.0, 0.00, 0.00, axisType); break; // Enhanced Precision (hard-coded curve) (almost the same curve as bezier 0.70, 0.28, 1.00, 1.00) //case 2: bezierCurveArray[device].InitBezierCurve(99.0, 92.0, 0.00, 0.00, axisType); break; // Quadric //case 3: bezierCurveArray[device].InitBezierCurve(99.0, 93.0, 0.00, 0.00, axisType); break; // Cubic //case 4: bezierCurveArray[device].InitBezierCurve(99.0, 94.0, 0.00, 0.00, axisType); break; // Easeout Quad //case 5: bezierCurveArray[device].InitBezierCurve(99.0, 95.0, 0.00, 0.00, axisType); break; // Easeout Cubic case 6: bezierCurveArray[device].InitBezierCurve(bezierCurveArray[device].CustomDefinition, axisType); break; // Custom output curve } } public BezierCurve[] lsOutBezierCurveObj = new BezierCurve[Global.TEST_PROFILE_ITEM_COUNT] { new BezierCurve(), new BezierCurve(), new BezierCurve(), new BezierCurve(), new BezierCurve(), new BezierCurve(), new BezierCurve(), new BezierCurve(), new BezierCurve() }; public BezierCurve[] rsOutBezierCurveObj = new BezierCurve[Global.TEST_PROFILE_ITEM_COUNT] { new BezierCurve(), new BezierCurve(), new BezierCurve(), new BezierCurve(), new BezierCurve(), new BezierCurve(), new BezierCurve(), new BezierCurve(), new BezierCurve() }; public BezierCurve[] l2OutBezierCurveObj = new BezierCurve[Global.TEST_PROFILE_ITEM_COUNT] { new BezierCurve(), new BezierCurve(), new BezierCurve(), new BezierCurve(), new BezierCurve(), new BezierCurve(), new BezierCurve(), new BezierCurve(), new BezierCurve() }; public BezierCurve[] r2OutBezierCurveObj = new BezierCurve[Global.TEST_PROFILE_ITEM_COUNT] { new BezierCurve(), new BezierCurve(), new BezierCurve(), new BezierCurve(), new BezierCurve(), new BezierCurve(), new BezierCurve(), new BezierCurve(), new BezierCurve() }; public BezierCurve[] sxOutBezierCurveObj = new BezierCurve[Global.TEST_PROFILE_ITEM_COUNT] { new BezierCurve(), new BezierCurve(), new BezierCurve(), new BezierCurve(), new BezierCurve(), new BezierCurve(), new BezierCurve(), new BezierCurve(), new BezierCurve() }; public BezierCurve[] szOutBezierCurveObj = new BezierCurve[Global.TEST_PROFILE_ITEM_COUNT] { new BezierCurve(), new BezierCurve(), new BezierCurve(), new BezierCurve(), new BezierCurve(), new BezierCurve(), new BezierCurve(), new BezierCurve(), new BezierCurve() }; private int[] _lsOutCurveMode = new int[Global.TEST_PROFILE_ITEM_COUNT] { 0, 0, 0, 0, 0, 0, 0, 0, 0 }; public int getLsOutCurveMode(int index) { return _lsOutCurveMode[index]; } public void setLsOutCurveMode(int index, int value) { if (value >= 1) setOutBezierCurveObjArrayItem(lsOutBezierCurveObj, index, value, BezierCurve.AxisType.LSRS); _lsOutCurveMode[index] = value; } private int[] _rsOutCurveMode = new int[Global.TEST_PROFILE_ITEM_COUNT] { 0, 0, 0, 0, 0, 0, 0, 0, 0 }; public int getRsOutCurveMode(int index) { return _rsOutCurveMode[index]; } public void setRsOutCurveMode(int index, int value) { if (value >= 1) setOutBezierCurveObjArrayItem(rsOutBezierCurveObj, index, value, BezierCurve.AxisType.LSRS); _rsOutCurveMode[index] = value; } private int[] _l2OutCurveMode = new int[Global.TEST_PROFILE_ITEM_COUNT] { 0, 0, 0, 0, 0, 0, 0, 0, 0 }; public int getL2OutCurveMode(int index) { return _l2OutCurveMode[index]; } public void setL2OutCurveMode(int index, int value) { if (value >= 1) setOutBezierCurveObjArrayItem(l2OutBezierCurveObj, index, value, BezierCurve.AxisType.L2R2); _l2OutCurveMode[index] = value; } private int[] _r2OutCurveMode = new int[Global.TEST_PROFILE_ITEM_COUNT] { 0, 0, 0, 0, 0, 0, 0, 0, 0 }; public int getR2OutCurveMode(int index) { return _r2OutCurveMode[index]; } public void setR2OutCurveMode(int index, int value) { if (value >= 1) setOutBezierCurveObjArrayItem(r2OutBezierCurveObj, index, value, BezierCurve.AxisType.L2R2); _r2OutCurveMode[index] = value; } private int[] _sxOutCurveMode = new int[Global.TEST_PROFILE_ITEM_COUNT] { 0, 0, 0, 0, 0, 0, 0, 0, 0 }; public int getSXOutCurveMode(int index) { return _sxOutCurveMode[index]; } public void setSXOutCurveMode(int index, int value) { if (value >= 1) setOutBezierCurveObjArrayItem(sxOutBezierCurveObj, index, value, BezierCurve.AxisType.SA); _sxOutCurveMode[index] = value; } private int[] _szOutCurveMode = new int[Global.TEST_PROFILE_ITEM_COUNT] { 0, 0, 0, 0, 0, 0, 0, 0, 0 }; public int getSZOutCurveMode(int index) { return _szOutCurveMode[index]; } public void setSZOutCurveMode(int index, int value) { if (value >= 1) setOutBezierCurveObjArrayItem(szOutBezierCurveObj, index, value, BezierCurve.AxisType.SA); _szOutCurveMode[index] = value; } public LightbarSettingInfo[] lightbarSettingInfo = new LightbarSettingInfo[Global.TEST_PROFILE_ITEM_COUNT] { new LightbarSettingInfo(), new LightbarSettingInfo(), new LightbarSettingInfo(), new LightbarSettingInfo(), new LightbarSettingInfo(), new LightbarSettingInfo(), new LightbarSettingInfo(), new LightbarSettingInfo(), new LightbarSettingInfo(), }; public string[] launchProgram = new string[Global.TEST_PROFILE_ITEM_COUNT] { string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty }; public bool[] dinputOnly = new bool[Global.TEST_PROFILE_ITEM_COUNT] { false, false, false, false, false, false, false, false, false }; public bool[] startTouchpadOff = new bool[Global.TEST_PROFILE_ITEM_COUNT] { false, false, false, false, false, false, false, false, false }; public TouchpadOutMode[] touchOutMode = new TouchpadOutMode[Global.TEST_PROFILE_ITEM_COUNT] { TouchpadOutMode.Mouse, TouchpadOutMode.Mouse, TouchpadOutMode.Mouse, TouchpadOutMode.Mouse, TouchpadOutMode.Mouse, TouchpadOutMode.Mouse, TouchpadOutMode.Mouse, TouchpadOutMode.Mouse, TouchpadOutMode.Mouse }; public GyroOutMode[] gyroOutMode = new GyroOutMode[Global.TEST_PROFILE_ITEM_COUNT] { GyroOutMode.Controls, GyroOutMode.Controls, GyroOutMode.Controls, GyroOutMode.Controls, GyroOutMode.Controls, GyroOutMode.Controls, GyroOutMode.Controls, GyroOutMode.Controls, GyroOutMode.Controls }; public string[] sATriggers = new string[Global.TEST_PROFILE_ITEM_COUNT] { "-1", "-1", "-1", "-1", "-1", "-1", "-1", "-1", "-1" }; public string[] sAMouseStickTriggers = new string[Global.TEST_PROFILE_ITEM_COUNT] { "-1", "-1", "-1", "-1", "-1", "-1", "-1", "-1", "-1" }; public bool[] sATriggerCond = new bool[Global.TEST_PROFILE_ITEM_COUNT] { true, true, true, true, true, true, true, true, true }; public bool[] sAMouseStickTriggerCond = new bool[Global.TEST_PROFILE_ITEM_COUNT] { true, true, true, true, true, true, true, true, true }; public bool[] gyroMouseStickTriggerTurns = new bool[Global.TEST_PROFILE_ITEM_COUNT] { true, true, true, true, true, true, true, true, true }; public GyroMouseStickInfo[] gyroMStickInfo = new GyroMouseStickInfo[Global.TEST_PROFILE_ITEM_COUNT] { new GyroMouseStickInfo(), new GyroMouseStickInfo(), new GyroMouseStickInfo(), new GyroMouseStickInfo(), new GyroMouseStickInfo(), new GyroMouseStickInfo(), new GyroMouseStickInfo(), new GyroMouseStickInfo(), new GyroMouseStickInfo(), }; public bool[] gyroMouseStickToggle = new bool[Global.TEST_PROFILE_ITEM_COUNT] { false, false, false, false, false, false, false, false, false }; public SASteeringWheelEmulationAxisType[] sASteeringWheelEmulationAxis = new SASteeringWheelEmulationAxisType[Global.TEST_PROFILE_ITEM_COUNT] { SASteeringWheelEmulationAxisType.None, SASteeringWheelEmulationAxisType.None, SASteeringWheelEmulationAxisType.None, SASteeringWheelEmulationAxisType.None, SASteeringWheelEmulationAxisType.None, SASteeringWheelEmulationAxisType.None, SASteeringWheelEmulationAxisType.None, SASteeringWheelEmulationAxisType.None, SASteeringWheelEmulationAxisType.None }; public int[] sASteeringWheelEmulationRange = new int[Global.TEST_PROFILE_ITEM_COUNT] { 360, 360, 360, 360, 360, 360, 360, 360, 360 }; public int[][] touchDisInvertTriggers = new int[Global.TEST_PROFILE_ITEM_COUNT][] { new int[1] { -1 }, new int[1] { -1 }, new int[1] { -1 }, new int[1] { -1 }, new int[1] { -1 }, new int[1] { -1 }, new int[1] { -1 }, new int[1] { -1 }, new int[1] { -1 } }; public int[] lsCurve = new int[Global.TEST_PROFILE_ITEM_COUNT] { 0, 0, 0, 0, 0, 0, 0, 0, 0 }; public int[] rsCurve = new int[Global.TEST_PROFILE_ITEM_COUNT] { 0, 0, 0, 0, 0, 0, 0, 0, 0 }; public Boolean useExclusiveMode = false; // Re-enable Ex Mode public Int32 formWidth = 782; public Int32 formHeight = 550; public int formLocationX = 0; public int formLocationY = 0; public Boolean startMinimized = false; public Boolean minToTaskbar = false; public DateTime lastChecked; public string lastVersionChecked = string.Empty; public ulong lastVersionCheckedNum; public int CheckWhen = 24; public int notifications = 2; public bool disconnectBTAtStop = false; public bool swipeProfiles = true; public bool ds4Mapping = false; public bool quickCharge = false; public bool closeMini = false; public List<SpecialAction> actions = new List<SpecialAction>(); public List<DS4ControlSettings>[] ds4settings = new List<DS4ControlSettings>[Global.TEST_PROFILE_ITEM_COUNT] { new List<DS4ControlSettings>(), new List<DS4ControlSettings>(), new List<DS4ControlSettings>(), new List<DS4ControlSettings>(), new List<DS4ControlSettings>(), new List<DS4ControlSettings>(), new List<DS4ControlSettings>(), new List<DS4ControlSettings>(), new List<DS4ControlSettings>() }; public ControlSettingsGroup[] ds4controlSettings; public List<string>[] profileActions = new List<string>[Global.TEST_PROFILE_ITEM_COUNT] { null, null, null, null, null, null, null, null, null }; public int[] profileActionCount = new int[Global.TEST_PROFILE_ITEM_COUNT] { 0, 0, 0, 0, 0, 0, 0, 0, 0 }; public Dictionary<string, SpecialAction>[] profileActionDict = new Dictionary<string, SpecialAction>[Global.TEST_PROFILE_ITEM_COUNT] { new Dictionary<string, SpecialAction>(), new Dictionary<string, SpecialAction>(), new Dictionary<string, SpecialAction>(), new Dictionary<string, SpecialAction>(), new Dictionary<string, SpecialAction>(), new Dictionary<string, SpecialAction>(), new Dictionary<string, SpecialAction>(), new Dictionary<string, SpecialAction>(), new Dictionary<string, SpecialAction>() }; public Dictionary<string, int>[] profileActionIndexDict = new Dictionary<string, int>[Global.TEST_PROFILE_ITEM_COUNT] { new Dictionary<string, int>(), new Dictionary<string, int>(), new Dictionary<string, int>(), new Dictionary<string, int>(), new Dictionary<string, int>(), new Dictionary<string, int>(), new Dictionary<string, int>(), new Dictionary<string, int>(), new Dictionary<string, int>() }; public string useLang = ""; public bool downloadLang = true; public TrayIconChoice useIconChoice; public bool flashWhenLate = true; public int flashWhenLateAt = 40; public bool useUDPServ = false; public int udpServPort = 26760; public string udpServListenAddress = "127.0.0.1"; // 127.0.0.1=IPAddress.Loopback (default), 0.0.0.0=IPAddress.Any as all interfaces, x.x.x.x = Specific ipv4 interface address or hostname public bool useUdpSmoothing; public double udpSmoothingMincutoff = DEFAULT_UDP_SMOOTH_MINCUTOFF; public double udpSmoothingBeta = DEFAULT_UDP_SMOOTH_BETA; public bool useCustomSteamFolder; public string customSteamFolder; public AppThemeChoice useCurrentTheme; public string fakeExeFileName = string.Empty; // Cache whether profile has custom action public bool[] containsCustomAction = new bool[Global.TEST_PROFILE_ITEM_COUNT] { false, false, false, false, false, false, false, false, false }; // Cache whether profile has custom extras public bool[] containsCustomExtras = new bool[Global.TEST_PROFILE_ITEM_COUNT] { false, false, false, false, false, false, false, false, false }; public int[] gyroSensitivity = new int[Global.TEST_PROFILE_ITEM_COUNT] { 100, 100, 100, 100, 100, 100, 100, 100, 100 }; public int[] gyroSensVerticalScale = new int[Global.TEST_PROFILE_ITEM_COUNT] { 100, 100, 100, 100, 100, 100, 100, 100, 100 }; public int[] gyroInvert = new int[Global.TEST_PROFILE_ITEM_COUNT] { 0, 0, 0, 0, 0, 0, 0, 0, 0 }; public bool[] gyroTriggerTurns = new bool[Global.TEST_PROFILE_ITEM_COUNT] { true, true, true, true, true, true, true, true, true }; public GyroMouseInfo[] gyroMouseInfo = new GyroMouseInfo[Global.TEST_PROFILE_ITEM_COUNT] { new GyroMouseInfo(), new GyroMouseInfo(), new GyroMouseInfo(), new GyroMouseInfo(), new GyroMouseInfo(), new GyroMouseInfo(), new GyroMouseInfo(), new GyroMouseInfo(), new GyroMouseInfo(), }; public int[] gyroMouseHorizontalAxis = new int[Global.TEST_PROFILE_ITEM_COUNT] { 0, 0, 0, 0, 0, 0, 0, 0, 0 }; public int[] gyroMouseStickHorizontalAxis = new int[Global.TEST_PROFILE_ITEM_COUNT] { 0, 0, 0, 0, 0, 0, 0, 0, 0 }; public bool[] trackballMode = new bool[Global.TEST_PROFILE_ITEM_COUNT] { false, false, false, false, false, false, false, false, false }; public double[] trackballFriction = new double[Global.TEST_PROFILE_ITEM_COUNT] { 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0 }; public TouchpadAbsMouseSettings[] touchpadAbsMouse = new TouchpadAbsMouseSettings[Global.TEST_PROFILE_ITEM_COUNT] { new TouchpadAbsMouseSettings(), new TouchpadAbsMouseSettings(), new TouchpadAbsMouseSettings(), new TouchpadAbsMouseSettings(),new TouchpadAbsMouseSettings(),new TouchpadAbsMouseSettings(),new TouchpadAbsMouseSettings(),new TouchpadAbsMouseSettings(),new TouchpadAbsMouseSettings() }; public TouchpadRelMouseSettings[] touchpadRelMouse = new TouchpadRelMouseSettings[Global.TEST_PROFILE_ITEM_COUNT] { new TouchpadRelMouseSettings(), new TouchpadRelMouseSettings(), new TouchpadRelMouseSettings(), new TouchpadRelMouseSettings(), new TouchpadRelMouseSettings(), new TouchpadRelMouseSettings(), new TouchpadRelMouseSettings(), new TouchpadRelMouseSettings(), new TouchpadRelMouseSettings() }; // Used to hold the controller type desired in a profile public OutContType[] outputDevType = new OutContType[Global.TEST_PROFILE_ITEM_COUNT] { OutContType.X360, OutContType.X360, OutContType.X360, OutContType.X360, OutContType.X360, OutContType.X360, OutContType.X360, OutContType.X360, OutContType.X360}; // TRUE=AutoProfile reverts to default profile if current foreground process is unknown, FALSE=Leave existing profile active when a foreground proces is unknown (ie. no matching auto-profile rule) public bool autoProfileRevertDefaultProfile = true; bool tempBool = false; public BackingStore() { ds4controlSettings = new ControlSettingsGroup[Global.TEST_PROFILE_ITEM_COUNT]; for (int i = 0; i < Global.TEST_PROFILE_ITEM_COUNT; i++) { foreach (DS4Controls dc in Enum.GetValues(typeof(DS4Controls))) { if (dc != DS4Controls.None) ds4settings[i].Add(new DS4ControlSettings(dc)); } ds4controlSettings[i] = new ControlSettingsGroup(ds4settings[i]); EstablishDefaultSpecialActions(i); CacheExtraProfileInfo(i); } SetupDefaultColors(); } public void EstablishDefaultSpecialActions(int idx) { profileActions[idx] = new List<string>(); profileActions[idx].Add("Disconnect Controller"); profileActionCount[idx] = profileActions[idx].Count; } public void CacheProfileCustomsFlags(int device) { bool customAct = false; containsCustomAction[device] = customAct = HasCustomActions(device); containsCustomExtras[device] = HasCustomExtras(device); if (!customAct) { customAct = gyroOutMode[device] == GyroOutMode.MouseJoystick; customAct = customAct || sASteeringWheelEmulationAxis[device] >= SASteeringWheelEmulationAxisType.VJoy1X; customAct = customAct || lsOutputSettings[device].mode != StickMode.Controls; customAct = customAct || rsOutputSettings[device].mode != StickMode.Controls; containsCustomAction[device] = customAct; } } private void SetupDefaultColors() { lightbarSettingInfo[0].ds4winSettings.m_Led = new DS4Color(Color.Blue); lightbarSettingInfo[1].ds4winSettings.m_Led = new DS4Color(Color.Red); lightbarSettingInfo[2].ds4winSettings.m_Led = new DS4Color(Color.Green); lightbarSettingInfo[3].ds4winSettings.m_Led = new DS4Color(Color.Pink); lightbarSettingInfo[4].ds4winSettings.m_Led = new DS4Color(Color.Blue); lightbarSettingInfo[5].ds4winSettings.m_Led = new DS4Color(Color.Red); lightbarSettingInfo[6].ds4winSettings.m_Led = new DS4Color(Color.Green); lightbarSettingInfo[7].ds4winSettings.m_Led = new DS4Color(Color.Pink); lightbarSettingInfo[8].ds4winSettings.m_Led = new DS4Color(Color.White); } public void CacheExtraProfileInfo(int device) { CalculateProfileActionCount(device); CalculateProfileActionDicts(device); CacheProfileCustomsFlags(device); } public void CalculateProfileActionCount(int index) { profileActionCount[index] = profileActions[index].Count; } public void CalculateProfileActionDicts(int device) { profileActionDict[device].Clear(); profileActionIndexDict[device].Clear(); foreach (string actionname in profileActions[device]) { profileActionDict[device][actionname] = GetAction(actionname); profileActionIndexDict[device][actionname] = GetActionIndexOf(actionname); } } public SpecialAction GetAction(string name) { //foreach (SpecialAction sA in actions) for (int i = 0, actionCount = actions.Count; i < actionCount; i++) { SpecialAction sA = actions[i]; if (sA.name == name) return sA; } return new SpecialAction("null", "null", "null", "null"); } public int GetActionIndexOf(string name) { for (int i = 0, actionCount = actions.Count; i < actionCount; i++) { if (actions[i].name == name) return i; } return -1; } private string stickOutputCurveString(int id) { string result = "linear"; switch (id) { case 0: break; case 1: result = "enhanced-precision"; break; case 2: result = "quadratic"; break; case 3: result = "cubic"; break; case 4: result = "easeout-quad"; break; case 5: result = "easeout-cubic"; break; case 6: result = "custom"; break; default: break; } return result; } private int stickOutputCurveId(string name) { int id = 0; switch (name) { case "linear": id = 0; break; case "enhanced-precision": id = 1; break; case "quadratic": id = 2; break; case "cubic": id = 3; break; case "easeout-quad": id = 4; break; case "easeout-cubic": id = 5; break; case "custom": id = 6; break; default: break; } return id; } private string axisOutputCurveString(int id) { return stickOutputCurveString(id); } private int axisOutputCurveId(string name) { return stickOutputCurveId(name); } private bool SaTriggerCondValue(string text) { bool result = true; switch (text) { case "and": result = true; break; case "or": result = false; break; default: result = true; break; } return result; } private string SaTriggerCondString(bool value) { string result = value ? "and" : "or"; return result; } public void SetSaTriggerCond(int index, string text) { sATriggerCond[index] = SaTriggerCondValue(text); } public void SetSaMouseStickTriggerCond(int index, string text) { sAMouseStickTriggerCond[index] = SaTriggerCondValue(text); } public void SetGyroMouseDZ(int index, int value, ControlService control) { gyroMouseDZ[index] = value; if (index < ControlService.CURRENT_DS4_CONTROLLER_LIMIT && control.touchPad[index] != null) control.touchPad[index].CursorGyroDead = value; } public void SetGyroMouseToggle(int index, bool value, ControlService control) { gyroMouseToggle[index] = value; if (index < ControlService.CURRENT_DS4_CONTROLLER_LIMIT && control.touchPad[index] != null) control.touchPad[index].ToggleGyroMouse = value; } public void SetGyroMouseStickToggle(int index, bool value, ControlService control) { gyroMouseStickToggle[index] = value; if (index < ControlService.CURRENT_DS4_CONTROLLER_LIMIT && control.touchPad[index] != null) control.touchPad[index].ToggleGyroMouse = value; } private string OutContDeviceString(OutContType id) { string result = "X360"; switch (id) { case OutContType.None: case OutContType.X360: result = "X360"; break; case OutContType.DS4: result = "DS4"; break; default: break; } return result; } private OutContType OutContDeviceId(string name) { OutContType id = OutContType.X360; switch (name) { case "None": case "X360": id = OutContType.X360; break; case "DS4": id = OutContType.DS4; break; default: break; } return id; } private void PortOldGyroSettings(int device) { if (gyroOutMode[device] == GyroOutMode.None) { gyroOutMode[device] = GyroOutMode.Controls; } } private string GetGyroOutModeString(GyroOutMode mode) { string result = "None"; switch(mode) { case GyroOutMode.Controls: result = "Controls"; break; case GyroOutMode.Mouse: result = "Mouse"; break; case GyroOutMode.MouseJoystick: result = "MouseJoystick"; break; default: break; } return result; } private GyroOutMode GetGyroOutModeType(string modeString) { GyroOutMode result = GyroOutMode.None; switch(modeString) { case "Controls": result = GyroOutMode.Controls; break; case "Mouse": result = GyroOutMode.Mouse; break; case "MouseJoystick": result = GyroOutMode.MouseJoystick; break; default: break; } return result; } private string GetLightbarModeString(LightbarMode mode) { string result = "DS4Win"; switch (mode) { case LightbarMode.DS4Win: result = "DS4Win"; break; case LightbarMode.Passthru: result = "Passthru"; break; default: break; } return result; } private LightbarMode GetLightbarModeType(string modeString) { LightbarMode result = LightbarMode.DS4Win; switch (modeString) { case "DS4Win": result = LightbarMode.DS4Win; break; case "Passthru": result = LightbarMode.Passthru; break; default: break; } return result; } public bool SaveAsNewProfile(int device, string proName) { bool Saved = true; ResetProfile(device); Saved = SaveProfile(device, proName); return Saved; } public bool SaveProfile(int device, string proName) { bool Saved = true; //string path = Global.appdatapath + @"\Profiles\" + Path.GetFileNameWithoutExtension(proName) + ".xml"; if (proName.EndsWith(Global.XML_EXTENSION)) { proName = proName.Remove(proName.LastIndexOf(Global.XML_EXTENSION)); } string path = $@"{Global.appdatapath}\Profiles\{proName}{Global.XML_EXTENSION}"; try { XmlNode tmpNode; XmlNode xmlControls = m_Xdoc.SelectSingleNode("/DS4Windows/Control"); XmlNode xmlShiftControls = m_Xdoc.SelectSingleNode("/DS4Windows/ShiftControl"); m_Xdoc.RemoveAll(); tmpNode = m_Xdoc.CreateXmlDeclaration("1.0", "utf-8", string.Empty); m_Xdoc.AppendChild(tmpNode); tmpNode = m_Xdoc.CreateComment(string.Format(" DS4Windows Configuration Data. {0} ", DateTime.Now)); m_Xdoc.AppendChild(tmpNode); tmpNode = m_Xdoc.CreateComment(string.Format(" Made with DS4Windows version {0} ", Global.exeversion)); m_Xdoc.AppendChild(tmpNode); tmpNode = m_Xdoc.CreateWhitespace("\r\n"); m_Xdoc.AppendChild(tmpNode); XmlElement rootElement = m_Xdoc.CreateElement("DS4Windows", null); rootElement.SetAttribute("app_version", Global.exeversion); rootElement.SetAttribute("config_version", Global.CONFIG_VERSION.ToString()); LightbarSettingInfo lightbarSettings = lightbarSettingInfo[device]; LightbarDS4WinInfo lightInfo = lightbarSettings.ds4winSettings; XmlNode xmlTouchToggle = m_Xdoc.CreateNode(XmlNodeType.Element, "touchToggle", null); xmlTouchToggle.InnerText = enableTouchToggle[device].ToString(); rootElement.AppendChild(xmlTouchToggle); XmlNode xmlIdleDisconnectTimeout = m_Xdoc.CreateNode(XmlNodeType.Element, "idleDisconnectTimeout", null); xmlIdleDisconnectTimeout.InnerText = idleDisconnectTimeout[device].ToString(); rootElement.AppendChild(xmlIdleDisconnectTimeout); XmlNode xmlOutputDataToDS4 = m_Xdoc.CreateNode(XmlNodeType.Element, "outputDataToDS4", null); xmlOutputDataToDS4.InnerText = enableOutputDataToDS4[device].ToString(); rootElement.AppendChild(xmlOutputDataToDS4); XmlNode xmlColor = m_Xdoc.CreateNode(XmlNodeType.Element, "Color", null); xmlColor.InnerText = lightInfo.m_Led.red.ToString() + "," + lightInfo.m_Led.green.ToString() + "," + lightInfo.m_Led.blue.ToString(); rootElement.AppendChild(xmlColor); XmlNode xmlRumbleBoost = m_Xdoc.CreateNode(XmlNodeType.Element, "RumbleBoost", null); xmlRumbleBoost.InnerText = rumble[device].ToString(); rootElement.AppendChild(xmlRumbleBoost); XmlNode xmlRumbleAutostopTime = m_Xdoc.CreateNode(XmlNodeType.Element, "RumbleAutostopTime", null); xmlRumbleAutostopTime.InnerText = rumbleAutostopTime[device].ToString(); rootElement.AppendChild(xmlRumbleAutostopTime); XmlNode xmlLightbarMode = m_Xdoc.CreateNode(XmlNodeType.Element, "LightbarMode", null); xmlLightbarMode.InnerText = GetLightbarModeString(lightbarSettings.mode); rootElement.AppendChild(xmlLightbarMode); XmlNode xmlLedAsBatteryIndicator = m_Xdoc.CreateNode(XmlNodeType.Element, "ledAsBatteryIndicator", null); xmlLedAsBatteryIndicator.InnerText = lightInfo.ledAsBattery.ToString(); rootElement.AppendChild(xmlLedAsBatteryIndicator); XmlNode xmlLowBatteryFlash = m_Xdoc.CreateNode(XmlNodeType.Element, "FlashType", null); xmlLowBatteryFlash.InnerText = lightInfo.flashType.ToString(); rootElement.AppendChild(xmlLowBatteryFlash); XmlNode xmlFlashBatterAt = m_Xdoc.CreateNode(XmlNodeType.Element, "flashBatteryAt", null); xmlFlashBatterAt.InnerText = lightInfo.flashAt.ToString(); rootElement.AppendChild(xmlFlashBatterAt); XmlNode xmlTouchSensitivity = m_Xdoc.CreateNode(XmlNodeType.Element, "touchSensitivity", null); xmlTouchSensitivity.InnerText = touchSensitivity[device].ToString(); rootElement.AppendChild(xmlTouchSensitivity); XmlNode xmlLowColor = m_Xdoc.CreateNode(XmlNodeType.Element, "LowColor", null); xmlLowColor.InnerText = lightInfo.m_LowLed.red.ToString() + "," + lightInfo.m_LowLed.green.ToString() + "," + lightInfo.m_LowLed.blue.ToString(); rootElement.AppendChild(xmlLowColor); XmlNode xmlChargingColor = m_Xdoc.CreateNode(XmlNodeType.Element, "ChargingColor", null); xmlChargingColor.InnerText = lightInfo.m_ChargingLed.red.ToString() + "," + lightInfo.m_ChargingLed.green.ToString() + "," + lightInfo.m_ChargingLed.blue.ToString(); rootElement.AppendChild(xmlChargingColor); XmlNode xmlFlashColor = m_Xdoc.CreateNode(XmlNodeType.Element, "FlashColor", null); xmlFlashColor.InnerText = lightInfo.m_FlashLed.red.ToString() + "," + lightInfo.m_FlashLed.green.ToString() + "," + lightInfo.m_FlashLed.blue.ToString(); rootElement.AppendChild(xmlFlashColor); XmlNode xmlTouchpadJitterCompensation = m_Xdoc.CreateNode(XmlNodeType.Element, "touchpadJitterCompensation", null); xmlTouchpadJitterCompensation.InnerText = touchpadJitterCompensation[device].ToString(); rootElement.AppendChild(xmlTouchpadJitterCompensation); XmlNode xmlLowerRCOn = m_Xdoc.CreateNode(XmlNodeType.Element, "lowerRCOn", null); xmlLowerRCOn.InnerText = lowerRCOn[device].ToString(); rootElement.AppendChild(xmlLowerRCOn); XmlNode xmlTapSensitivity = m_Xdoc.CreateNode(XmlNodeType.Element, "tapSensitivity", null); xmlTapSensitivity.InnerText = tapSensitivity[device].ToString(); rootElement.AppendChild(xmlTapSensitivity); XmlNode xmlDouble = m_Xdoc.CreateNode(XmlNodeType.Element, "doubleTap", null); xmlDouble.InnerText = doubleTap[device].ToString(); rootElement.AppendChild(xmlDouble); XmlNode xmlScrollSensitivity = m_Xdoc.CreateNode(XmlNodeType.Element, "scrollSensitivity", null); xmlScrollSensitivity.InnerText = scrollSensitivity[device].ToString(); rootElement.AppendChild(xmlScrollSensitivity); XmlNode xmlLeftTriggerMiddle = m_Xdoc.CreateNode(XmlNodeType.Element, "LeftTriggerMiddle", null); xmlLeftTriggerMiddle.InnerText = l2ModInfo[device].deadZone.ToString(); rootElement.AppendChild(xmlLeftTriggerMiddle); XmlNode xmlRightTriggerMiddle = m_Xdoc.CreateNode(XmlNodeType.Element, "RightTriggerMiddle", null); xmlRightTriggerMiddle.InnerText = r2ModInfo[device].deadZone.ToString(); rootElement.AppendChild(xmlRightTriggerMiddle); XmlNode xmlTouchpadInvert = m_Xdoc.CreateNode(XmlNodeType.Element, "TouchpadInvert", null); xmlTouchpadInvert.InnerText = touchpadInvert[device].ToString(); rootElement.AppendChild(xmlTouchpadInvert); XmlNode xmlL2AD = m_Xdoc.CreateNode(XmlNodeType.Element, "L2AntiDeadZone", null); xmlL2AD.InnerText = l2ModInfo[device].antiDeadZone.ToString(); rootElement.AppendChild(xmlL2AD); XmlNode xmlR2AD = m_Xdoc.CreateNode(XmlNodeType.Element, "R2AntiDeadZone", null); xmlR2AD.InnerText = r2ModInfo[device].antiDeadZone.ToString(); rootElement.AppendChild(xmlR2AD); XmlNode xmlL2Maxzone = m_Xdoc.CreateNode(XmlNodeType.Element, "L2MaxZone", null); xmlL2Maxzone.InnerText = l2ModInfo[device].maxZone.ToString(); rootElement.AppendChild(xmlL2Maxzone); XmlNode xmlR2Maxzone = m_Xdoc.CreateNode(XmlNodeType.Element, "R2MaxZone", null); xmlR2Maxzone.InnerText = r2ModInfo[device].maxZone.ToString(); rootElement.AppendChild(xmlR2Maxzone); XmlNode xmlL2MaxOutput = m_Xdoc.CreateNode(XmlNodeType.Element, "L2MaxOutput", null); xmlL2MaxOutput.InnerText = l2ModInfo[device].maxOutput.ToString(); rootElement.AppendChild(xmlL2MaxOutput); XmlNode xmlR2MaxOutput = m_Xdoc.CreateNode(XmlNodeType.Element, "R2MaxOutput", null); xmlR2MaxOutput.InnerText = r2ModInfo[device].maxOutput.ToString(); rootElement.AppendChild(xmlR2MaxOutput); XmlNode xmlButtonMouseSensitivity = m_Xdoc.CreateNode(XmlNodeType.Element, "ButtonMouseSensitivity", null); xmlButtonMouseSensitivity.InnerText = buttonMouseInfos[device].buttonSensitivity.ToString(); rootElement.AppendChild(xmlButtonMouseSensitivity); XmlNode xmlButtonMouseOffset = m_Xdoc.CreateNode(XmlNodeType.Element, "ButtonMouseOffset", null); xmlButtonMouseOffset.InnerText = buttonMouseInfos[device].mouseVelocityOffset.ToString(); rootElement.AppendChild(xmlButtonMouseOffset); XmlNode xmlRainbow = m_Xdoc.CreateNode(XmlNodeType.Element, "Rainbow", null); xmlRainbow.InnerText = lightInfo.rainbow.ToString(); rootElement.AppendChild(xmlRainbow); XmlNode xmlMaxSatRainbow = m_Xdoc.CreateNode(XmlNodeType.Element, "MaxSatRainbow", null); xmlMaxSatRainbow.InnerText = Convert.ToInt32(lightInfo.maxRainbowSat * 100.0).ToString(); rootElement.AppendChild(xmlMaxSatRainbow); XmlNode xmlLSD = m_Xdoc.CreateNode(XmlNodeType.Element, "LSDeadZone", null); xmlLSD.InnerText = lsModInfo[device].deadZone.ToString(); rootElement.AppendChild(xmlLSD); XmlNode xmlRSD = m_Xdoc.CreateNode(XmlNodeType.Element, "RSDeadZone", null); xmlRSD.InnerText = rsModInfo[device].deadZone.ToString(); rootElement.AppendChild(xmlRSD); XmlNode xmlLSAD = m_Xdoc.CreateNode(XmlNodeType.Element, "LSAntiDeadZone", null); xmlLSAD.InnerText = lsModInfo[device].antiDeadZone.ToString(); rootElement.AppendChild(xmlLSAD); XmlNode xmlRSAD = m_Xdoc.CreateNode(XmlNodeType.Element, "RSAntiDeadZone", null); xmlRSAD.InnerText = rsModInfo[device].antiDeadZone.ToString(); rootElement.AppendChild(xmlRSAD); XmlNode xmlLSMaxZone = m_Xdoc.CreateNode(XmlNodeType.Element, "LSMaxZone", null); xmlLSMaxZone.InnerText = lsModInfo[device].maxZone.ToString(); rootElement.AppendChild(xmlLSMaxZone); XmlNode xmlRSMaxZone = m_Xdoc.CreateNode(XmlNodeType.Element, "RSMaxZone", null); xmlRSMaxZone.InnerText = rsModInfo[device].maxZone.ToString(); rootElement.AppendChild(xmlRSMaxZone); XmlNode xmlLSMaxOutput = m_Xdoc.CreateNode(XmlNodeType.Element, "LSMaxOutput", null); xmlLSMaxOutput.InnerText = lsModInfo[device].maxOutput.ToString(); rootElement.AppendChild(xmlLSMaxOutput); XmlNode xmlRSMaxOutput = m_Xdoc.CreateNode(XmlNodeType.Element, "RSMaxOutput", null); xmlRSMaxOutput.InnerText = rsModInfo[device].maxOutput.ToString(); rootElement.AppendChild(xmlRSMaxOutput); XmlNode xmlLSRotation = m_Xdoc.CreateNode(XmlNodeType.Element, "LSRotation", null); xmlLSRotation.InnerText = Convert.ToInt32(LSRotation[device] * 180.0 / Math.PI).ToString(); rootElement.AppendChild(xmlLSRotation); XmlNode xmlRSRotation = m_Xdoc.CreateNode(XmlNodeType.Element, "RSRotation", null); xmlRSRotation.InnerText = Convert.ToInt32(RSRotation[device] * 180.0 / Math.PI).ToString(); rootElement.AppendChild(xmlRSRotation); XmlNode xmlLSFuzz = m_Xdoc.CreateNode(XmlNodeType.Element, "LSFuzz", null); xmlLSFuzz.InnerText = lsModInfo[device].fuzz.ToString(); rootElement.AppendChild(xmlLSFuzz); XmlNode xmlRSFuzz = m_Xdoc.CreateNode(XmlNodeType.Element, "RSFuzz", null); xmlRSFuzz.InnerText = rsModInfo[device].fuzz.ToString(); rootElement.AppendChild(xmlRSFuzz); XmlNode xmlSXD = m_Xdoc.CreateNode(XmlNodeType.Element, "SXDeadZone", null); xmlSXD.InnerText = SXDeadzone[device].ToString(); rootElement.AppendChild(xmlSXD); XmlNode xmlSZD = m_Xdoc.CreateNode(XmlNodeType.Element, "SZDeadZone", null); xmlSZD.InnerText = SZDeadzone[device].ToString(); rootElement.AppendChild(xmlSZD); XmlNode xmlSXMaxzone = m_Xdoc.CreateNode(XmlNodeType.Element, "SXMaxZone", null); xmlSXMaxzone.InnerText = Convert.ToInt32(SXMaxzone[device] * 100.0).ToString(); rootElement.AppendChild(xmlSXMaxzone); XmlNode xmlSZMaxzone = m_Xdoc.CreateNode(XmlNodeType.Element, "SZMaxZone", null); xmlSZMaxzone.InnerText = Convert.ToInt32(SZMaxzone[device] * 100.0).ToString(); rootElement.AppendChild(xmlSZMaxzone); XmlNode xmlSXAntiDeadzone = m_Xdoc.CreateNode(XmlNodeType.Element, "SXAntiDeadZone", null); xmlSXAntiDeadzone.InnerText = Convert.ToInt32(SXAntiDeadzone[device] * 100.0).ToString(); rootElement.AppendChild(xmlSXAntiDeadzone); XmlNode xmlSZAntiDeadzone = m_Xdoc.CreateNode(XmlNodeType.Element, "SZAntiDeadZone", null); xmlSZAntiDeadzone.InnerText = Convert.ToInt32(SZAntiDeadzone[device] * 100.0).ToString(); rootElement.AppendChild(xmlSZAntiDeadzone); XmlNode xmlSens = m_Xdoc.CreateNode(XmlNodeType.Element, "Sensitivity", null); xmlSens.InnerText = $"{LSSens[device]}|{RSSens[device]}|{l2Sens[device]}|{r2Sens[device]}|{SXSens[device]}|{SZSens[device]}"; rootElement.AppendChild(xmlSens); XmlNode xmlChargingType = m_Xdoc.CreateNode(XmlNodeType.Element, "ChargingType", null); xmlChargingType.InnerText = lightInfo.chargingType.ToString(); rootElement.AppendChild(xmlChargingType); XmlNode xmlMouseAccel = m_Xdoc.CreateNode(XmlNodeType.Element, "MouseAcceleration", null); xmlMouseAccel.InnerText = buttonMouseInfos[device].mouseAccel.ToString(); rootElement.AppendChild(xmlMouseAccel); XmlNode xmlMouseVerticalScale = m_Xdoc.CreateNode(XmlNodeType.Element, "ButtonMouseVerticalScale", null); xmlMouseVerticalScale.InnerText = Convert.ToInt32(buttonMouseInfos[device].buttonVerticalScale * 100).ToString(); rootElement.AppendChild(xmlMouseVerticalScale); //XmlNode xmlShiftMod = m_Xdoc.CreateNode(XmlNodeType.Element, "ShiftModifier", null); xmlShiftMod.InnerText = shiftModifier[device].ToString(); rootElement.AppendChild(xmlShiftMod); XmlNode xmlLaunchProgram = m_Xdoc.CreateNode(XmlNodeType.Element, "LaunchProgram", null); xmlLaunchProgram.InnerText = launchProgram[device].ToString(); rootElement.AppendChild(xmlLaunchProgram); XmlNode xmlDinput = m_Xdoc.CreateNode(XmlNodeType.Element, "DinputOnly", null); xmlDinput.InnerText = dinputOnly[device].ToString(); rootElement.AppendChild(xmlDinput); XmlNode xmlStartTouchpadOff = m_Xdoc.CreateNode(XmlNodeType.Element, "StartTouchpadOff", null); xmlStartTouchpadOff.InnerText = startTouchpadOff[device].ToString(); rootElement.AppendChild(xmlStartTouchpadOff); XmlNode xmlTouchOutMode = m_Xdoc.CreateNode(XmlNodeType.Element, "TouchpadOutputMode", null); xmlTouchOutMode.InnerText = touchOutMode[device].ToString(); rootElement.AppendChild(xmlTouchOutMode); XmlNode xmlSATriggers = m_Xdoc.CreateNode(XmlNodeType.Element, "SATriggers", null); xmlSATriggers.InnerText = sATriggers[device].ToString(); rootElement.AppendChild(xmlSATriggers); XmlNode xmlSATriggerCond = m_Xdoc.CreateNode(XmlNodeType.Element, "SATriggerCond", null); xmlSATriggerCond.InnerText = SaTriggerCondString(sATriggerCond[device]); rootElement.AppendChild(xmlSATriggerCond); XmlNode xmlSASteeringWheelEmulationAxis = m_Xdoc.CreateNode(XmlNodeType.Element, "SASteeringWheelEmulationAxis", null); xmlSASteeringWheelEmulationAxis.InnerText = sASteeringWheelEmulationAxis[device].ToString("G"); rootElement.AppendChild(xmlSASteeringWheelEmulationAxis); XmlNode xmlSASteeringWheelEmulationRange = m_Xdoc.CreateNode(XmlNodeType.Element, "SASteeringWheelEmulationRange", null); xmlSASteeringWheelEmulationRange.InnerText = sASteeringWheelEmulationRange[device].ToString(); rootElement.AppendChild(xmlSASteeringWheelEmulationRange); XmlNode xmlSASteeringWheelFuzz = m_Xdoc.CreateNode(XmlNodeType.Element, "SASteeringWheelFuzz", null); xmlSASteeringWheelFuzz.InnerText = saWheelFuzzValues[device].ToString(); rootElement.AppendChild(xmlSASteeringWheelFuzz); XmlElement xmlSASteeringWheelSmoothingGroupEl = m_Xdoc.CreateElement("SASteeringWheelSmoothingOptions"); XmlElement xmlSASteeringWheelUseSmoothing = m_Xdoc.CreateElement("SASteeringWheelUseSmoothing"); xmlSASteeringWheelUseSmoothing.InnerText = wheelSmoothInfo[device].Enabled.ToString(); xmlSASteeringWheelSmoothingGroupEl.AppendChild(xmlSASteeringWheelUseSmoothing); XmlElement xmlSASteeringWheelSmoothMinCutoff = m_Xdoc.CreateElement("SASteeringWheelSmoothMinCutoff"); xmlSASteeringWheelSmoothMinCutoff.InnerText = wheelSmoothInfo[device].MinCutoff.ToString(); xmlSASteeringWheelSmoothingGroupEl.AppendChild(xmlSASteeringWheelSmoothMinCutoff); XmlElement xmlSASteeringWheelSmoothBeta = m_Xdoc.CreateElement("SASteeringWheelSmoothBeta"); xmlSASteeringWheelSmoothBeta.InnerText = wheelSmoothInfo[device].Beta.ToString(); xmlSASteeringWheelSmoothingGroupEl.AppendChild(xmlSASteeringWheelSmoothBeta); rootElement.AppendChild(xmlSASteeringWheelSmoothingGroupEl); //XmlNode xmlSASteeringWheelUseSmoothing = m_Xdoc.CreateNode(XmlNodeType.Element, "SASteeringWheelUseSmoothing", null); xmlSASteeringWheelUseSmoothing.InnerText = wheelSmoothInfo[device].Enabled.ToString(); rootElement.AppendChild(xmlSASteeringWheelUseSmoothing); //XmlNode xmlSASteeringWheelSmoothMinCutoff = m_Xdoc.CreateNode(XmlNodeType.Element, "SASteeringWheelSmoothMinCutoff", null); xmlSASteeringWheelSmoothMinCutoff.InnerText = wheelSmoothInfo[device].MinCutoff.ToString(); rootElement.AppendChild(xmlSASteeringWheelSmoothMinCutoff); //XmlNode xmlSASteeringWheelSmoothBeta = m_Xdoc.CreateNode(XmlNodeType.Element, "SASteeringWheelSmoothBeta", null); xmlSASteeringWheelSmoothBeta.InnerText = wheelSmoothInfo[device].Beta.ToString(); rootElement.AppendChild(xmlSASteeringWheelSmoothBeta); XmlNode xmlTouchDisInvTriggers = m_Xdoc.CreateNode(XmlNodeType.Element, "TouchDisInvTriggers", null); string tempTouchDisInv = string.Join(",", touchDisInvertTriggers[device]); xmlTouchDisInvTriggers.InnerText = tempTouchDisInv; rootElement.AppendChild(xmlTouchDisInvTriggers); XmlNode xmlGyroSensitivity = m_Xdoc.CreateNode(XmlNodeType.Element, "GyroSensitivity", null); xmlGyroSensitivity.InnerText = gyroSensitivity[device].ToString(); rootElement.AppendChild(xmlGyroSensitivity); XmlNode xmlGyroSensVerticalScale = m_Xdoc.CreateNode(XmlNodeType.Element, "GyroSensVerticalScale", null); xmlGyroSensVerticalScale.InnerText = gyroSensVerticalScale[device].ToString(); rootElement.AppendChild(xmlGyroSensVerticalScale); XmlNode xmlGyroInvert = m_Xdoc.CreateNode(XmlNodeType.Element, "GyroInvert", null); xmlGyroInvert.InnerText = gyroInvert[device].ToString(); rootElement.AppendChild(xmlGyroInvert); XmlNode xmlGyroTriggerTurns = m_Xdoc.CreateNode(XmlNodeType.Element, "GyroTriggerTurns", null); xmlGyroTriggerTurns.InnerText = gyroTriggerTurns[device].ToString(); rootElement.AppendChild(xmlGyroTriggerTurns); /*XmlNode xmlGyroSmoothWeight = m_Xdoc.CreateNode(XmlNodeType.Element, "GyroSmoothingWeight", null); xmlGyroSmoothWeight.InnerText = Convert.ToInt32(gyroSmoothWeight[device] * 100).ToString(); rootElement.AppendChild(xmlGyroSmoothWeight); XmlNode xmlGyroSmoothing = m_Xdoc.CreateNode(XmlNodeType.Element, "GyroSmoothing", null); xmlGyroSmoothing.InnerText = gyroSmoothing[device].ToString(); rootElement.AppendChild(xmlGyroSmoothing); */ XmlElement xmlGyroSmoothingElement = m_Xdoc.CreateElement("GyroMouseSmoothingSettings"); XmlNode xmlGyroSmoothing = m_Xdoc.CreateNode(XmlNodeType.Element, "UseSmoothing", null); xmlGyroSmoothing.InnerText = gyroMouseInfo[device].enableSmoothing.ToString(); xmlGyroSmoothingElement.AppendChild(xmlGyroSmoothing); XmlNode xmlGyroSmoothingMethod = m_Xdoc.CreateNode(XmlNodeType.Element, "SmoothingMethod", null); xmlGyroSmoothingMethod.InnerText = gyroMouseInfo[device].SmoothMethodIdentifier(); xmlGyroSmoothingElement.AppendChild(xmlGyroSmoothingMethod); XmlNode xmlGyroSmoothWeight = m_Xdoc.CreateNode(XmlNodeType.Element, "SmoothingWeight", null); xmlGyroSmoothWeight.InnerText = Convert.ToInt32(gyroMouseInfo[device].smoothingWeight * 100).ToString(); xmlGyroSmoothingElement.AppendChild(xmlGyroSmoothWeight); XmlNode xmlGyroSmoothMincutoff = m_Xdoc.CreateNode(XmlNodeType.Element, "SmoothingMinCutoff", null); xmlGyroSmoothMincutoff.InnerText = gyroMouseInfo[device].minCutoff.ToString(); xmlGyroSmoothingElement.AppendChild(xmlGyroSmoothMincutoff); XmlNode xmlGyroSmoothBeta = m_Xdoc.CreateNode(XmlNodeType.Element, "SmoothingBeta", null); xmlGyroSmoothBeta.InnerText = gyroMouseInfo[device].beta.ToString(); xmlGyroSmoothingElement.AppendChild(xmlGyroSmoothBeta); rootElement.AppendChild(xmlGyroSmoothingElement); XmlNode xmlGyroMouseHAxis = m_Xdoc.CreateNode(XmlNodeType.Element, "GyroMouseHAxis", null); xmlGyroMouseHAxis.InnerText = gyroMouseHorizontalAxis[device].ToString(); rootElement.AppendChild(xmlGyroMouseHAxis); XmlNode xmlGyroMouseDZ = m_Xdoc.CreateNode(XmlNodeType.Element, "GyroMouseDeadZone", null); xmlGyroMouseDZ.InnerText = gyroMouseDZ[device].ToString(); rootElement.AppendChild(xmlGyroMouseDZ); XmlNode xmlGyroMinThreshold = m_Xdoc.CreateNode(XmlNodeType.Element, "GyroMouseMinThreshold", null); xmlGyroMinThreshold.InnerText = gyroMouseInfo[device].minThreshold.ToString(); rootElement.AppendChild(xmlGyroMinThreshold); XmlNode xmlGyroMouseToggle = m_Xdoc.CreateNode(XmlNodeType.Element, "GyroMouseToggle", null); xmlGyroMouseToggle.InnerText = gyroMouseToggle[device].ToString(); rootElement.AppendChild(xmlGyroMouseToggle); XmlNode xmlGyroOutMode = m_Xdoc.CreateNode(XmlNodeType.Element, "GyroOutputMode", null); xmlGyroOutMode.InnerText = GetGyroOutModeString(gyroOutMode[device]); rootElement.AppendChild(xmlGyroOutMode); XmlNode xmlGyroMStickTriggers = m_Xdoc.CreateNode(XmlNodeType.Element, "GyroMouseStickTriggers", null); xmlGyroMStickTriggers.InnerText = sAMouseStickTriggers[device].ToString(); rootElement.AppendChild(xmlGyroMStickTriggers); XmlNode xmlGyroMStickTriggerCond = m_Xdoc.CreateNode(XmlNodeType.Element, "GyroMouseStickTriggerCond", null); xmlGyroMStickTriggerCond.InnerText = SaTriggerCondString(sAMouseStickTriggerCond[device]); rootElement.AppendChild(xmlGyroMStickTriggerCond); XmlNode xmlGyroMStickTriggerTurns = m_Xdoc.CreateNode(XmlNodeType.Element, "GyroMouseStickTriggerTurns", null); xmlGyroMStickTriggerTurns.InnerText = gyroMouseStickTriggerTurns[device].ToString(); rootElement.AppendChild(xmlGyroMStickTriggerTurns); XmlNode xmlGyroMStickHAxis = m_Xdoc.CreateNode(XmlNodeType.Element, "GyroMouseStickHAxis", null); xmlGyroMStickHAxis.InnerText = gyroMouseStickHorizontalAxis[device].ToString(); rootElement.AppendChild(xmlGyroMStickHAxis); XmlNode xmlGyroMStickDZ = m_Xdoc.CreateNode(XmlNodeType.Element, "GyroMouseStickDeadZone", null); xmlGyroMStickDZ.InnerText = gyroMStickInfo[device].deadZone.ToString(); rootElement.AppendChild(xmlGyroMStickDZ); XmlNode xmlGyroMStickMaxZ = m_Xdoc.CreateNode(XmlNodeType.Element, "GyroMouseStickMaxZone", null); xmlGyroMStickMaxZ.InnerText = gyroMStickInfo[device].maxZone.ToString(); rootElement.AppendChild(xmlGyroMStickMaxZ); XmlNode xmlGyroMStickAntiDX = m_Xdoc.CreateNode(XmlNodeType.Element, "GyroMouseStickAntiDeadX", null); xmlGyroMStickAntiDX.InnerText = gyroMStickInfo[device].antiDeadX.ToString(); rootElement.AppendChild(xmlGyroMStickAntiDX); XmlNode xmlGyroMStickAntiDY = m_Xdoc.CreateNode(XmlNodeType.Element, "GyroMouseStickAntiDeadY", null); xmlGyroMStickAntiDY.InnerText = gyroMStickInfo[device].antiDeadY.ToString(); rootElement.AppendChild(xmlGyroMStickAntiDY); XmlNode xmlGyroMStickInvert = m_Xdoc.CreateNode(XmlNodeType.Element, "GyroMouseStickInvert", null); xmlGyroMStickInvert.InnerText = gyroMStickInfo[device].inverted.ToString(); rootElement.AppendChild(xmlGyroMStickInvert); XmlNode xmlGyroMStickToggle = m_Xdoc.CreateNode(XmlNodeType.Element, "GyroMouseStickToggle", null); xmlGyroMStickToggle.InnerText = gyroMouseStickToggle[device].ToString(); rootElement.AppendChild(xmlGyroMStickToggle); XmlNode xmlGyroMStickMaxOutput = m_Xdoc.CreateNode(XmlNodeType.Element, "GyroMouseStickMaxOutput", null); xmlGyroMStickMaxOutput.InnerText = gyroMStickInfo[device].maxOutput.ToString(); rootElement.AppendChild(xmlGyroMStickMaxOutput); XmlNode xmlGyroMStickMaxOutputEnabled = m_Xdoc.CreateNode(XmlNodeType.Element, "GyroMouseStickMaxOutputEnabled", null); xmlGyroMStickMaxOutputEnabled.InnerText = gyroMStickInfo[device].maxOutputEnabled.ToString(); rootElement.AppendChild(xmlGyroMStickMaxOutputEnabled); XmlNode xmlGyroMStickVerticalScale = m_Xdoc.CreateNode(XmlNodeType.Element, "GyroMouseStickVerticalScale", null); xmlGyroMStickVerticalScale.InnerText = gyroMStickInfo[device].vertScale.ToString(); rootElement.AppendChild(xmlGyroMStickVerticalScale); /*XmlNode xmlGyroMStickSmoothing = m_Xdoc.CreateNode(XmlNodeType.Element, "GyroMouseStickSmoothing", null); xmlGyroMStickSmoothing.InnerText = gyroMStickInfo[device].useSmoothing.ToString(); rootElement.AppendChild(xmlGyroMStickSmoothing); XmlNode xmlGyroMStickSmoothWeight = m_Xdoc.CreateNode(XmlNodeType.Element, "GyroMouseStickSmoothingWeight", null); xmlGyroMStickSmoothWeight.InnerText = Convert.ToInt32(gyroMStickInfo[device].smoothWeight * 100).ToString(); rootElement.AppendChild(xmlGyroMStickSmoothWeight); */ XmlElement xmlGyroMStickSmoothingElement = m_Xdoc.CreateElement("GyroMouseStickSmoothingSettings"); XmlNode xmlGyroMStickSmoothing = m_Xdoc.CreateNode(XmlNodeType.Element, "UseSmoothing", null); xmlGyroMStickSmoothing.InnerText = gyroMStickInfo[device].useSmoothing.ToString(); xmlGyroMStickSmoothingElement.AppendChild(xmlGyroMStickSmoothing); XmlNode xmlGyroMStickSmoothingMethod = m_Xdoc.CreateNode(XmlNodeType.Element, "SmoothingMethod", null); xmlGyroMStickSmoothingMethod.InnerText = gyroMStickInfo[device].SmoothMethodIdentifier(); xmlGyroMStickSmoothingElement.AppendChild(xmlGyroMStickSmoothingMethod); XmlNode xmlGyroMStickSmoothWeight = m_Xdoc.CreateNode(XmlNodeType.Element, "SmoothingWeight", null); xmlGyroMStickSmoothWeight.InnerText = Convert.ToInt32(gyroMStickInfo[device].smoothWeight * 100).ToString(); xmlGyroMStickSmoothingElement.AppendChild(xmlGyroMStickSmoothWeight); XmlNode xmlGyroMStickSmoothMincutoff = m_Xdoc.CreateNode(XmlNodeType.Element, "SmoothingMinCutoff", null); xmlGyroMStickSmoothMincutoff.InnerText = gyroMStickInfo[device].minCutoff.ToString(); xmlGyroMStickSmoothingElement.AppendChild(xmlGyroMStickSmoothMincutoff); XmlNode xmlGyroMStickSmoothBeta = m_Xdoc.CreateNode(XmlNodeType.Element, "SmoothingBeta", null); xmlGyroMStickSmoothBeta.InnerText = gyroMStickInfo[device].beta.ToString(); xmlGyroMStickSmoothingElement.AppendChild(xmlGyroMStickSmoothBeta); rootElement.AppendChild(xmlGyroMStickSmoothingElement); XmlNode xmlLSC = m_Xdoc.CreateNode(XmlNodeType.Element, "LSCurve", null); xmlLSC.InnerText = lsCurve[device].ToString(); rootElement.AppendChild(xmlLSC); XmlNode xmlRSC = m_Xdoc.CreateNode(XmlNodeType.Element, "RSCurve", null); xmlRSC.InnerText = rsCurve[device].ToString(); rootElement.AppendChild(xmlRSC); XmlNode xmlProfileActions = m_Xdoc.CreateNode(XmlNodeType.Element, "ProfileActions", null); xmlProfileActions.InnerText = string.Join("/", profileActions[device]); rootElement.AppendChild(xmlProfileActions); XmlNode xmlBTPollRate = m_Xdoc.CreateNode(XmlNodeType.Element, "BTPollRate", null); xmlBTPollRate.InnerText = btPollRate[device].ToString(); rootElement.AppendChild(xmlBTPollRate); XmlNode xmlLsOutputCurveMode = m_Xdoc.CreateNode(XmlNodeType.Element, "LSOutputCurveMode", null); xmlLsOutputCurveMode.InnerText = stickOutputCurveString(getLsOutCurveMode(device)); rootElement.AppendChild(xmlLsOutputCurveMode); XmlNode xmlLsOutputCurveCustom = m_Xdoc.CreateNode(XmlNodeType.Element, "LSOutputCurveCustom", null); xmlLsOutputCurveCustom.InnerText = lsOutBezierCurveObj[device].ToString(); rootElement.AppendChild(xmlLsOutputCurveCustom); XmlNode xmlRsOutputCurveMode = m_Xdoc.CreateNode(XmlNodeType.Element, "RSOutputCurveMode", null); xmlRsOutputCurveMode.InnerText = stickOutputCurveString(getRsOutCurveMode(device)); rootElement.AppendChild(xmlRsOutputCurveMode); XmlNode xmlRsOutputCurveCustom = m_Xdoc.CreateNode(XmlNodeType.Element, "RSOutputCurveCustom", null); xmlRsOutputCurveCustom.InnerText = rsOutBezierCurveObj[device].ToString(); rootElement.AppendChild(xmlRsOutputCurveCustom); XmlNode xmlLsSquareStickMode = m_Xdoc.CreateNode(XmlNodeType.Element, "LSSquareStick", null); xmlLsSquareStickMode.InnerText = squStickInfo[device].lsMode.ToString(); rootElement.AppendChild(xmlLsSquareStickMode); XmlNode xmlRsSquareStickMode = m_Xdoc.CreateNode(XmlNodeType.Element, "RSSquareStick", null); xmlRsSquareStickMode.InnerText = squStickInfo[device].rsMode.ToString(); rootElement.AppendChild(xmlRsSquareStickMode); XmlNode xmlSquareStickRoundness = m_Xdoc.CreateNode(XmlNodeType.Element, "SquareStickRoundness", null); xmlSquareStickRoundness.InnerText = squStickInfo[device].lsRoundness.ToString(); rootElement.AppendChild(xmlSquareStickRoundness); XmlNode xmlSquareRStickRoundness = m_Xdoc.CreateNode(XmlNodeType.Element, "SquareRStickRoundness", null); xmlSquareRStickRoundness.InnerText = squStickInfo[device].rsRoundness.ToString(); rootElement.AppendChild(xmlSquareRStickRoundness); XmlNode xmlLsOutputMode = m_Xdoc.CreateNode(XmlNodeType.Element, "LSOutputMode", null); xmlLsOutputMode.InnerText = lsOutputSettings[device].mode.ToString(); rootElement.AppendChild(xmlLsOutputMode); XmlNode xmlRsOutputMode = m_Xdoc.CreateNode(XmlNodeType.Element, "RSOutputMode", null); xmlRsOutputMode.InnerText = rsOutputSettings[device].mode.ToString(); rootElement.AppendChild(xmlRsOutputMode); XmlElement xmlLsOutputSettingsElement = m_Xdoc.CreateElement("LSOutputSettings"); XmlElement xmlLsFlickStickGroupElement = m_Xdoc.CreateElement("FlickStickSettings"); xmlLsOutputSettingsElement.AppendChild(xmlLsFlickStickGroupElement); XmlNode xmlLsFlickStickRWC = m_Xdoc.CreateNode(XmlNodeType.Element, "RealWorldCalibration", null); xmlLsFlickStickRWC.InnerText = lsOutputSettings[device].outputSettings.flickSettings.realWorldCalibration.ToString(); xmlLsFlickStickGroupElement.AppendChild(xmlLsFlickStickRWC); XmlNode xmlLsFlickStickThreshold = m_Xdoc.CreateNode(XmlNodeType.Element, "FlickThreshold", null); xmlLsFlickStickThreshold.InnerText = lsOutputSettings[device].outputSettings.flickSettings.flickThreshold.ToString(); xmlLsFlickStickGroupElement.AppendChild(xmlLsFlickStickThreshold); XmlNode xmlLsFlickStickTime = m_Xdoc.CreateNode(XmlNodeType.Element, "FlickTime", null); xmlLsFlickStickTime.InnerText = lsOutputSettings[device].outputSettings.flickSettings.flickTime.ToString(); xmlLsFlickStickGroupElement.AppendChild(xmlLsFlickStickTime); rootElement.AppendChild(xmlLsOutputSettingsElement); XmlElement xmlRsOutputSettingsElement = m_Xdoc.CreateElement("RSOutputSettings"); XmlElement xmlRsFlickStickGroupElement = m_Xdoc.CreateElement("FlickStickSettings"); xmlRsOutputSettingsElement.AppendChild(xmlRsFlickStickGroupElement); XmlNode xmlRsFlickStickRWC = m_Xdoc.CreateNode(XmlNodeType.Element, "RealWorldCalibration", null); xmlRsFlickStickRWC.InnerText = rsOutputSettings[device].outputSettings.flickSettings.realWorldCalibration.ToString(); xmlRsFlickStickGroupElement.AppendChild(xmlRsFlickStickRWC); XmlNode xmlRsFlickStickThreshold = m_Xdoc.CreateNode(XmlNodeType.Element, "FlickThreshold", null); xmlRsFlickStickThreshold.InnerText = rsOutputSettings[device].outputSettings.flickSettings.flickThreshold.ToString(); xmlRsFlickStickGroupElement.AppendChild(xmlRsFlickStickThreshold); XmlNode xmlRsFlickStickTime = m_Xdoc.CreateNode(XmlNodeType.Element, "FlickTime", null); xmlRsFlickStickTime.InnerText = rsOutputSettings[device].outputSettings.flickSettings.flickTime.ToString(); xmlRsFlickStickGroupElement.AppendChild(xmlRsFlickStickTime); rootElement.AppendChild(xmlRsOutputSettingsElement); XmlNode xmlL2OutputCurveMode = m_Xdoc.CreateNode(XmlNodeType.Element, "L2OutputCurveMode", null); xmlL2OutputCurveMode.InnerText = axisOutputCurveString(getL2OutCurveMode(device)); rootElement.AppendChild(xmlL2OutputCurveMode); XmlNode xmlL2OutputCurveCustom = m_Xdoc.CreateNode(XmlNodeType.Element, "L2OutputCurveCustom", null); xmlL2OutputCurveCustom.InnerText = l2OutBezierCurveObj[device].ToString(); rootElement.AppendChild(xmlL2OutputCurveCustom); XmlNode xmlR2OutputCurveMode = m_Xdoc.CreateNode(XmlNodeType.Element, "R2OutputCurveMode", null); xmlR2OutputCurveMode.InnerText = axisOutputCurveString(getR2OutCurveMode(device)); rootElement.AppendChild(xmlR2OutputCurveMode); XmlNode xmlR2OutputCurveCustom = m_Xdoc.CreateNode(XmlNodeType.Element, "R2OutputCurveCustom", null); xmlR2OutputCurveCustom.InnerText = r2OutBezierCurveObj[device].ToString(); rootElement.AppendChild(xmlR2OutputCurveCustom); XmlNode xmlSXOutputCurveMode = m_Xdoc.CreateNode(XmlNodeType.Element, "SXOutputCurveMode", null); xmlSXOutputCurveMode.InnerText = axisOutputCurveString(getSXOutCurveMode(device)); rootElement.AppendChild(xmlSXOutputCurveMode); XmlNode xmlSXOutputCurveCustom = m_Xdoc.CreateNode(XmlNodeType.Element, "SXOutputCurveCustom", null); xmlSXOutputCurveCustom.InnerText = sxOutBezierCurveObj[device].ToString(); rootElement.AppendChild(xmlSXOutputCurveCustom); XmlNode xmlSZOutputCurveMode = m_Xdoc.CreateNode(XmlNodeType.Element, "SZOutputCurveMode", null); xmlSZOutputCurveMode.InnerText = axisOutputCurveString(getSZOutCurveMode(device)); rootElement.AppendChild(xmlSZOutputCurveMode); XmlNode xmlSZOutputCurveCustom = m_Xdoc.CreateNode(XmlNodeType.Element, "SZOutputCurveCustom", null); xmlSZOutputCurveCustom.InnerText = szOutBezierCurveObj[device].ToString(); rootElement.AppendChild(xmlSZOutputCurveCustom); XmlNode xmlTrackBallMode = m_Xdoc.CreateNode(XmlNodeType.Element, "TrackballMode", null); xmlTrackBallMode.InnerText = trackballMode[device].ToString(); rootElement.AppendChild(xmlTrackBallMode); XmlNode xmlTrackBallFriction = m_Xdoc.CreateNode(XmlNodeType.Element, "TrackballFriction", null); xmlTrackBallFriction.InnerText = trackballFriction[device].ToString(); rootElement.AppendChild(xmlTrackBallFriction); XmlNode xmlTouchRelMouseRotation = m_Xdoc.CreateNode(XmlNodeType.Element, "TouchRelMouseRotation", null); xmlTouchRelMouseRotation.InnerText = Convert.ToInt32(touchpadRelMouse[device].rotation * 180.0 / Math.PI).ToString(); rootElement.AppendChild(xmlTouchRelMouseRotation); XmlNode xmlTouchRelMouseMinThreshold = m_Xdoc.CreateNode(XmlNodeType.Element, "TouchRelMouseMinThreshold", null); xmlTouchRelMouseMinThreshold.InnerText = touchpadRelMouse[device].minThreshold.ToString(); rootElement.AppendChild(xmlTouchRelMouseMinThreshold); XmlElement xmlTouchAbsMouseGroupEl = m_Xdoc.CreateElement("TouchpadAbsMouseSettings"); XmlElement xmlTouchAbsMouseMaxZoneX = m_Xdoc.CreateElement("MaxZoneX"); xmlTouchAbsMouseMaxZoneX.InnerText = touchpadAbsMouse[device].maxZoneX.ToString(); xmlTouchAbsMouseGroupEl.AppendChild(xmlTouchAbsMouseMaxZoneX); XmlElement xmlTouchAbsMouseMaxZoneY = m_Xdoc.CreateElement("MaxZoneY"); xmlTouchAbsMouseMaxZoneY.InnerText = touchpadAbsMouse[device].maxZoneY.ToString(); xmlTouchAbsMouseGroupEl.AppendChild(xmlTouchAbsMouseMaxZoneY); XmlElement xmlTouchAbsMouseSnapCenter = m_Xdoc.CreateElement("SnapToCenter"); xmlTouchAbsMouseSnapCenter.InnerText = touchpadAbsMouse[device].snapToCenter.ToString(); xmlTouchAbsMouseGroupEl.AppendChild(xmlTouchAbsMouseSnapCenter); rootElement.AppendChild(xmlTouchAbsMouseGroupEl); XmlNode xmlOutContDevice = m_Xdoc.CreateNode(XmlNodeType.Element, "OutputContDevice", null); xmlOutContDevice.InnerText = OutContDeviceString(outputDevType[device]); rootElement.AppendChild(xmlOutContDevice); XmlNode NodeControl = m_Xdoc.CreateNode(XmlNodeType.Element, "Control", null); XmlNode Key = m_Xdoc.CreateNode(XmlNodeType.Element, "Key", null); XmlNode Macro = m_Xdoc.CreateNode(XmlNodeType.Element, "Macro", null); XmlNode KeyType = m_Xdoc.CreateNode(XmlNodeType.Element, "KeyType", null); XmlNode Button = m_Xdoc.CreateNode(XmlNodeType.Element, "Button", null); XmlNode Extras = m_Xdoc.CreateNode(XmlNodeType.Element, "Extras", null); XmlNode NodeShiftControl = m_Xdoc.CreateNode(XmlNodeType.Element, "ShiftControl", null); XmlNode ShiftKey = m_Xdoc.CreateNode(XmlNodeType.Element, "Key", null); XmlNode ShiftMacro = m_Xdoc.CreateNode(XmlNodeType.Element, "Macro", null); XmlNode ShiftKeyType = m_Xdoc.CreateNode(XmlNodeType.Element, "KeyType", null); XmlNode ShiftButton = m_Xdoc.CreateNode(XmlNodeType.Element, "Button", null); XmlNode ShiftExtras = m_Xdoc.CreateNode(XmlNodeType.Element, "Extras", null); foreach (DS4ControlSettings dcs in ds4settings[device]) { if (dcs.action != null) { XmlNode buttonNode; string keyType = string.Empty; if (dcs.action is string) { if (dcs.action.ToString() == "Unbound") keyType += DS4KeyType.Unbound; } if (dcs.keyType.HasFlag(DS4KeyType.HoldMacro)) keyType += DS4KeyType.HoldMacro; else if (dcs.keyType.HasFlag(DS4KeyType.Macro)) keyType += DS4KeyType.Macro; if (dcs.keyType.HasFlag(DS4KeyType.Toggle)) keyType += DS4KeyType.Toggle; if (dcs.keyType.HasFlag(DS4KeyType.ScanCode)) keyType += DS4KeyType.ScanCode; if (keyType != string.Empty) { buttonNode = m_Xdoc.CreateNode(XmlNodeType.Element, dcs.control.ToString(), null); buttonNode.InnerText = keyType; KeyType.AppendChild(buttonNode); } buttonNode = m_Xdoc.CreateNode(XmlNodeType.Element, dcs.control.ToString(), null); if (dcs.action is IEnumerable<int> || dcs.action is int[] || dcs.action is ushort[]) { int[] ii = (int[])dcs.action; buttonNode.InnerText = string.Join("/", ii); Macro.AppendChild(buttonNode); } else if (dcs.action is int || dcs.action is ushort || dcs.action is byte) { buttonNode.InnerText = dcs.action.ToString(); Key.AppendChild(buttonNode); } else if (dcs.action is string) { buttonNode.InnerText = dcs.action.ToString(); Button.AppendChild(buttonNode); } else if (dcs.action is X360Controls) { buttonNode.InnerText = getX360ControlString((X360Controls)dcs.action); Button.AppendChild(buttonNode); } } bool hasvalue = false; if (!string.IsNullOrEmpty(dcs.extras)) { foreach (string s in dcs.extras.Split(',')) { if (s != "0") { hasvalue = true; break; } } } if (hasvalue) { XmlNode extraNode = m_Xdoc.CreateNode(XmlNodeType.Element, dcs.control.ToString(), null); extraNode.InnerText = dcs.extras; Extras.AppendChild(extraNode); } if (dcs.shiftAction != null && dcs.shiftTrigger > 0) { XmlElement buttonNode; string keyType = string.Empty; if (dcs.shiftAction is string) { if (dcs.shiftAction.ToString() == "Unbound") keyType += DS4KeyType.Unbound; } if (dcs.shiftKeyType.HasFlag(DS4KeyType.HoldMacro)) keyType += DS4KeyType.HoldMacro; if (dcs.shiftKeyType.HasFlag(DS4KeyType.Macro)) keyType += DS4KeyType.Macro; if (dcs.shiftKeyType.HasFlag(DS4KeyType.Toggle)) keyType += DS4KeyType.Toggle; if (dcs.shiftKeyType.HasFlag(DS4KeyType.ScanCode)) keyType += DS4KeyType.ScanCode; if (keyType != string.Empty) { buttonNode = m_Xdoc.CreateElement(dcs.control.ToString()); buttonNode.InnerText = keyType; ShiftKeyType.AppendChild(buttonNode); } buttonNode = m_Xdoc.CreateElement(dcs.control.ToString()); buttonNode.SetAttribute("Trigger", dcs.shiftTrigger.ToString()); if (dcs.shiftAction is IEnumerable<int> || dcs.shiftAction is int[] || dcs.shiftAction is ushort[]) { int[] ii = (int[])dcs.shiftAction; buttonNode.InnerText = string.Join("/", ii); ShiftMacro.AppendChild(buttonNode); } else if (dcs.shiftAction is int || dcs.shiftAction is ushort || dcs.shiftAction is byte) { buttonNode.InnerText = dcs.shiftAction.ToString(); ShiftKey.AppendChild(buttonNode); } else if (dcs.shiftAction is string || dcs.shiftAction is X360Controls) { buttonNode.InnerText = dcs.shiftAction.ToString(); ShiftButton.AppendChild(buttonNode); } } hasvalue = false; if (!string.IsNullOrEmpty(dcs.shiftExtras)) { foreach (string s in dcs.shiftExtras.Split(',')) { if (s != "0") { hasvalue = true; break; } } } if (hasvalue) { XmlNode extraNode = m_Xdoc.CreateNode(XmlNodeType.Element, dcs.control.ToString(), null); extraNode.InnerText = dcs.shiftExtras; ShiftExtras.AppendChild(extraNode); } } rootElement.AppendChild(NodeControl); if (Button.HasChildNodes) NodeControl.AppendChild(Button); if (Macro.HasChildNodes) NodeControl.AppendChild(Macro); if (Key.HasChildNodes) NodeControl.AppendChild(Key); if (Extras.HasChildNodes) NodeControl.AppendChild(Extras); if (KeyType.HasChildNodes) NodeControl.AppendChild(KeyType); if (NodeControl.HasChildNodes) rootElement.AppendChild(NodeControl); rootElement.AppendChild(NodeShiftControl); if (ShiftButton.HasChildNodes) NodeShiftControl.AppendChild(ShiftButton); if (ShiftMacro.HasChildNodes) NodeShiftControl.AppendChild(ShiftMacro); if (ShiftKey.HasChildNodes) NodeShiftControl.AppendChild(ShiftKey); if (ShiftKeyType.HasChildNodes) NodeShiftControl.AppendChild(ShiftKeyType); if (ShiftExtras.HasChildNodes) NodeShiftControl.AppendChild(ShiftExtras); m_Xdoc.AppendChild(rootElement); m_Xdoc.Save(path); } catch { Saved = false; } return Saved; } public DS4Controls getDS4ControlsByName(string key) { if (!key.StartsWith("bn")) return (DS4Controls)Enum.Parse(typeof(DS4Controls), key, true); switch (key) { case "bnShare": return DS4Controls.Share; case "bnL3": return DS4Controls.L3; case "bnR3": return DS4Controls.R3; case "bnOptions": return DS4Controls.Options; case "bnUp": return DS4Controls.DpadUp; case "bnRight": return DS4Controls.DpadRight; case "bnDown": return DS4Controls.DpadDown; case "bnLeft": return DS4Controls.DpadLeft; case "bnL1": return DS4Controls.L1; case "bnR1": return DS4Controls.R1; case "bnTriangle": return DS4Controls.Triangle; case "bnCircle": return DS4Controls.Circle; case "bnCross": return DS4Controls.Cross; case "bnSquare": return DS4Controls.Square; case "bnPS": return DS4Controls.PS; case "bnLSLeft": return DS4Controls.LXNeg; case "bnLSUp": return DS4Controls.LYNeg; case "bnRSLeft": return DS4Controls.RXNeg; case "bnRSUp": return DS4Controls.RYNeg; case "bnLSRight": return DS4Controls.LXPos; case "bnLSDown": return DS4Controls.LYPos; case "bnRSRight": return DS4Controls.RXPos; case "bnRSDown": return DS4Controls.RYPos; case "bnL2": return DS4Controls.L2; case "bnR2": return DS4Controls.R2; case "bnTouchLeft": return DS4Controls.TouchLeft; case "bnTouchMulti": return DS4Controls.TouchMulti; case "bnTouchUpper": return DS4Controls.TouchUpper; case "bnTouchRight": return DS4Controls.TouchRight; case "bnGyroXP": return DS4Controls.GyroXPos; case "bnGyroXN": return DS4Controls.GyroXNeg; case "bnGyroZP": return DS4Controls.GyroZPos; case "bnGyroZN": return DS4Controls.GyroZNeg; case "bnSwipeUp": return DS4Controls.SwipeUp; case "bnSwipeDown": return DS4Controls.SwipeDown; case "bnSwipeLeft": return DS4Controls.SwipeLeft; case "bnSwipeRight": return DS4Controls.SwipeRight; #region OldShiftname case "sbnShare": return DS4Controls.Share; case "sbnL3": return DS4Controls.L3; case "sbnR3": return DS4Controls.R3; case "sbnOptions": return DS4Controls.Options; case "sbnUp": return DS4Controls.DpadUp; case "sbnRight": return DS4Controls.DpadRight; case "sbnDown": return DS4Controls.DpadDown; case "sbnLeft": return DS4Controls.DpadLeft; case "sbnL1": return DS4Controls.L1; case "sbnR1": return DS4Controls.R1; case "sbnTriangle": return DS4Controls.Triangle; case "sbnCircle": return DS4Controls.Circle; case "sbnCross": return DS4Controls.Cross; case "sbnSquare": return DS4Controls.Square; case "sbnPS": return DS4Controls.PS; case "sbnLSLeft": return DS4Controls.LXNeg; case "sbnLSUp": return DS4Controls.LYNeg; case "sbnRSLeft": return DS4Controls.RXNeg; case "sbnRSUp": return DS4Controls.RYNeg; case "sbnLSRight": return DS4Controls.LXPos; case "sbnLSDown": return DS4Controls.LYPos; case "sbnRSRight": return DS4Controls.RXPos; case "sbnRSDown": return DS4Controls.RYPos; case "sbnL2": return DS4Controls.L2; case "sbnR2": return DS4Controls.R2; case "sbnTouchLeft": return DS4Controls.TouchLeft; case "sbnTouchMulti": return DS4Controls.TouchMulti; case "sbnTouchUpper": return DS4Controls.TouchUpper; case "sbnTouchRight": return DS4Controls.TouchRight; case "sbnGsyroXP": return DS4Controls.GyroXPos; case "sbnGyroXN": return DS4Controls.GyroXNeg; case "sbnGyroZP": return DS4Controls.GyroZPos; case "sbnGyroZN": return DS4Controls.GyroZNeg; #endregion case "bnShiftShare": return DS4Controls.Share; case "bnShiftL3": return DS4Controls.L3; case "bnShiftR3": return DS4Controls.R3; case "bnShiftOptions": return DS4Controls.Options; case "bnShiftUp": return DS4Controls.DpadUp; case "bnShiftRight": return DS4Controls.DpadRight; case "bnShiftDown": return DS4Controls.DpadDown; case "bnShiftLeft": return DS4Controls.DpadLeft; case "bnShiftL1": return DS4Controls.L1; case "bnShiftR1": return DS4Controls.R1; case "bnShiftTriangle": return DS4Controls.Triangle; case "bnShiftCircle": return DS4Controls.Circle; case "bnShiftCross": return DS4Controls.Cross; case "bnShiftSquare": return DS4Controls.Square; case "bnShiftPS": return DS4Controls.PS; case "bnShiftLSLeft": return DS4Controls.LXNeg; case "bnShiftLSUp": return DS4Controls.LYNeg; case "bnShiftRSLeft": return DS4Controls.RXNeg; case "bnShiftRSUp": return DS4Controls.RYNeg; case "bnShiftLSRight": return DS4Controls.LXPos; case "bnShiftLSDown": return DS4Controls.LYPos; case "bnShiftRSRight": return DS4Controls.RXPos; case "bnShiftRSDown": return DS4Controls.RYPos; case "bnShiftL2": return DS4Controls.L2; case "bnShiftR2": return DS4Controls.R2; case "bnShiftTouchLeft": return DS4Controls.TouchLeft; case "bnShiftTouchMulti": return DS4Controls.TouchMulti; case "bnShiftTouchUpper": return DS4Controls.TouchUpper; case "bnShiftTouchRight": return DS4Controls.TouchRight; case "bnShiftGyroXP": return DS4Controls.GyroXPos; case "bnShiftGyroXN": return DS4Controls.GyroXNeg; case "bnShiftGyroZP": return DS4Controls.GyroZPos; case "bnShiftGyroZN": return DS4Controls.GyroZNeg; case "bnShiftSwipeUp": return DS4Controls.SwipeUp; case "bnShiftSwipeDown": return DS4Controls.SwipeDown; case "bnShiftSwipeLeft": return DS4Controls.SwipeLeft; case "bnShiftSwipeRight": return DS4Controls.SwipeRight; } return 0; } public X360Controls getX360ControlsByName(string key) { X360Controls x3c; if (Enum.TryParse(key, true, out x3c)) return x3c; switch (key) { case "Back": return X360Controls.Back; case "Left Stick": return X360Controls.LS; case "Right Stick": return X360Controls.RS; case "Start": return X360Controls.Start; case "Up Button": return X360Controls.DpadUp; case "Right Button": return X360Controls.DpadRight; case "Down Button": return X360Controls.DpadDown; case "Left Button": return X360Controls.DpadLeft; case "Left Bumper": return X360Controls.LB; case "Right Bumper": return X360Controls.RB; case "Y Button": return X360Controls.Y; case "B Button": return X360Controls.B; case "A Button": return X360Controls.A; case "X Button": return X360Controls.X; case "Guide": return X360Controls.Guide; case "Left X-Axis-": return X360Controls.LXNeg; case "Left Y-Axis-": return X360Controls.LYNeg; case "Right X-Axis-": return X360Controls.RXNeg; case "Right Y-Axis-": return X360Controls.RYNeg; case "Left X-Axis+": return X360Controls.LXPos; case "Left Y-Axis+": return X360Controls.LYPos; case "Right X-Axis+": return X360Controls.RXPos; case "Right Y-Axis+": return X360Controls.RYPos; case "Left Trigger": return X360Controls.LT; case "Right Trigger": return X360Controls.RT; case "Touchpad Click": return X360Controls.TouchpadClick; case "Left Mouse Button": return X360Controls.LeftMouse; case "Right Mouse Button": return X360Controls.RightMouse; case "Middle Mouse Button": return X360Controls.MiddleMouse; case "4th Mouse Button": return X360Controls.FourthMouse; case "5th Mouse Button": return X360Controls.FifthMouse; case "Mouse Wheel Up": return X360Controls.WUP; case "Mouse Wheel Down": return X360Controls.WDOWN; case "Mouse Up": return X360Controls.MouseUp; case "Mouse Down": return X360Controls.MouseDown; case "Mouse Left": return X360Controls.MouseLeft; case "Mouse Right": return X360Controls.MouseRight; case "Unbound": return X360Controls.Unbound; } return X360Controls.Unbound; } public string getX360ControlString(X360Controls key) { switch (key) { case X360Controls.Back: return "Back"; case X360Controls.LS: return "Left Stick"; case X360Controls.RS: return "Right Stick"; case X360Controls.Start: return "Start"; case X360Controls.DpadUp: return "Up Button"; case X360Controls.DpadRight: return "Right Button"; case X360Controls.DpadDown: return "Down Button"; case X360Controls.DpadLeft: return "Left Button"; case X360Controls.LB: return "Left Bumper"; case X360Controls.RB: return "Right Bumper"; case X360Controls.Y: return "Y Button"; case X360Controls.B: return "B Button"; case X360Controls.A: return "A Button"; case X360Controls.X: return "X Button"; case X360Controls.Guide: return "Guide"; case X360Controls.LXNeg: return "Left X-Axis-"; case X360Controls.LYNeg: return "Left Y-Axis-"; case X360Controls.RXNeg: return "Right X-Axis-"; case X360Controls.RYNeg: return "Right Y-Axis-"; case X360Controls.LXPos: return "Left X-Axis+"; case X360Controls.LYPos: return "Left Y-Axis+"; case X360Controls.RXPos: return "Right X-Axis+"; case X360Controls.RYPos: return "Right Y-Axis+"; case X360Controls.LT: return "Left Trigger"; case X360Controls.RT: return "Right Trigger"; case X360Controls.TouchpadClick: return "Touchpad Click"; case X360Controls.LeftMouse: return "Left Mouse Button"; case X360Controls.RightMouse: return "Right Mouse Button"; case X360Controls.MiddleMouse: return "Middle Mouse Button"; case X360Controls.FourthMouse: return "4th Mouse Button"; case X360Controls.FifthMouse: return "5th Mouse Button"; case X360Controls.WUP: return "Mouse Wheel Up"; case X360Controls.WDOWN: return "Mouse Wheel Down"; case X360Controls.MouseUp: return "Mouse Up"; case X360Controls.MouseDown: return "Mouse Down"; case X360Controls.MouseLeft: return "Mouse Left"; case X360Controls.MouseRight: return "Mouse Right"; case X360Controls.Unbound: return "Unbound"; } return "Unbound"; } public bool LoadProfile(int device, bool launchprogram, ControlService control, string propath = "", bool xinputChange = true, bool postLoad = true) { bool Loaded = true; Dictionary<DS4Controls, DS4KeyType> customMapKeyTypes = new Dictionary<DS4Controls, DS4KeyType>(); Dictionary<DS4Controls, UInt16> customMapKeys = new Dictionary<DS4Controls, UInt16>(); Dictionary<DS4Controls, X360Controls> customMapButtons = new Dictionary<DS4Controls, X360Controls>(); Dictionary<DS4Controls, String> customMapMacros = new Dictionary<DS4Controls, String>(); Dictionary<DS4Controls, String> customMapExtras = new Dictionary<DS4Controls, String>(); Dictionary<DS4Controls, DS4KeyType> shiftCustomMapKeyTypes = new Dictionary<DS4Controls, DS4KeyType>(); Dictionary<DS4Controls, UInt16> shiftCustomMapKeys = new Dictionary<DS4Controls, UInt16>(); Dictionary<DS4Controls, X360Controls> shiftCustomMapButtons = new Dictionary<DS4Controls, X360Controls>(); Dictionary<DS4Controls, String> shiftCustomMapMacros = new Dictionary<DS4Controls, String>(); Dictionary<DS4Controls, String> shiftCustomMapExtras = new Dictionary<DS4Controls, String>(); string rootname = "DS4Windows"; bool missingSetting = false; bool migratePerformed = false; string profilepath; if (propath == "") profilepath = Global.appdatapath + @"\Profiles\" + profilePath[device] + ".xml"; else profilepath = propath; bool xinputPlug = false; bool xinputStatus = false; if (File.Exists(profilepath)) { XmlNode Item; ProfileMigration tmpMigration = new ProfileMigration(profilepath); if (tmpMigration.RequiresMigration()) { tmpMigration.Migrate(); m_Xdoc.Load(tmpMigration.ProfileReader); migratePerformed = true; } else { m_Xdoc.Load(tmpMigration.ProfileReader); //m_Xdoc.Load(profilepath); } if (m_Xdoc.SelectSingleNode(rootname) == null) { rootname = "ScpControl"; missingSetting = true; } if (device < Global.MAX_DS4_CONTROLLER_COUNT) { DS4LightBar.forcelight[device] = false; DS4LightBar.forcedFlash[device] = 0; } OutContType oldContType = Global.activeOutDevType[device]; LightbarSettingInfo lightbarSettings = lightbarSettingInfo[device]; LightbarDS4WinInfo lightInfo = lightbarSettings.ds4winSettings; // Make sure to reset currently set profile values before parsing ResetProfile(device); try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/touchToggle"); Boolean.TryParse(Item.InnerText, out enableTouchToggle[device]); } catch { missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/idleDisconnectTimeout"); Int32.TryParse(Item.InnerText, out idleDisconnectTimeout[device]); } catch { missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/outputDataToDS4"); Boolean.TryParse(Item.InnerText, out enableOutputDataToDS4[device]); } catch { missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/LightbarMode"); string tempMode = Item.InnerText; lightbarSettings.mode = GetLightbarModeType(tempMode); } catch { lightbarSettings.mode = LightbarMode.DS4Win; missingSetting = true; } //New method for saving color try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/Color"); string[] colors; if (!string.IsNullOrEmpty(Item.InnerText)) colors = Item.InnerText.Split(','); else colors = new string[0]; lightInfo.m_Led.red = byte.Parse(colors[0]); lightInfo.m_Led.green = byte.Parse(colors[1]); lightInfo.m_Led.blue = byte.Parse(colors[2]); } catch { missingSetting = true; } if (m_Xdoc.SelectSingleNode("/" + rootname + "/Color") == null) { //Old method of color saving try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/Red"); Byte.TryParse(Item.InnerText, out lightInfo.m_Led.red); } catch { missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/Green"); Byte.TryParse(Item.InnerText, out lightInfo.m_Led.green); } catch { missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/Blue"); Byte.TryParse(Item.InnerText, out lightInfo.m_Led.blue); } catch { missingSetting = true; } } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/RumbleBoost"); Byte.TryParse(Item.InnerText, out rumble[device]); } catch { missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/RumbleAutostopTime"); Int32.TryParse(Item.InnerText, out rumbleAutostopTime[device]); } catch { missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/ledAsBatteryIndicator"); Boolean.TryParse(Item.InnerText, out lightInfo.ledAsBattery); } catch { missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/FlashType"); Byte.TryParse(Item.InnerText, out lightInfo.flashType); } catch { missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/flashBatteryAt"); Int32.TryParse(Item.InnerText, out lightInfo.flashAt); } catch { missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/touchSensitivity"); Byte.TryParse(Item.InnerText, out touchSensitivity[device]); } catch { missingSetting = true; } //New method for saving color try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/LowColor"); string[] colors; if (!string.IsNullOrEmpty(Item.InnerText)) colors = Item.InnerText.Split(','); else colors = new string[0]; lightInfo.m_LowLed.red = byte.Parse(colors[0]); lightInfo.m_LowLed.green = byte.Parse(colors[1]); lightInfo.m_LowLed.blue = byte.Parse(colors[2]); } catch { missingSetting = true; } if (m_Xdoc.SelectSingleNode("/" + rootname + "/LowColor") == null) { //Old method of color saving try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/LowRed"); byte.TryParse(Item.InnerText, out lightInfo.m_LowLed.red); } catch { missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/LowGreen"); byte.TryParse(Item.InnerText, out lightInfo.m_LowLed.green); } catch { missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/LowBlue"); byte.TryParse(Item.InnerText, out lightInfo.m_LowLed.blue); } catch { missingSetting = true; } } //New method for saving color try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/ChargingColor"); string[] colors; if (!string.IsNullOrEmpty(Item.InnerText)) colors = Item.InnerText.Split(','); else colors = new string[0]; lightInfo.m_ChargingLed.red = byte.Parse(colors[0]); lightInfo.m_ChargingLed.green = byte.Parse(colors[1]); lightInfo.m_ChargingLed.blue = byte.Parse(colors[2]); } catch { missingSetting = true; } if (m_Xdoc.SelectSingleNode("/" + rootname + "/ChargingColor") == null) { try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/ChargingRed"); Byte.TryParse(Item.InnerText, out lightInfo.m_ChargingLed.red); } catch { missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/ChargingGreen"); Byte.TryParse(Item.InnerText, out lightInfo.m_ChargingLed.green); } catch { missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/ChargingBlue"); Byte.TryParse(Item.InnerText, out lightInfo.m_ChargingLed.blue); } catch { missingSetting = true; } } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/FlashColor"); string[] colors; if (!string.IsNullOrEmpty(Item.InnerText)) colors = Item.InnerText.Split(','); else colors = new string[0]; lightInfo.m_FlashLed.red = byte.Parse(colors[0]); lightInfo.m_FlashLed.green = byte.Parse(colors[1]); lightInfo.m_FlashLed.blue = byte.Parse(colors[2]); } catch { missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/touchpadJitterCompensation"); bool.TryParse(Item.InnerText, out touchpadJitterCompensation[device]); } catch { missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/lowerRCOn"); bool.TryParse(Item.InnerText, out lowerRCOn[device]); } catch { missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/tapSensitivity"); byte.TryParse(Item.InnerText, out tapSensitivity[device]); } catch { missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/doubleTap"); bool.TryParse(Item.InnerText, out doubleTap[device]); } catch { missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/scrollSensitivity"); int.TryParse(Item.InnerText, out scrollSensitivity[device]); } catch { missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/TouchpadInvert"); int temp = 0; int.TryParse(Item.InnerText, out temp); touchpadInvert[device] = Math.Min(Math.Max(temp, 0), 3); } catch { touchpadInvert[device] = 0; missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/LeftTriggerMiddle"); byte.TryParse(Item.InnerText, out l2ModInfo[device].deadZone); } catch { missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/RightTriggerMiddle"); byte.TryParse(Item.InnerText, out r2ModInfo[device].deadZone); } catch { missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/L2AntiDeadZone"); int.TryParse(Item.InnerText, out l2ModInfo[device].antiDeadZone); } catch { l2ModInfo[device].antiDeadZone = 0; missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/R2AntiDeadZone"); int.TryParse(Item.InnerText, out r2ModInfo[device].antiDeadZone); } catch { r2ModInfo[device].antiDeadZone = 0; missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/L2MaxZone"); int temp = 100; int.TryParse(Item.InnerText, out temp); l2ModInfo[device].maxZone = Math.Min(Math.Max(temp, 0), 100); } catch { l2ModInfo[device].maxZone = 100; missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/R2MaxZone"); int temp = 100; int.TryParse(Item.InnerText, out temp); r2ModInfo[device].maxZone = Math.Min(Math.Max(temp, 0), 100); } catch { r2ModInfo[device].maxZone = 100; missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/L2MaxOutput"); double temp = 100.0; temp = double.Parse(Item.InnerText); l2ModInfo[device].maxOutput = Math.Min(Math.Max(temp, 0.0), 100.0); } catch { l2ModInfo[device].maxOutput = 100.0; missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/R2MaxOutput"); double temp = 100.0; temp = double.Parse(Item.InnerText); r2ModInfo[device].maxOutput = Math.Min(Math.Max(temp, 0.0), 100.0); } catch { r2ModInfo[device].maxOutput = 100.0; missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/LSRotation"); int temp = 0; int.TryParse(Item.InnerText, out temp); temp = Math.Min(Math.Max(temp, -180), 180); LSRotation[device] = temp * Math.PI / 180.0; } catch { LSRotation[device] = 0.0; missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/RSRotation"); int temp = 0; int.TryParse(Item.InnerText, out temp); temp = Math.Min(Math.Max(temp, -180), 180); RSRotation[device] = temp * Math.PI / 180.0; } catch { RSRotation[device] = 0.0; missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/LSFuzz"); int temp = 0; int.TryParse(Item.InnerText, out temp); temp = Math.Min(Math.Max(temp, 0), 100); lsModInfo[device].fuzz = temp; } catch { lsModInfo[device].fuzz = StickDeadZoneInfo.DEFAULT_FUZZ; missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/RSFuzz"); int temp = 0; int.TryParse(Item.InnerText, out temp); temp = Math.Min(Math.Max(temp, 0), 100); rsModInfo[device].fuzz = temp; } catch { rsModInfo[device].fuzz = StickDeadZoneInfo.DEFAULT_FUZZ; missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/ButtonMouseSensitivity"); int.TryParse(Item.InnerText, out buttonMouseInfos[device].buttonSensitivity); } catch { missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/ButtonMouseOffset"); double.TryParse(Item.InnerText, out buttonMouseInfos[device].mouseVelocityOffset); } catch { missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/ButtonMouseVerticalScale"); int.TryParse(Item.InnerText, out int temp); buttonMouseInfos[device].buttonVerticalScale = Math.Min(Math.Max(temp, 0), 500) * 0.01; } catch { missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/Rainbow"); double.TryParse(Item.InnerText, out lightInfo.rainbow); } catch { lightInfo.rainbow = 0; missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/MaxSatRainbow"); int.TryParse(Item.InnerText, out int temp); lightInfo.maxRainbowSat = Math.Max(0, Math.Min(100, temp)) / 100.0; } catch { lightInfo.maxRainbowSat = 1.0; missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/LSDeadZone"); int.TryParse(Item.InnerText, out int temp); temp = Math.Min(Math.Max(temp, 0), 127); lsModInfo[device].deadZone = temp; } catch { lsModInfo[device].deadZone = 10; missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/RSDeadZone"); int.TryParse(Item.InnerText, out int temp); temp = Math.Min(Math.Max(temp, 0), 127); rsModInfo[device].deadZone = temp; } catch { rsModInfo[device].deadZone = 10; missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/LSAntiDeadZone"); int.TryParse(Item.InnerText, out lsModInfo[device].antiDeadZone); } catch { lsModInfo[device].antiDeadZone = 25; missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/RSAntiDeadZone"); int.TryParse(Item.InnerText, out rsModInfo[device].antiDeadZone); } catch { rsModInfo[device].antiDeadZone = 25; missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/LSMaxZone"); int temp = 100; int.TryParse(Item.InnerText, out temp); lsModInfo[device].maxZone = Math.Min(Math.Max(temp, 0), 100); } catch { lsModInfo[device].maxZone = 100; missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/RSMaxZone"); int temp = 100; int.TryParse(Item.InnerText, out temp); rsModInfo[device].maxZone = Math.Min(Math.Max(temp, 0), 100); } catch { rsModInfo[device].maxZone = 100; missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/LSMaxOutput"); double temp = 100.0; temp = double.Parse(Item.InnerText); lsModInfo[device].maxOutput = Math.Min(Math.Max(temp, 0.0), 100.0); } catch { lsModInfo[device].maxOutput = 100.0; missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/RSMaxOutput"); double temp = 100.0; temp = double.Parse(Item.InnerText); rsModInfo[device].maxOutput = Math.Min(Math.Max(temp, 0.0), 100.0); } catch { rsModInfo[device].maxOutput = 100; missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/SXDeadZone"); double.TryParse(Item.InnerText, out SXDeadzone[device]); } catch { SXDeadzone[device] = 0.02; missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/SZDeadZone"); double.TryParse(Item.InnerText, out SZDeadzone[device]); } catch { SZDeadzone[device] = 0.02; missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/SXMaxZone"); int temp = 0; int.TryParse(Item.InnerText, out temp); SXMaxzone[device] = Math.Min(Math.Max(temp * 0.01, 0.0), 1.0); } catch { SXMaxzone[device] = 1.0; missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/SZMaxZone"); int temp = 0; int.TryParse(Item.InnerText, out temp); SZMaxzone[device] = Math.Min(Math.Max(temp * 0.01, 0.0), 1.0); } catch { SZMaxzone[device] = 1.0; missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/SXAntiDeadZone"); int temp = 0; int.TryParse(Item.InnerText, out temp); SXAntiDeadzone[device] = Math.Min(Math.Max(temp * 0.01, 0.0), 1.0); } catch { SXAntiDeadzone[device] = 0.0; missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/SZAntiDeadZone"); int temp = 0; int.TryParse(Item.InnerText, out temp); SZAntiDeadzone[device] = Math.Min(Math.Max(temp * 0.01, 0.0), 1.0); } catch { SZAntiDeadzone[device] = 0.0; missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/Sensitivity"); string[] s = Item.InnerText.Split('|'); if (s.Length == 1) s = Item.InnerText.Split(','); if (!double.TryParse(s[0], out LSSens[device]) || LSSens[device] < .5f) LSSens[device] = 1; if (!double.TryParse(s[1], out RSSens[device]) || RSSens[device] < .5f) RSSens[device] = 1; if (!double.TryParse(s[2], out l2Sens[device]) || l2Sens[device] < .1f) l2Sens[device] = 1; if (!double.TryParse(s[3], out r2Sens[device]) || r2Sens[device] < .1f) r2Sens[device] = 1; if (!double.TryParse(s[4], out SXSens[device]) || SXSens[device] < .5f) SXSens[device] = 1; if (!double.TryParse(s[5], out SZSens[device]) || SZSens[device] < .5f) SZSens[device] = 1; } catch { missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/ChargingType"); int.TryParse(Item.InnerText, out lightInfo.chargingType); } catch { missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/MouseAcceleration"); bool.TryParse(Item.InnerText, out buttonMouseInfos[device].mouseAccel); } catch { missingSetting = true; } int shiftM = 0; if (m_Xdoc.SelectSingleNode("/" + rootname + "/ShiftModifier") != null) int.TryParse(m_Xdoc.SelectSingleNode("/" + rootname + "/ShiftModifier").InnerText, out shiftM); try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/LaunchProgram"); launchProgram[device] = Item.InnerText; } catch { launchProgram[device] = string.Empty; missingSetting = true; } if (launchprogram == true && launchProgram[device] != string.Empty) { string programPath = launchProgram[device]; System.Diagnostics.Process[] localAll = System.Diagnostics.Process.GetProcesses(); bool procFound = false; for (int procInd = 0, procsLen = localAll.Length; !procFound && procInd < procsLen; procInd++) { try { string temp = localAll[procInd].MainModule.FileName; if (temp == programPath) { procFound = true; } } // Ignore any process for which this information // is not exposed catch { } } if (!procFound) { Task processTask = new Task(() => { Thread.Sleep(5000); System.Diagnostics.Process tempProcess = new System.Diagnostics.Process(); tempProcess.StartInfo.FileName = programPath; tempProcess.StartInfo.WorkingDirectory = new FileInfo(programPath).Directory.ToString(); //tempProcess.StartInfo.UseShellExecute = false; try { tempProcess.Start(); } catch { } }); processTask.Start(); } } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/DinputOnly"); bool.TryParse(Item.InnerText, out dinputOnly[device]); } catch { dinputOnly[device] = false; missingSetting = true; } bool oldUseDInputOnly = Global.useDInputOnly[device]; try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/StartTouchpadOff"); bool.TryParse(Item.InnerText, out startTouchpadOff[device]); if (startTouchpadOff[device] == true) control.StartTPOff(device); } catch { startTouchpadOff[device] = false; missingSetting = true; } // Fallback lookup if TouchpadOutMode is not set bool tpForControlsPresent = false; XmlNode xmlUseTPForControlsElement = m_Xdoc.SelectSingleNode("/" + rootname + "/UseTPforControls"); tpForControlsPresent = xmlUseTPForControlsElement != null; try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/UseTPforControls"); bool.TryParse(Item.InnerText, out bool temp); if (temp) touchOutMode[device] = TouchpadOutMode.Controls; } catch { touchOutMode[device] = TouchpadOutMode.Mouse; missingSetting = true; } // Fallback lookup if GyroOutMode is not set try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/UseSAforMouse"); bool.TryParse(Item.InnerText, out bool temp); if (temp) gyroOutMode[device] = GyroOutMode.Mouse; } catch { gyroOutMode[device] = GyroOutMode.Controls; missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/SATriggers"); sATriggers[device] = Item.InnerText; } catch { sATriggers[device] = "-1"; missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/SATriggerCond"); sATriggerCond[device] = SaTriggerCondValue(Item.InnerText); } catch { sATriggerCond[device] = true; missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/SASteeringWheelEmulationAxis"); SASteeringWheelEmulationAxisType.TryParse(Item.InnerText, out sASteeringWheelEmulationAxis[device]); } catch { sASteeringWheelEmulationAxis[device] = SASteeringWheelEmulationAxisType.None; missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/SASteeringWheelEmulationRange"); int.TryParse(Item.InnerText, out sASteeringWheelEmulationRange[device]); } catch { sASteeringWheelEmulationRange[device] = 360; missingSetting = true; } bool sASteeringWheelSmoothingGroup = false; XmlNode xmlSASteeringWheelSmoothElement = m_Xdoc.SelectSingleNode("/" + rootname + "/SASteeringWheelSmoothingOptions"); sASteeringWheelSmoothingGroup = xmlSASteeringWheelSmoothElement != null; if (sASteeringWheelSmoothingGroup) { try { Item = xmlSASteeringWheelSmoothElement.SelectSingleNode("SASteeringWheelUseSmoothing"); //Item = m_Xdoc.SelectSingleNode("/" + rootname + "/SASteeringWheelUseSmoothing"); bool.TryParse(Item.InnerText, out bool temp); wheelSmoothInfo[device].Enabled = temp; } catch { wheelSmoothInfo[device].Reset(); missingSetting = true; } try { Item = xmlSASteeringWheelSmoothElement.SelectSingleNode("SASteeringWheelSmoothMinCutoff"); //Item = m_Xdoc.SelectSingleNode("/" + rootname + "/SASteeringWheelSmoothMinCutoff"); double.TryParse(Item.InnerText, out double temp); wheelSmoothInfo[device].MinCutoff = temp; } catch { wheelSmoothInfo[device].MinCutoff = OneEuroFilterPair.DEFAULT_WHEEL_CUTOFF; missingSetting = true; } try { Item = xmlSASteeringWheelSmoothElement.SelectSingleNode("SASteeringWheelSmoothBeta"); //Item = m_Xdoc.SelectSingleNode("/" + rootname + "/SASteeringWheelSmoothBeta"); double.TryParse(Item.InnerText, out double temp); wheelSmoothInfo[device].Beta = temp; } catch { wheelSmoothInfo[device].Beta = OneEuroFilterPair.DEFAULT_WHEEL_BETA; missingSetting = true; } } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/SASteeringWheelFuzz"); int.TryParse(Item.InnerText, out int temp); saWheelFuzzValues[device] = temp >= 0 && temp <= 100 ? temp : 0; } catch { saWheelFuzzValues[device] = 0; missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/GyroOutputMode"); string tempMode = Item.InnerText; gyroOutMode[device] = GetGyroOutModeType(tempMode); } catch { PortOldGyroSettings(device); missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/GyroMouseStickTriggers"); sAMouseStickTriggers[device] = Item.InnerText; } catch { sAMouseStickTriggers[device] = "-1"; missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/GyroMouseStickTriggerCond"); sAMouseStickTriggerCond[device] = SaTriggerCondValue(Item.InnerText); } catch { sAMouseStickTriggerCond[device] = true; missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/GyroMouseStickTriggerTurns"); bool.TryParse(Item.InnerText, out gyroMouseStickTriggerTurns[device]); } catch { gyroMouseStickTriggerTurns[device] = true; missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/GyroMouseStickHAxis"); int temp = 0; int.TryParse(Item.InnerText, out temp); gyroMouseStickHorizontalAxis[device] = Math.Min(Math.Max(0, temp), 1); } catch { gyroMouseStickHorizontalAxis[device] = 0; missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/GyroMouseStickDeadZone"); int.TryParse(Item.InnerText, out int temp); gyroMStickInfo[device].deadZone = temp; } catch { gyroMStickInfo[device].deadZone = 30; missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/GyroMouseStickMaxZone"); int.TryParse(Item.InnerText, out int temp); gyroMStickInfo[device].maxZone = Math.Max(temp, 1); } catch { gyroMStickInfo[device].maxZone = 830; missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/GyroMouseStickAntiDeadX"); double.TryParse(Item.InnerText, out double temp); gyroMStickInfo[device].antiDeadX = temp; } catch { gyroMStickInfo[device].antiDeadX = 0.4; missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/GyroMouseStickAntiDeadY"); double.TryParse(Item.InnerText, out double temp); gyroMStickInfo[device].antiDeadY = temp; } catch { gyroMStickInfo[device].antiDeadY = 0.4; missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/GyroMouseStickInvert"); uint.TryParse(Item.InnerText, out gyroMStickInfo[device].inverted); } catch { gyroMStickInfo[device].inverted = 0; missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/GyroMouseStickToggle"); bool.TryParse(Item.InnerText, out bool temp); gyroMouseStickToggle[device] = temp; } catch { gyroMouseStickToggle[device] = false; missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/GyroMouseStickMaxOutput"); double temp = 100.0; temp = double.Parse(Item.InnerText); gyroMStickInfo[device].maxOutput = Math.Min(Math.Max(temp, 0.0), 100.0); } catch { gyroMStickInfo[device].maxOutput = 100.0; missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/GyroMouseStickMaxOutputEnabled"); bool.TryParse(Item.InnerText, out bool temp); gyroMStickInfo[device].maxOutputEnabled = temp; } catch { gyroMStickInfo[device].maxOutputEnabled = false; missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/GyroMouseStickVerticalScale"); int.TryParse(Item.InnerText, out gyroMStickInfo[device].vertScale); } catch { gyroMStickInfo[device].vertScale = 100; missingSetting = true; } bool gyroMStickSmoothingGroup = false; XmlNode xmlGyroMStickSmoothingElement = m_Xdoc.SelectSingleNode("/" + rootname + "/GyroMouseStickSmoothingSettings"); gyroMStickSmoothingGroup = xmlGyroMStickSmoothingElement != null; if (gyroMStickSmoothingGroup) { try { Item = xmlGyroMStickSmoothingElement.SelectSingleNode("UseSmoothing"); bool.TryParse(Item.InnerText, out bool tempSmoothing); gyroMStickInfo[device].useSmoothing = tempSmoothing; } catch { gyroMStickInfo[device].useSmoothing = false; missingSetting = true; } try { Item = xmlGyroMStickSmoothingElement.SelectSingleNode("SmoothingMethod"); string temp = Item?.InnerText ?? GyroMouseStickInfo.DEFAULT_SMOOTH_TECHNIQUE; gyroMStickInfo[device].DetermineSmoothMethod(temp); } catch { gyroMStickInfo[device].ResetSmoothing(); missingSetting = true; } try { Item = xmlGyroMStickSmoothingElement.SelectSingleNode("SmoothingWeight"); int temp = 0; int.TryParse(Item.InnerText, out temp); gyroMStickInfo[device].smoothWeight = Math.Min(Math.Max(0.0, Convert.ToDouble(temp * 0.01)), 1.0); } catch { gyroMStickInfo[device].smoothWeight = 0.5; missingSetting = true; } try { Item = xmlGyroMStickSmoothingElement.SelectSingleNode("SmoothingMinCutoff"); double.TryParse(Item.InnerText, out double temp); gyroMStickInfo[device].minCutoff = Math.Min(Math.Max(0.0, temp), 100.0); } catch { gyroMStickInfo[device].minCutoff = GyroMouseStickInfo.DEFAULT_MINCUTOFF; missingSetting = true; } try { Item = xmlGyroMStickSmoothingElement.SelectSingleNode("SmoothingBeta"); double.TryParse(Item.InnerText, out double temp); gyroMStickInfo[device].beta = Math.Min(Math.Max(0.0, temp), 1.0); } catch { gyroMStickInfo[device].beta = GyroMouseStickInfo.DEFAULT_BETA; missingSetting = true; } } else { missingSetting = true; } // Check for TouchpadOutputMode if UseTPforControls is not present in profile if (!tpForControlsPresent) { try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/TouchpadOutputMode"); string tempMode = Item.InnerText; Enum.TryParse(tempMode, out touchOutMode[device]); } catch { touchOutMode[device] = TouchpadOutMode.Mouse; missingSetting = true; } } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/TouchDisInvTriggers"); string[] triggers = Item.InnerText.Split(','); int temp = -1; List<int> tempIntList = new List<int>(); for (int i = 0, arlen = triggers.Length; i < arlen; i++) { if (int.TryParse(triggers[i], out temp)) tempIntList.Add(temp); } touchDisInvertTriggers[device] = tempIntList.ToArray(); } catch { touchDisInvertTriggers[device] = new int[1] { -1 }; missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/GyroSensitivity"); int.TryParse(Item.InnerText, out gyroSensitivity[device]); } catch { gyroSensitivity[device] = 100; missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/GyroSensVerticalScale"); int.TryParse(Item.InnerText, out gyroSensVerticalScale[device]); } catch { gyroSensVerticalScale[device] = 100; missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/GyroInvert"); int.TryParse(Item.InnerText, out gyroInvert[device]); } catch { gyroInvert[device] = 0; missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/GyroTriggerTurns"); bool.TryParse(Item.InnerText, out gyroTriggerTurns[device]); } catch { gyroTriggerTurns[device] = true; missingSetting = true; } /*try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/GyroSmoothing"); bool.TryParse(Item.InnerText, out gyroSmoothing[device]); } catch { gyroSmoothing[device] = false; missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/GyroSmoothingWeight"); int temp = 0; int.TryParse(Item.InnerText, out temp); gyroSmoothWeight[device] = Math.Min(Math.Max(0.0, Convert.ToDouble(temp * 0.01)), 1.0); } catch { gyroSmoothWeight[device] = 0.5; missingSetting = true; } */ bool gyroSmoothingGroup = false; XmlNode xmlGyroSmoothingElement = m_Xdoc.SelectSingleNode("/" + rootname + "/GyroMouseSmoothingSettings"); gyroSmoothingGroup = xmlGyroSmoothingElement != null; if (gyroSmoothingGroup) { try { Item = xmlGyroSmoothingElement.SelectSingleNode("UseSmoothing"); bool.TryParse(Item.InnerText, out bool temp); gyroMouseInfo[device].enableSmoothing = temp; } catch { gyroMouseInfo[device].enableSmoothing = false; missingSetting = true; } try { Item = xmlGyroSmoothingElement.SelectSingleNode("SmoothingMethod"); string temp = Item?.InnerText ?? GyroMouseInfo.DEFAULT_SMOOTH_TECHNIQUE; gyroMouseInfo[device].DetermineSmoothMethod(temp); } catch { gyroMouseInfo[device].ResetSmoothing(); missingSetting = true; } try { Item = xmlGyroSmoothingElement.SelectSingleNode("SmoothingWeight"); int.TryParse(Item.InnerText, out int temp); gyroMouseInfo[device].smoothingWeight = Math.Min(Math.Max(0.0, Convert.ToDouble(temp * 0.01)), 1.0); } catch { gyroMouseInfo[device].smoothingWeight = 0.5; missingSetting = true; } try { Item = xmlGyroSmoothingElement.SelectSingleNode("SmoothingMinCutoff"); double.TryParse(Item.InnerText, out double temp); gyroMouseInfo[device].minCutoff = Math.Min(Math.Max(0.0, temp), 100.0); } catch { gyroMouseInfo[device].minCutoff = GyroMouseInfo.DEFAULT_MINCUTOFF; missingSetting = true; } try { Item = xmlGyroSmoothingElement.SelectSingleNode("SmoothingBeta"); double.TryParse(Item.InnerText, out double temp); gyroMouseInfo[device].beta = Math.Min(Math.Max(0.0, temp), 1.0); } catch { gyroMouseInfo[device].beta = GyroMouseInfo.DEFAULT_BETA; missingSetting = true; } } else { missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/GyroMouseHAxis"); int temp = 0; int.TryParse(Item.InnerText, out temp); gyroMouseHorizontalAxis[device] = Math.Min(Math.Max(0, temp), 1); } catch { gyroMouseHorizontalAxis[device] = 0; missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/GyroMouseDeadZone"); int.TryParse(Item.InnerText, out int temp); SetGyroMouseDZ(device, temp, control); } catch { SetGyroMouseDZ(device, MouseCursor.GYRO_MOUSE_DEADZONE, control); missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/GyroMouseMinThreshold"); double.TryParse(Item.InnerText, out double temp); temp = Math.Min(Math.Max(temp, 1.0), 40.0); gyroMouseInfo[device].minThreshold = temp; } catch { gyroMouseInfo[device].minThreshold = GyroMouseInfo.DEFAULT_MIN_THRESHOLD; missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/GyroMouseToggle"); bool.TryParse(Item.InnerText, out bool temp); gyroMouseToggle[device] = temp; } catch { gyroMouseToggle[device] = false; missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/LSCurve"); int.TryParse(Item.InnerText, out lsCurve[device]); } catch { lsCurve[device] = 0; missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/RSCurve"); int.TryParse(Item.InnerText, out rsCurve[device]); } catch { rsCurve[device] = 0; missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/BTPollRate"); int temp = 0; int.TryParse(Item.InnerText, out temp); btPollRate[device] = (temp >= 0 && temp <= 16) ? temp : 4; } catch { btPollRate[device] = 4; missingSetting = true; } // Note! xxOutputCurveCustom property needs to be read before xxOutputCurveMode property in case the curveMode is value 6 try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/LSOutputCurveCustom"); lsOutBezierCurveObj[device].CustomDefinition = Item.InnerText; } catch { missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/LSOutputCurveMode"); setLsOutCurveMode(device, stickOutputCurveId(Item.InnerText)); } catch { setLsOutCurveMode(device, 0); missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/RSOutputCurveCustom"); rsOutBezierCurveObj[device].CustomDefinition = Item.InnerText; } catch { missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/RSOutputCurveMode"); setRsOutCurveMode(device, stickOutputCurveId(Item.InnerText)); } catch { setRsOutCurveMode(device, 0); missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/LSSquareStick"); bool.TryParse(Item.InnerText, out squStickInfo[device].lsMode); } catch { squStickInfo[device].lsMode = false; missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/SquareStickRoundness"); double.TryParse(Item.InnerText, out squStickInfo[device].lsRoundness); } catch { squStickInfo[device].lsRoundness = 5.0; missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/SquareRStickRoundness"); double.TryParse(Item.InnerText, out squStickInfo[device].rsRoundness); } catch { squStickInfo[device].rsRoundness = 5.0; missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/RSSquareStick"); bool.TryParse(Item.InnerText, out squStickInfo[device].rsMode); } catch { squStickInfo[device].rsMode = false; missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/LSOutputMode"); Enum.TryParse(Item.InnerText, out lsOutputSettings[device].mode); } catch { missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/RSOutputMode"); Enum.TryParse(Item.InnerText, out rsOutputSettings[device].mode); } catch { missingSetting = true; } XmlNode xmlLSOutputSettingsElement = m_Xdoc.SelectSingleNode("/" + rootname + "/LSOutputSettings"); bool lsOutputGroup = xmlLSOutputSettingsElement != null; if (lsOutputGroup) { bool flickStickLSGroup = false; XmlNode xmlFlickStickLSElement = xmlLSOutputSettingsElement.SelectSingleNode("FlickStickSettings"); flickStickLSGroup = xmlFlickStickLSElement != null; if (flickStickLSGroup) { try { Item = xmlFlickStickLSElement.SelectSingleNode("RealWorldCalibration"); double.TryParse(Item.InnerText, out double temp); lsOutputSettings[device].outputSettings.flickSettings.realWorldCalibration = temp; } catch { missingSetting = true; } try { Item = xmlFlickStickLSElement.SelectSingleNode("FlickThreshold"); double.TryParse(Item.InnerText, out double temp); lsOutputSettings[device].outputSettings.flickSettings.flickThreshold = temp; } catch { missingSetting = true; } try { Item = xmlFlickStickLSElement.SelectSingleNode("FlickTime"); double.TryParse(Item.InnerText, out double temp); lsOutputSettings[device].outputSettings.flickSettings.flickTime = temp; } catch { missingSetting = true; } } else { missingSetting = true; } } else { missingSetting = true; } XmlNode xmlRSOutputSettingsElement = m_Xdoc.SelectSingleNode("/" + rootname + "/RSOutputSettings"); bool rsOutputGroup = xmlRSOutputSettingsElement != null; if (rsOutputGroup) { bool flickStickRSGroup = false; XmlNode xmlFlickStickRSElement = xmlRSOutputSettingsElement.SelectSingleNode("FlickStickSettings"); flickStickRSGroup = xmlFlickStickRSElement != null; if (flickStickRSGroup) { try { Item = xmlFlickStickRSElement.SelectSingleNode("RealWorldCalibration"); double.TryParse(Item.InnerText, out double temp); rsOutputSettings[device].outputSettings.flickSettings.realWorldCalibration = temp; } catch { missingSetting = true; } try { Item = xmlFlickStickRSElement.SelectSingleNode("FlickThreshold"); double.TryParse(Item.InnerText, out double temp); rsOutputSettings[device].outputSettings.flickSettings.flickThreshold = temp; } catch { missingSetting = true; } try { Item = xmlFlickStickRSElement.SelectSingleNode("FlickTime"); double.TryParse(Item.InnerText, out double temp); rsOutputSettings[device].outputSettings.flickSettings.flickTime = temp; } catch { missingSetting = true; } } else { missingSetting = true; } } else { missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/L2OutputCurveCustom"); l2OutBezierCurveObj[device].CustomDefinition = Item.InnerText; } catch { missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/L2OutputCurveMode"); setL2OutCurveMode(device, axisOutputCurveId(Item.InnerText)); } catch { setL2OutCurveMode(device, 0); missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/R2OutputCurveCustom"); r2OutBezierCurveObj[device].CustomDefinition = Item.InnerText; } catch { missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/R2OutputCurveMode"); setR2OutCurveMode(device, axisOutputCurveId(Item.InnerText)); } catch { setR2OutCurveMode(device, 0); missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/SXOutputCurveCustom"); sxOutBezierCurveObj[device].CustomDefinition = Item.InnerText; } catch { missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/SXOutputCurveMode"); setSXOutCurveMode(device, axisOutputCurveId(Item.InnerText)); } catch { setSXOutCurveMode(device, 0); missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/SZOutputCurveCustom"); szOutBezierCurveObj[device].CustomDefinition = Item.InnerText; } catch { missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/SZOutputCurveMode"); setSZOutCurveMode(device, axisOutputCurveId(Item.InnerText)); } catch { setSZOutCurveMode(device, 0); missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/TrackballMode"); bool.TryParse(Item.InnerText, out trackballMode[device]); } catch { trackballMode[device] = false; missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/TrackballFriction"); double.TryParse(Item.InnerText, out trackballFriction[device]); } catch { trackballFriction[device] = 10.0; missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/TouchRelMouseRotation"); int.TryParse(Item.InnerText, out int temp); temp = Math.Min(Math.Max(temp, -180), 180); touchpadRelMouse[device].rotation = temp * Math.PI / 180.0; } catch { touchpadRelMouse[device].rotation = 0.0; missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/TouchRelMouseMinThreshold"); double.TryParse(Item.InnerText, out double temp); temp = Math.Min(Math.Max(temp, 1.0), 40.0); touchpadRelMouse[device].minThreshold = temp; } catch { touchpadRelMouse[device].minThreshold = TouchpadRelMouseSettings.DEFAULT_MIN_THRESHOLD; missingSetting = true; } bool touchpadAbsMouseGroup = false; XmlNode touchpadAbsMouseElement = m_Xdoc.SelectSingleNode("/" + rootname + "/TouchpadAbsMouseSettings"); touchpadAbsMouseGroup = touchpadAbsMouseElement != null; if (touchpadAbsMouseGroup) { try { Item = touchpadAbsMouseElement.SelectSingleNode("MaxZoneX"); int.TryParse(Item.InnerText, out int temp); touchpadAbsMouse[device].maxZoneX = temp; } catch { touchpadAbsMouse[device].maxZoneX = TouchpadAbsMouseSettings.DEFAULT_MAXZONE_X; missingSetting = true; } try { Item = touchpadAbsMouseElement.SelectSingleNode("MaxZoneY"); int.TryParse(Item.InnerText, out int temp); touchpadAbsMouse[device].maxZoneY = temp; } catch { touchpadAbsMouse[device].maxZoneY = TouchpadAbsMouseSettings.DEFAULT_MAXZONE_Y; missingSetting = true; } try { Item = touchpadAbsMouseElement.SelectSingleNode("SnapToCenter"); bool.TryParse(Item.InnerText, out bool temp); touchpadAbsMouse[device].snapToCenter = temp; } catch { touchpadAbsMouse[device].snapToCenter = TouchpadAbsMouseSettings.DEFAULT_SNAP_CENTER; missingSetting = true; } } else { missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/OutputContDevice"); outputDevType[device] = OutContDeviceId(Item.InnerText); } catch { outputDevType[device] = OutContType.X360; missingSetting = true; } // Only change xinput devices under certain conditions. Avoid // performing this upon program startup before loading devices. if (xinputChange) { CheckOldDevicestatus(device, control, oldContType, out xinputPlug, out xinputStatus); } try { Item = m_Xdoc.SelectSingleNode("/" + rootname + "/ProfileActions"); profileActions[device].Clear(); if (!string.IsNullOrEmpty(Item.InnerText)) { string[] actionNames = Item.InnerText.Split('/'); for (int actIndex = 0, actLen = actionNames.Length; actIndex < actLen; actIndex++) { string tempActionName = actionNames[actIndex]; if (!profileActions[device].Contains(tempActionName)) { profileActions[device].Add(tempActionName); } } } } catch { profileActions[device].Clear(); missingSetting = true; } foreach (DS4ControlSettings dcs in ds4settings[device]) dcs.Reset(); containsCustomAction[device] = false; containsCustomExtras[device] = false; profileActionCount[device] = profileActions[device].Count; profileActionDict[device].Clear(); profileActionIndexDict[device].Clear(); foreach (string actionname in profileActions[device]) { profileActionDict[device][actionname] = Global.GetAction(actionname); profileActionIndexDict[device][actionname] = Global.GetActionIndexOf(actionname); } DS4KeyType keyType; ushort wvk; { XmlNode ParentItem = m_Xdoc.SelectSingleNode("/" + rootname + "/Control/Button"); if (ParentItem != null) { foreach (XmlNode item in ParentItem.ChildNodes) { UpdateDS4CSetting(device, item.Name, false, getX360ControlsByName(item.InnerText), "", DS4KeyType.None, 0); customMapButtons.Add(getDS4ControlsByName(item.Name), getX360ControlsByName(item.InnerText)); } } ParentItem = m_Xdoc.SelectSingleNode("/" + rootname + "/Control/Macro"); if (ParentItem != null) { foreach (XmlNode item in ParentItem.ChildNodes) { customMapMacros.Add(getDS4ControlsByName(item.Name), item.InnerText); string[] skeys; int[] keys; if (!string.IsNullOrEmpty(item.InnerText)) { skeys = item.InnerText.Split('/'); keys = new int[skeys.Length]; } else { skeys = new string[0]; keys = new int[0]; } for (int i = 0, keylen = keys.Length; i < keylen; i++) keys[i] = int.Parse(skeys[i]); UpdateDS4CSetting(device, item.Name, false, keys, "", DS4KeyType.None, 0); } } ParentItem = m_Xdoc.SelectSingleNode("/" + rootname + "/Control/Key"); if (ParentItem != null) { foreach (XmlNode item in ParentItem.ChildNodes) { if (ushort.TryParse(item.InnerText, out wvk)) { UpdateDS4CSetting(device, item.Name, false, wvk, "", DS4KeyType.None, 0); customMapKeys.Add(getDS4ControlsByName(item.Name), wvk); } } } ParentItem = m_Xdoc.SelectSingleNode("/" + rootname + "/Control/Extras"); if (ParentItem != null) { foreach (XmlNode item in ParentItem.ChildNodes) { if (item.InnerText != string.Empty) { UpdateDS4CExtra(device, item.Name, false, item.InnerText); customMapExtras.Add(getDS4ControlsByName(item.Name), item.InnerText); } else ParentItem.RemoveChild(item); } } ParentItem = m_Xdoc.SelectSingleNode("/" + rootname + "/Control/KeyType"); if (ParentItem != null) { foreach (XmlNode item in ParentItem.ChildNodes) { if (item != null) { keyType = DS4KeyType.None; if (item.InnerText.Contains(DS4KeyType.ScanCode.ToString())) keyType |= DS4KeyType.ScanCode; if (item.InnerText.Contains(DS4KeyType.Toggle.ToString())) keyType |= DS4KeyType.Toggle; if (item.InnerText.Contains(DS4KeyType.Macro.ToString())) keyType |= DS4KeyType.Macro; if (item.InnerText.Contains(DS4KeyType.HoldMacro.ToString())) keyType |= DS4KeyType.HoldMacro; if (item.InnerText.Contains(DS4KeyType.Unbound.ToString())) keyType |= DS4KeyType.Unbound; if (keyType != DS4KeyType.None) { UpdateDS4CKeyType(device, item.Name, false, keyType); customMapKeyTypes.Add(getDS4ControlsByName(item.Name), keyType); } } } } ParentItem = m_Xdoc.SelectSingleNode("/" + rootname + "/ShiftControl/Button"); if (ParentItem != null) { foreach (XmlElement item in ParentItem.ChildNodes) { int shiftT = shiftM; if (item.HasAttribute("Trigger")) int.TryParse(item.Attributes["Trigger"].Value, out shiftT); UpdateDS4CSetting(device, item.Name, true, getX360ControlsByName(item.InnerText), "", DS4KeyType.None, shiftT); shiftCustomMapButtons.Add(getDS4ControlsByName(item.Name), getX360ControlsByName(item.InnerText)); } } ParentItem = m_Xdoc.SelectSingleNode("/" + rootname + "/ShiftControl/Macro"); if (ParentItem != null) { foreach (XmlElement item in ParentItem.ChildNodes) { shiftCustomMapMacros.Add(getDS4ControlsByName(item.Name), item.InnerText); string[] skeys; int[] keys; if (!string.IsNullOrEmpty(item.InnerText)) { skeys = item.InnerText.Split('/'); keys = new int[skeys.Length]; } else { skeys = new string[0]; keys = new int[0]; } for (int i = 0, keylen = keys.Length; i < keylen; i++) keys[i] = int.Parse(skeys[i]); int shiftT = shiftM; if (item.HasAttribute("Trigger")) int.TryParse(item.Attributes["Trigger"].Value, out shiftT); UpdateDS4CSetting(device, item.Name, true, keys, "", DS4KeyType.None, shiftT); } } ParentItem = m_Xdoc.SelectSingleNode("/" + rootname + "/ShiftControl/Key"); if (ParentItem != null) { foreach (XmlElement item in ParentItem.ChildNodes) { if (ushort.TryParse(item.InnerText, out wvk)) { int shiftT = shiftM; if (item.HasAttribute("Trigger")) int.TryParse(item.Attributes["Trigger"].Value, out shiftT); UpdateDS4CSetting(device, item.Name, true, wvk, "", DS4KeyType.None, shiftT); shiftCustomMapKeys.Add(getDS4ControlsByName(item.Name), wvk); } } } ParentItem = m_Xdoc.SelectSingleNode("/" + rootname + "/ShiftControl/Extras"); if (ParentItem != null) { foreach (XmlElement item in ParentItem.ChildNodes) { if (item.InnerText != string.Empty) { UpdateDS4CExtra(device, item.Name, true, item.InnerText); shiftCustomMapExtras.Add(getDS4ControlsByName(item.Name), item.InnerText); } else ParentItem.RemoveChild(item); } } ParentItem = m_Xdoc.SelectSingleNode("/" + rootname + "/ShiftControl/KeyType"); if (ParentItem != null) { foreach (XmlElement item in ParentItem.ChildNodes) { if (item != null) { keyType = DS4KeyType.None; if (item.InnerText.Contains(DS4KeyType.ScanCode.ToString())) keyType |= DS4KeyType.ScanCode; if (item.InnerText.Contains(DS4KeyType.Toggle.ToString())) keyType |= DS4KeyType.Toggle; if (item.InnerText.Contains(DS4KeyType.Macro.ToString())) keyType |= DS4KeyType.Macro; if (item.InnerText.Contains(DS4KeyType.HoldMacro.ToString())) keyType |= DS4KeyType.HoldMacro; if (item.InnerText.Contains(DS4KeyType.Unbound.ToString())) keyType |= DS4KeyType.Unbound; if (keyType != DS4KeyType.None) { UpdateDS4CKeyType(device, item.Name, true, keyType); shiftCustomMapKeyTypes.Add(getDS4ControlsByName(item.Name), keyType); } } } } } } // Only add missing settings if the actual load was graceful if ((missingSetting || migratePerformed) && Loaded)// && buttons != null) { string proName = Path.GetFileName(profilepath); SaveProfile(device, proName); } CacheProfileCustomsFlags(device); buttonMouseInfos[device].activeButtonSensitivity = buttonMouseInfos[device].buttonSensitivity; if (device < Global.MAX_DS4_CONTROLLER_COUNT && control.touchPad[device] != null) { control.touchPad[device]?.ResetToggleGyroM(); GyroOutMode currentGyro = gyroOutMode[device]; if (currentGyro == GyroOutMode.Mouse) { control.touchPad[device].ToggleGyroMouse = gyroMouseToggle[device]; } else if (currentGyro == GyroOutMode.MouseJoystick) { control.touchPad[device].ToggleGyroMouse = gyroMouseStickToggle[device]; } } // If a device exists, make sure to transfer relevant profile device // options to device instance if (postLoad && device < Global.MAX_DS4_CONTROLLER_COUNT) { PostLoadSnippet(device, control, xinputStatus, xinputPlug); } return Loaded; } public bool Load() { bool Loaded = true; bool missingSetting = false; try { if (File.Exists(m_Profile)) { XmlNode Item; m_Xdoc.Load(m_Profile); try { Item = m_Xdoc.SelectSingleNode("/Profile/useExclusiveMode"); Boolean.TryParse(Item.InnerText, out useExclusiveMode); } // Ex Mode catch { missingSetting = true; } // Ex Mode try { Item = m_Xdoc.SelectSingleNode("/Profile/startMinimized"); Boolean.TryParse(Item.InnerText, out startMinimized); } catch { missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/Profile/minimizeToTaskbar"); Boolean.TryParse(Item.InnerText, out minToTaskbar); } catch { missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/Profile/formWidth"); Int32.TryParse(Item.InnerText, out formWidth); } catch { missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/Profile/formHeight"); Int32.TryParse(Item.InnerText, out formHeight); } catch { missingSetting = true; } try { int temp = 0; Item = m_Xdoc.SelectSingleNode("/Profile/formLocationX"); Int32.TryParse(Item.InnerText, out temp); formLocationX = Math.Max(temp, 0); } catch { missingSetting = true; } try { int temp = 0; Item = m_Xdoc.SelectSingleNode("/Profile/formLocationY"); Int32.TryParse(Item.InnerText, out temp); formLocationY = Math.Max(temp, 0); } catch { missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/Profile/Controller1"); profilePath[0] = Item.InnerText; if (profilePath[0].ToLower().Contains("distance")) { distanceProfiles[0] = true; } olderProfilePath[0] = profilePath[0]; } catch { profilePath[0] = olderProfilePath[0] = string.Empty; distanceProfiles[0] = false; missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/Profile/Controller2"); profilePath[1] = Item.InnerText; if (profilePath[1].ToLower().Contains("distance")) { distanceProfiles[1] = true; } olderProfilePath[1] = profilePath[1]; } catch { profilePath[1] = olderProfilePath[1] = string.Empty; distanceProfiles[1] = false; missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/Profile/Controller3"); profilePath[2] = Item.InnerText; if (profilePath[2].ToLower().Contains("distance")) { distanceProfiles[2] = true; } olderProfilePath[2] = profilePath[2]; } catch { profilePath[2] = olderProfilePath[2] = string.Empty; distanceProfiles[2] = false; missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/Profile/Controller4"); profilePath[3] = Item.InnerText; if (profilePath[3].ToLower().Contains("distance")) { distanceProfiles[3] = true; } olderProfilePath[3] = profilePath[3]; } catch { profilePath[3] = olderProfilePath[3] = string.Empty; distanceProfiles[3] = false; missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/Profile/LastChecked"); DateTime.TryParse(Item.InnerText, out lastChecked); } catch { missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/Profile/CheckWhen"); Int32.TryParse(Item.InnerText, out CheckWhen); } catch { missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/Profile/LastVersionChecked"); string tempVer = Item?.InnerText ?? string.Empty; if (!string.IsNullOrEmpty(tempVer)) { lastVersionCheckedNum = Global.CompileVersionNumberFromString(tempVer); if (lastVersionCheckedNum > 0) lastVersionChecked = tempVer; } } catch { missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/Profile/Notifications"); if (!int.TryParse(Item.InnerText, out notifications)) notifications = (Boolean.Parse(Item.InnerText) ? 2 : 0); } catch { missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/Profile/DisconnectBTAtStop"); Boolean.TryParse(Item.InnerText, out disconnectBTAtStop); } catch { missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/Profile/SwipeProfiles"); Boolean.TryParse(Item.InnerText, out swipeProfiles); } catch { missingSetting = true; } //try { Item = m_Xdoc.SelectSingleNode("/Profile/UseDS4ForMapping"); Boolean.TryParse(Item.InnerText, out ds4Mapping); } //catch { missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/Profile/QuickCharge"); Boolean.TryParse(Item.InnerText, out quickCharge); } catch { missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/Profile/CloseMinimizes"); Boolean.TryParse(Item.InnerText, out closeMini); } catch { missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/Profile/UseLang"); useLang = Item.InnerText; } catch { missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/Profile/DownloadLang"); Boolean.TryParse(Item.InnerText, out downloadLang); } catch { missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/Profile/FlashWhenLate"); Boolean.TryParse(Item.InnerText, out flashWhenLate); } catch { missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/Profile/FlashWhenLateAt"); int.TryParse(Item.InnerText, out flashWhenLateAt); } catch { missingSetting = true; } Item = m_Xdoc.SelectSingleNode("/Profile/AppIcon"); bool hasIconChoice = Item != null; if (hasIconChoice) { hasIconChoice = Enum.TryParse(Item.InnerText ?? "", out useIconChoice); } if (!hasIconChoice) { missingSetting = true; try { Item = m_Xdoc.SelectSingleNode("/Profile/WhiteIcon"); if (bool.TryParse(Item?.InnerText ?? "", out bool temp)) { useIconChoice = temp ? TrayIconChoice.White : TrayIconChoice.Default; } } catch { missingSetting = true; } } try { Item = m_Xdoc.SelectSingleNode("/Profile/AppTheme"); string temp = Item.InnerText; Enum.TryParse(temp, out AppThemeChoice choice); useCurrentTheme = choice; } catch { missingSetting = true; useCurrentTheme = AppThemeChoice.Default; } try { Item = m_Xdoc.SelectSingleNode("/Profile/UseUDPServer"); Boolean.TryParse(Item.InnerText, out useUDPServ); } catch { missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/Profile/UDPServerPort"); int temp; int.TryParse(Item.InnerText, out temp); udpServPort = Math.Min(Math.Max(temp, 1024), 65535); } catch { missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/Profile/UDPServerListenAddress"); udpServListenAddress = Item.InnerText; } catch { missingSetting = true; } bool udpServerSmoothingGroup = false; XmlNode xmlUdpServerSmoothElement = m_Xdoc.SelectSingleNode("/Profile/UDPServerSmoothingOptions"); udpServerSmoothingGroup = xmlUdpServerSmoothElement != null; if (udpServerSmoothingGroup) { try { Item = xmlUdpServerSmoothElement.SelectSingleNode("UseSmoothing"); bool.TryParse(Item.InnerText, out bool temp); useUdpSmoothing = temp; } catch { missingSetting = true; } try { Item = xmlUdpServerSmoothElement.SelectSingleNode("UdpSmoothMinCutoff"); double.TryParse(Item.InnerText, out double temp); temp = Math.Min(Math.Max(temp, 0.00001), 100.0); udpSmoothingMincutoff = temp; } catch { missingSetting = true; } try { Item = xmlUdpServerSmoothElement.SelectSingleNode("UdpSmoothBeta"); double.TryParse(Item.InnerText, out double temp); temp = Math.Min(Math.Max(temp, 0.0), 1.0); udpSmoothingBeta = temp; } catch { missingSetting = true; } } try { Item = m_Xdoc.SelectSingleNode("/Profile/UseCustomSteamFolder"); Boolean.TryParse(Item.InnerText, out useCustomSteamFolder); } catch { missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/Profile/CustomSteamFolder"); customSteamFolder = Item.InnerText; } catch { missingSetting = true; } try { Item = m_Xdoc.SelectSingleNode("/Profile/AutoProfileRevertDefaultProfile"); Boolean.TryParse(Item.InnerText, out autoProfileRevertDefaultProfile); } catch { missingSetting = true; } for (int i = 0; i < Global.MAX_DS4_CONTROLLER_COUNT; i++) { try { Item = m_Xdoc.SelectSingleNode("/Profile/CustomLed" + (i + 1)); string[] ss = Item.InnerText.Split(':'); bool.TryParse(ss[0], out lightbarSettingInfo[i].ds4winSettings.useCustomLed); DS4Color.TryParse(ss[1], ref lightbarSettingInfo[i].ds4winSettings.m_CustomLed); } catch { lightbarSettingInfo[i].ds4winSettings.useCustomLed = false; lightbarSettingInfo[i].ds4winSettings.m_CustomLed = new DS4Color(Color.Blue); missingSetting = true; } } } } catch { } if (missingSetting) Save(); if (Loaded) { string custom_exe_name_path = Path.Combine(Global.exedirpath, Global.CUSTOM_EXE_CONFIG_FILENAME); bool fakeExeFileExists = File.Exists(custom_exe_name_path); if (fakeExeFileExists) { string fake_exe_name = File.ReadAllText(custom_exe_name_path).Trim(); bool valid = !(fake_exe_name.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0); if (valid) { fakeExeFileName = fake_exe_name; } } } return Loaded; } public bool Save() { bool Saved = true; XmlNode Node; m_Xdoc.RemoveAll(); Node = m_Xdoc.CreateXmlDeclaration("1.0", "utf-8", String.Empty); m_Xdoc.AppendChild(Node); Node = m_Xdoc.CreateComment(String.Format(" Profile Configuration Data. {0} ", DateTime.Now)); m_Xdoc.AppendChild(Node); Node = m_Xdoc.CreateComment(string.Format(" Made with DS4Windows version {0} ", Global.exeversion)); m_Xdoc.AppendChild(Node); Node = m_Xdoc.CreateWhitespace("\r\n"); m_Xdoc.AppendChild(Node); XmlElement rootElement = m_Xdoc.CreateElement("Profile", null); rootElement.SetAttribute("app_version", Global.exeversion); rootElement.SetAttribute("config_version", Global.APP_CONFIG_VERSION.ToString()); // Ex Mode (+1 line) XmlNode xmlUseExclNode = m_Xdoc.CreateNode(XmlNodeType.Element, "useExclusiveMode", null); xmlUseExclNode.InnerText = useExclusiveMode.ToString(); rootElement.AppendChild(xmlUseExclNode); XmlNode xmlStartMinimized = m_Xdoc.CreateNode(XmlNodeType.Element, "startMinimized", null); xmlStartMinimized.InnerText = startMinimized.ToString(); rootElement.AppendChild(xmlStartMinimized); XmlNode xmlminToTaskbar = m_Xdoc.CreateNode(XmlNodeType.Element, "minimizeToTaskbar", null); xmlminToTaskbar.InnerText = minToTaskbar.ToString(); rootElement.AppendChild(xmlminToTaskbar); XmlNode xmlFormWidth = m_Xdoc.CreateNode(XmlNodeType.Element, "formWidth", null); xmlFormWidth.InnerText = formWidth.ToString(); rootElement.AppendChild(xmlFormWidth); XmlNode xmlFormHeight = m_Xdoc.CreateNode(XmlNodeType.Element, "formHeight", null); xmlFormHeight.InnerText = formHeight.ToString(); rootElement.AppendChild(xmlFormHeight); XmlNode xmlFormLocationX = m_Xdoc.CreateNode(XmlNodeType.Element, "formLocationX", null); xmlFormLocationX.InnerText = formLocationX.ToString(); rootElement.AppendChild(xmlFormLocationX); XmlNode xmlFormLocationY = m_Xdoc.CreateNode(XmlNodeType.Element, "formLocationY", null); xmlFormLocationY.InnerText = formLocationY.ToString(); rootElement.AppendChild(xmlFormLocationY); XmlNode xmlController1 = m_Xdoc.CreateNode(XmlNodeType.Element, "Controller1", null); xmlController1.InnerText = !Global.linkedProfileCheck[0] ? profilePath[0] : olderProfilePath[0]; rootElement.AppendChild(xmlController1); XmlNode xmlController2 = m_Xdoc.CreateNode(XmlNodeType.Element, "Controller2", null); xmlController2.InnerText = !Global.linkedProfileCheck[1] ? profilePath[1] : olderProfilePath[1]; rootElement.AppendChild(xmlController2); XmlNode xmlController3 = m_Xdoc.CreateNode(XmlNodeType.Element, "Controller3", null); xmlController3.InnerText = !Global.linkedProfileCheck[2] ? profilePath[2] : olderProfilePath[2]; rootElement.AppendChild(xmlController3); XmlNode xmlController4 = m_Xdoc.CreateNode(XmlNodeType.Element, "Controller4", null); xmlController4.InnerText = !Global.linkedProfileCheck[3] ? profilePath[3] : olderProfilePath[3]; rootElement.AppendChild(xmlController4); XmlNode xmlLastChecked = m_Xdoc.CreateNode(XmlNodeType.Element, "LastChecked", null); xmlLastChecked.InnerText = lastChecked.ToString(); rootElement.AppendChild(xmlLastChecked); XmlNode xmlCheckWhen = m_Xdoc.CreateNode(XmlNodeType.Element, "CheckWhen", null); xmlCheckWhen.InnerText = CheckWhen.ToString(); rootElement.AppendChild(xmlCheckWhen); if (!string.IsNullOrEmpty(lastVersionChecked)) { XmlNode xmlLastVersionChecked = m_Xdoc.CreateNode(XmlNodeType.Element, "LastVersionChecked", null); xmlLastVersionChecked.InnerText = lastVersionChecked.ToString(); rootElement.AppendChild(xmlLastVersionChecked); } XmlNode xmlNotifications = m_Xdoc.CreateNode(XmlNodeType.Element, "Notifications", null); xmlNotifications.InnerText = notifications.ToString(); rootElement.AppendChild(xmlNotifications); XmlNode xmlDisconnectBT = m_Xdoc.CreateNode(XmlNodeType.Element, "DisconnectBTAtStop", null); xmlDisconnectBT.InnerText = disconnectBTAtStop.ToString(); rootElement.AppendChild(xmlDisconnectBT); XmlNode xmlSwipeProfiles = m_Xdoc.CreateNode(XmlNodeType.Element, "SwipeProfiles", null); xmlSwipeProfiles.InnerText = swipeProfiles.ToString(); rootElement.AppendChild(xmlSwipeProfiles); //XmlNode xmlDS4Mapping = m_Xdoc.CreateNode(XmlNodeType.Element, "UseDS4ForMapping", null); xmlDS4Mapping.InnerText = ds4Mapping.ToString(); rootElement.AppendChild(xmlDS4Mapping); XmlNode xmlQuickCharge = m_Xdoc.CreateNode(XmlNodeType.Element, "QuickCharge", null); xmlQuickCharge.InnerText = quickCharge.ToString(); rootElement.AppendChild(xmlQuickCharge); XmlNode xmlCloseMini = m_Xdoc.CreateNode(XmlNodeType.Element, "CloseMinimizes", null); xmlCloseMini.InnerText = closeMini.ToString(); rootElement.AppendChild(xmlCloseMini); XmlNode xmlUseLang = m_Xdoc.CreateNode(XmlNodeType.Element, "UseLang", null); xmlUseLang.InnerText = useLang.ToString(); rootElement.AppendChild(xmlUseLang); XmlNode xmlDownloadLang = m_Xdoc.CreateNode(XmlNodeType.Element, "DownloadLang", null); xmlDownloadLang.InnerText = downloadLang.ToString(); rootElement.AppendChild(xmlDownloadLang); XmlNode xmlFlashWhenLate = m_Xdoc.CreateNode(XmlNodeType.Element, "FlashWhenLate", null); xmlFlashWhenLate.InnerText = flashWhenLate.ToString(); rootElement.AppendChild(xmlFlashWhenLate); XmlNode xmlFlashWhenLateAt = m_Xdoc.CreateNode(XmlNodeType.Element, "FlashWhenLateAt", null); xmlFlashWhenLateAt.InnerText = flashWhenLateAt.ToString(); rootElement.AppendChild(xmlFlashWhenLateAt); XmlNode xmlAppIconChoice = m_Xdoc.CreateNode(XmlNodeType.Element, "AppIcon", null); xmlAppIconChoice.InnerText = useIconChoice.ToString(); rootElement.AppendChild(xmlAppIconChoice); XmlNode xmlAppThemeChoice = m_Xdoc.CreateNode(XmlNodeType.Element, "AppTheme", null); xmlAppThemeChoice.InnerText = useCurrentTheme.ToString(); rootElement.AppendChild(xmlAppThemeChoice); XmlNode xmlUseUDPServ = m_Xdoc.CreateNode(XmlNodeType.Element, "UseUDPServer", null); xmlUseUDPServ.InnerText = useUDPServ.ToString(); rootElement.AppendChild(xmlUseUDPServ); XmlNode xmlUDPServPort = m_Xdoc.CreateNode(XmlNodeType.Element, "UDPServerPort", null); xmlUDPServPort.InnerText = udpServPort.ToString(); rootElement.AppendChild(xmlUDPServPort); XmlNode xmlUDPServListenAddress = m_Xdoc.CreateNode(XmlNodeType.Element, "UDPServerListenAddress", null); xmlUDPServListenAddress.InnerText = udpServListenAddress; rootElement.AppendChild(xmlUDPServListenAddress); XmlElement xmlUdpServerSmoothElement = m_Xdoc.CreateElement("UDPServerSmoothingOptions"); XmlElement xmlUDPUseSmoothing = m_Xdoc.CreateElement("UseSmoothing"); xmlUDPUseSmoothing.InnerText = useUdpSmoothing.ToString(); xmlUdpServerSmoothElement.AppendChild(xmlUDPUseSmoothing); XmlElement xmlUDPSmoothMinCutoff = m_Xdoc.CreateElement("UdpSmoothMinCutoff"); xmlUDPSmoothMinCutoff.InnerText = udpSmoothingMincutoff.ToString(); xmlUdpServerSmoothElement.AppendChild(xmlUDPSmoothMinCutoff); XmlElement xmlUDPSmoothBeta = m_Xdoc.CreateElement("UdpSmoothBeta"); xmlUDPSmoothBeta.InnerText = udpSmoothingBeta.ToString(); xmlUdpServerSmoothElement.AppendChild(xmlUDPSmoothBeta); rootElement.AppendChild(xmlUdpServerSmoothElement); XmlNode xmlUseCustomSteamFolder = m_Xdoc.CreateNode(XmlNodeType.Element, "UseCustomSteamFolder", null); xmlUseCustomSteamFolder.InnerText = useCustomSteamFolder.ToString(); rootElement.AppendChild(xmlUseCustomSteamFolder); XmlNode xmlCustomSteamFolder = m_Xdoc.CreateNode(XmlNodeType.Element, "CustomSteamFolder", null); xmlCustomSteamFolder.InnerText = customSteamFolder; rootElement.AppendChild(xmlCustomSteamFolder); XmlNode xmlAutoProfileRevertDefaultProfile = m_Xdoc.CreateNode(XmlNodeType.Element, "AutoProfileRevertDefaultProfile", null); xmlAutoProfileRevertDefaultProfile.InnerText = autoProfileRevertDefaultProfile.ToString(); rootElement.AppendChild(xmlAutoProfileRevertDefaultProfile); for (int i = 0; i < Global.MAX_DS4_CONTROLLER_COUNT; i++) { XmlNode xmlCustomLed = m_Xdoc.CreateNode(XmlNodeType.Element, "CustomLed" + (1 + i), null); xmlCustomLed.InnerText = lightbarSettingInfo[i].ds4winSettings.useCustomLed + ":" + lightbarSettingInfo[i].ds4winSettings.m_CustomLed.red + "," + lightbarSettingInfo[i].ds4winSettings.m_CustomLed.green + "," + lightbarSettingInfo[i].ds4winSettings.m_CustomLed.blue; rootElement.AppendChild(xmlCustomLed); } m_Xdoc.AppendChild(rootElement); try { m_Xdoc.Save(m_Profile); } catch (UnauthorizedAccessException) { Saved = false; } bool adminNeeded = Global.AdminNeeded(); if (Saved && (!adminNeeded || (adminNeeded && Global.IsAdministrator()))) { string custom_exe_name_path = Path.Combine(Global.exedirpath, Global.CUSTOM_EXE_CONFIG_FILENAME); bool fakeExeFileExists = File.Exists(custom_exe_name_path); if (!string.IsNullOrEmpty(fakeExeFileName) || fakeExeFileExists) { File.WriteAllText(custom_exe_name_path, fakeExeFileName); } } return Saved; } private void CreateAction() { XmlDocument m_Xdoc = new XmlDocument(); XmlNode Node; Node = m_Xdoc.CreateXmlDeclaration("1.0", "utf-8", String.Empty); m_Xdoc.AppendChild(Node); Node = m_Xdoc.CreateComment(String.Format(" Special Actions Configuration Data. {0} ", DateTime.Now)); m_Xdoc.AppendChild(Node); Node = m_Xdoc.CreateWhitespace("\r\n"); m_Xdoc.AppendChild(Node); Node = m_Xdoc.CreateNode(XmlNodeType.Element, "Actions", ""); m_Xdoc.AppendChild(Node); m_Xdoc.Save(m_Actions); } public bool SaveAction(string name, string controls, int mode, string details, bool edit, string extras = "") { bool saved = true; if (!File.Exists(m_Actions)) CreateAction(); m_Xdoc.Load(m_Actions); XmlNode Node; Node = m_Xdoc.CreateComment(String.Format(" Special Actions Configuration Data. {0} ", DateTime.Now)); foreach (XmlNode node in m_Xdoc.SelectNodes("//comment()")) node.ParentNode.ReplaceChild(Node, node); Node = m_Xdoc.SelectSingleNode("Actions"); XmlElement el = m_Xdoc.CreateElement("Action"); el.SetAttribute("Name", name); el.AppendChild(m_Xdoc.CreateElement("Trigger")).InnerText = controls; switch (mode) { case 1: el.AppendChild(m_Xdoc.CreateElement("Type")).InnerText = "Macro"; el.AppendChild(m_Xdoc.CreateElement("Details")).InnerText = details; if (extras != string.Empty) el.AppendChild(m_Xdoc.CreateElement("Extras")).InnerText = extras; break; case 2: el.AppendChild(m_Xdoc.CreateElement("Type")).InnerText = "Program"; el.AppendChild(m_Xdoc.CreateElement("Details")).InnerText = details.Split('?')[0]; el.AppendChild(m_Xdoc.CreateElement("Arguements")).InnerText = extras; el.AppendChild(m_Xdoc.CreateElement("Delay")).InnerText = details.Split('?')[1]; break; case 3: el.AppendChild(m_Xdoc.CreateElement("Type")).InnerText = "Profile"; el.AppendChild(m_Xdoc.CreateElement("Details")).InnerText = details; el.AppendChild(m_Xdoc.CreateElement("UnloadTrigger")).InnerText = extras; break; case 4: el.AppendChild(m_Xdoc.CreateElement("Type")).InnerText = "Key"; el.AppendChild(m_Xdoc.CreateElement("Details")).InnerText = details; if (!string.IsNullOrEmpty(extras)) { string[] exts = extras.Split('\n'); el.AppendChild(m_Xdoc.CreateElement("UnloadTrigger")).InnerText = exts[1]; el.AppendChild(m_Xdoc.CreateElement("UnloadStyle")).InnerText = exts[0]; } break; case 5: el.AppendChild(m_Xdoc.CreateElement("Type")).InnerText = "DisconnectBT"; el.AppendChild(m_Xdoc.CreateElement("Details")).InnerText = details; break; case 6: el.AppendChild(m_Xdoc.CreateElement("Type")).InnerText = "BatteryCheck"; el.AppendChild(m_Xdoc.CreateElement("Details")).InnerText = details; break; case 7: el.AppendChild(m_Xdoc.CreateElement("Type")).InnerText = "MultiAction"; el.AppendChild(m_Xdoc.CreateElement("Details")).InnerText = details; break; case 8: el.AppendChild(m_Xdoc.CreateElement("Type")).InnerText = "SASteeringWheelEmulationCalibrate"; el.AppendChild(m_Xdoc.CreateElement("Details")).InnerText = details; break; } if (edit) { XmlNode oldxmlprocess = m_Xdoc.SelectSingleNode("/Actions/Action[@Name=\"" + name + "\"]"); Node.ReplaceChild(el, oldxmlprocess); } else { Node.AppendChild(el); } m_Xdoc.AppendChild(Node); try { m_Xdoc.Save(m_Actions); } catch { saved = false; } LoadActions(); return saved; } public void RemoveAction(string name) { m_Xdoc.Load(m_Actions); XmlNode Node = m_Xdoc.SelectSingleNode("Actions"); XmlNode Item = m_Xdoc.SelectSingleNode("/Actions/Action[@Name=\"" + name + "\"]"); if (Item != null) Node.RemoveChild(Item); m_Xdoc.AppendChild(Node); m_Xdoc.Save(m_Actions); LoadActions(); } public bool LoadActions() { bool saved = true; if (!File.Exists(Global.appdatapath + "\\Actions.xml")) { SaveAction("Disconnect Controller", "PS/Options", 5, "0", false); saved = false; } try { actions.Clear(); XmlDocument doc = new XmlDocument(); doc.Load(Global.appdatapath + "\\Actions.xml"); XmlNodeList actionslist = doc.SelectNodes("Actions/Action"); string name, controls, type, details, extras, extras2; Mapping.actionDone.Clear(); foreach (XmlNode x in actionslist) { name = x.Attributes["Name"].Value; controls = x.ChildNodes[0].InnerText; type = x.ChildNodes[1].InnerText; details = x.ChildNodes[2].InnerText; Mapping.actionDone.Add(new Mapping.ActionState()); if (type == "Profile") { extras = x.ChildNodes[3].InnerText; actions.Add(new SpecialAction(name, controls, type, details, 0, extras)); } else if (type == "Macro") { if (x.ChildNodes[3] != null) extras = x.ChildNodes[3].InnerText; else extras = string.Empty; actions.Add(new SpecialAction(name, controls, type, details, 0, extras)); } else if (type == "Key") { if (x.ChildNodes[3] != null) { extras = x.ChildNodes[3].InnerText; extras2 = x.ChildNodes[4].InnerText; } else { extras = string.Empty; extras2 = string.Empty; } if (!string.IsNullOrEmpty(extras)) actions.Add(new SpecialAction(name, controls, type, details, 0, extras2 + '\n' + extras)); else actions.Add(new SpecialAction(name, controls, type, details)); } else if (type == "DisconnectBT") { double doub; if (double.TryParse(details, out doub)) actions.Add(new SpecialAction(name, controls, type, "", doub)); else actions.Add(new SpecialAction(name, controls, type, "")); } else if (type == "BatteryCheck") { double doub; if (double.TryParse(details.Split('|')[0], out doub)) actions.Add(new SpecialAction(name, controls, type, details, doub)); else if (double.TryParse(details.Split(',')[0], out doub)) actions.Add(new SpecialAction(name, controls, type, details, doub)); else actions.Add(new SpecialAction(name, controls, type, details)); } else if (type == "Program") { double doub; if (x.ChildNodes[3] != null) { extras = x.ChildNodes[3].InnerText; if (double.TryParse(x.ChildNodes[4].InnerText, out doub)) actions.Add(new SpecialAction(name, controls, type, details, doub, extras)); else actions.Add(new SpecialAction(name, controls, type, details, 0, extras)); } else { actions.Add(new SpecialAction(name, controls, type, details)); } } else if (type == "XboxGameDVR" || type == "MultiAction") { actions.Add(new SpecialAction(name, controls, type, details)); } else if (type == "SASteeringWheelEmulationCalibrate") { double doub; if (double.TryParse(details, out doub)) actions.Add(new SpecialAction(name, controls, type, "", doub)); else actions.Add(new SpecialAction(name, controls, type, "")); } } } catch { saved = false; } return saved; } public bool createLinkedProfiles() { bool saved = true; XmlDocument m_Xdoc = new XmlDocument(); XmlNode Node; Node = m_Xdoc.CreateXmlDeclaration("1.0", "utf-8", string.Empty); m_Xdoc.AppendChild(Node); Node = m_Xdoc.CreateComment(string.Format(" Mac Address and Profile Linking Data. {0} ", DateTime.Now)); m_Xdoc.AppendChild(Node); Node = m_Xdoc.CreateWhitespace("\r\n"); m_Xdoc.AppendChild(Node); Node = m_Xdoc.CreateNode(XmlNodeType.Element, "LinkedControllers", ""); m_Xdoc.AppendChild(Node); try { m_Xdoc.Save(m_linkedProfiles); } catch (UnauthorizedAccessException) { AppLogger.LogToGui("Unauthorized Access - Save failed to path: " + m_linkedProfiles, false); saved = false; } return saved; } public bool LoadLinkedProfiles() { bool loaded = true; if (File.Exists(m_linkedProfiles)) { XmlDocument linkedXdoc = new XmlDocument(); XmlNode Node; linkedXdoc.Load(m_linkedProfiles); linkedProfiles.Clear(); try { Node = linkedXdoc.SelectSingleNode("/LinkedControllers"); XmlNodeList links = Node.ChildNodes; for (int i = 0, listLen = links.Count; i < listLen; i++) { XmlNode current = links[i]; string serial = current.Name.Replace("MAC", string.Empty); string profile = current.InnerText; linkedProfiles[serial] = profile; } } catch { loaded = false; } } else { AppLogger.LogToGui("LinkedProfiles.xml can't be found.", false); loaded = false; } return loaded; } public bool SaveLinkedProfiles() { bool saved = true; if (File.Exists(m_linkedProfiles)) { XmlDocument linkedXdoc = new XmlDocument(); XmlNode Node; Node = linkedXdoc.CreateXmlDeclaration("1.0", "utf-8", string.Empty); linkedXdoc.AppendChild(Node); Node = linkedXdoc.CreateComment(string.Format(" Mac Address and Profile Linking Data. {0} ", DateTime.Now)); linkedXdoc.AppendChild(Node); Node = linkedXdoc.CreateWhitespace("\r\n"); linkedXdoc.AppendChild(Node); Node = linkedXdoc.CreateNode(XmlNodeType.Element, "LinkedControllers", ""); linkedXdoc.AppendChild(Node); Dictionary<string, string>.KeyCollection serials = linkedProfiles.Keys; //for (int i = 0, itemCount = linkedProfiles.Count; i < itemCount; i++) for (var serialEnum = serials.GetEnumerator(); serialEnum.MoveNext();) { //string serial = serials.ElementAt(i); string serial = serialEnum.Current; string profile = linkedProfiles[serial]; XmlElement link = linkedXdoc.CreateElement("MAC" + serial); link.InnerText = profile; Node.AppendChild(link); } try { linkedXdoc.Save(m_linkedProfiles); } catch (UnauthorizedAccessException) { AppLogger.LogToGui("Unauthorized Access - Save failed to path: " + m_linkedProfiles, false); saved = false; } } else { saved = createLinkedProfiles(); saved = saved && SaveLinkedProfiles(); } return saved; } public bool createControllerConfigs() { bool saved = true; XmlDocument configXdoc = new XmlDocument(); XmlNode Node; Node = configXdoc.CreateXmlDeclaration("1.0", "utf-8", string.Empty); configXdoc.AppendChild(Node); Node = configXdoc.CreateComment(string.Format(" Controller config data. {0} ", DateTime.Now)); configXdoc.AppendChild(Node); Node = configXdoc.CreateWhitespace("\r\n"); configXdoc.AppendChild(Node); Node = configXdoc.CreateNode(XmlNodeType.Element, "Controllers", ""); configXdoc.AppendChild(Node); try { configXdoc.Save(m_controllerConfigs); } catch (UnauthorizedAccessException) { AppLogger.LogToGui("Unauthorized Access - Save failed to path: " + m_controllerConfigs, false); saved = false; } return saved; } public bool LoadControllerConfigsForDevice(DS4Device device) { bool loaded = false; if (device == null) return false; if (!File.Exists(m_controllerConfigs)) createControllerConfigs(); try { XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(m_controllerConfigs); XmlNode node = xmlDoc.SelectSingleNode("/Controllers/Controller[@Mac=\"" + device.getMacAddress() + "\"]"); if (node != null) { Int32 intValue; if (Int32.TryParse(node["wheelCenterPoint"].InnerText.Split(',')[0], out intValue)) device.wheelCenterPoint.X = intValue; if (Int32.TryParse(node["wheelCenterPoint"].InnerText.Split(',')[1], out intValue)) device.wheelCenterPoint.Y = intValue; if (Int32.TryParse(node["wheel90DegPointLeft"].InnerText.Split(',')[0], out intValue)) device.wheel90DegPointLeft.X = intValue; if (Int32.TryParse(node["wheel90DegPointLeft"].InnerText.Split(',')[1], out intValue)) device.wheel90DegPointLeft.Y = intValue; if (Int32.TryParse(node["wheel90DegPointRight"].InnerText.Split(',')[0], out intValue)) device.wheel90DegPointRight.X = intValue; if (Int32.TryParse(node["wheel90DegPointRight"].InnerText.Split(',')[1], out intValue)) device.wheel90DegPointRight.Y = intValue; loaded = true; } } catch { AppLogger.LogToGui("ControllerConfigs.xml can't be found.", false); loaded = false; } return loaded; } public bool SaveControllerConfigsForDevice(DS4Device device) { bool saved = true; if (device == null) return false; if (!File.Exists(m_controllerConfigs)) createControllerConfigs(); try { //XmlNode node = null; XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(m_controllerConfigs); XmlNode node = xmlDoc.SelectSingleNode("/Controllers/Controller[@Mac=\"" + device.getMacAddress() + "\"]"); if (node == null) { XmlNode xmlControllersNode = xmlDoc.SelectSingleNode("/Controllers"); XmlElement el = xmlDoc.CreateElement("Controller"); el.SetAttribute("Mac", device.getMacAddress()); el.AppendChild(xmlDoc.CreateElement("wheelCenterPoint")); el.AppendChild(xmlDoc.CreateElement("wheel90DegPointLeft")); el.AppendChild(xmlDoc.CreateElement("wheel90DegPointRight")); node = xmlControllersNode.AppendChild(el); } node["wheelCenterPoint"].InnerText = $"{device.wheelCenterPoint.X},{device.wheelCenterPoint.Y}"; node["wheel90DegPointLeft"].InnerText = $"{device.wheel90DegPointLeft.X},{device.wheel90DegPointLeft.Y}"; node["wheel90DegPointRight"].InnerText = $"{device.wheel90DegPointRight.X},{device.wheel90DegPointRight.Y}"; xmlDoc.Save(m_controllerConfigs); } catch (UnauthorizedAccessException) { AppLogger.LogToGui("Unauthorized Access - Save failed to path: " + m_controllerConfigs, false); saved = false; } return saved; } public void UpdateDS4CSetting(int deviceNum, string buttonName, bool shift, object action, string exts, DS4KeyType kt, int trigger = 0) { DS4Controls dc; if (buttonName.StartsWith("bn")) dc = getDS4ControlsByName(buttonName); else dc = (DS4Controls)Enum.Parse(typeof(DS4Controls), buttonName, true); int temp = (int)dc; if (temp > 0) { int index = temp - 1; DS4ControlSettings dcs = ds4settings[deviceNum][index]; dcs.UpdateSettings(shift, action, exts, kt, trigger); } } public void UpdateDS4CExtra(int deviceNum, string buttonName, bool shift, string exts) { DS4Controls dc; if (buttonName.StartsWith("bn")) dc = getDS4ControlsByName(buttonName); else dc = (DS4Controls)Enum.Parse(typeof(DS4Controls), buttonName, true); int temp = (int)dc; if (temp > 0) { int index = temp - 1; DS4ControlSettings dcs = ds4settings[deviceNum][index]; if (shift) dcs.shiftExtras = exts; else dcs.extras = exts; } } private void UpdateDS4CKeyType(int deviceNum, string buttonName, bool shift, DS4KeyType keyType) { DS4Controls dc; if (buttonName.StartsWith("bn")) dc = getDS4ControlsByName(buttonName); else dc = (DS4Controls)Enum.Parse(typeof(DS4Controls), buttonName, true); int temp = (int)dc; if (temp > 0) { int index = temp - 1; DS4ControlSettings dcs = ds4settings[deviceNum][index]; if (shift) dcs.shiftKeyType = keyType; else dcs.keyType = keyType; } } public object GetDS4Action(int deviceNum, string buttonName, bool shift) { DS4Controls dc; if (buttonName.StartsWith("bn")) dc = getDS4ControlsByName(buttonName); else dc = (DS4Controls)Enum.Parse(typeof(DS4Controls), buttonName, true); int temp = (int)dc; if (temp > 0) { int index = temp - 1; DS4ControlSettings dcs = ds4settings[deviceNum][index]; if (shift) { return dcs.shiftAction; } else { return dcs.action; } } return null; } public object GetDS4Action(int deviceNum, DS4Controls dc, bool shift) { int temp = (int)dc; if (temp > 0) { int index = temp - 1; DS4ControlSettings dcs = ds4settings[deviceNum][index]; if (shift) { return dcs.shiftAction; } else { return dcs.action; } } return null; } public string GetDS4Extra(int deviceNum, string buttonName, bool shift) { DS4Controls dc; if (buttonName.StartsWith("bn")) dc = getDS4ControlsByName(buttonName); else dc = (DS4Controls)Enum.Parse(typeof(DS4Controls), buttonName, true); int temp = (int)dc; if (temp > 0) { int index = temp - 1; DS4ControlSettings dcs = ds4settings[deviceNum][index]; if (shift) return dcs.shiftExtras; else return dcs.extras; } return null; } public DS4KeyType GetDS4KeyType(int deviceNum, string buttonName, bool shift) { DS4Controls dc; if (buttonName.StartsWith("bn")) dc = getDS4ControlsByName(buttonName); else dc = (DS4Controls)Enum.Parse(typeof(DS4Controls), buttonName, true); int temp = (int)dc; if (temp > 0) { int index = temp - 1; DS4ControlSettings dcs = ds4settings[deviceNum][index]; if (shift) return dcs.shiftKeyType; else return dcs.keyType; } return DS4KeyType.None; } public int GetDS4STrigger(int deviceNum, string buttonName) { DS4Controls dc; if (buttonName.StartsWith("bn")) dc = getDS4ControlsByName(buttonName); else dc = (DS4Controls)Enum.Parse(typeof(DS4Controls), buttonName, true); int temp = (int)dc; if (temp > 0) { int index = temp - 1; DS4ControlSettings dcs = ds4settings[deviceNum][index]; return dcs.shiftTrigger; } return 0; } public int GetDS4STrigger(int deviceNum, DS4Controls dc) { int temp = (int)dc; if (temp > 0) { int index = temp - 1; DS4ControlSettings dcs = ds4settings[deviceNum][index]; return dcs.shiftTrigger; } return 0; } public DS4ControlSettings getDS4CSetting(int deviceNum, string buttonName) { DS4Controls dc; if (buttonName.StartsWith("bn")) dc = getDS4ControlsByName(buttonName); else dc = (DS4Controls)Enum.Parse(typeof(DS4Controls), buttonName, true); int temp = (int)dc; if (temp > 0) { int index = temp - 1; DS4ControlSettings dcs = ds4settings[deviceNum][index]; return dcs; } return null; } public DS4ControlSettings getDS4CSetting(int deviceNum, DS4Controls dc) { int temp = (int)dc; if (temp > 0) { int index = temp - 1; DS4ControlSettings dcs = ds4settings[deviceNum][index]; return dcs; } return null; } public bool HasCustomActions(int deviceNum) { List<DS4ControlSettings> ds4settingsList = ds4settings[deviceNum]; for (int i = 0, settingsLen = ds4settingsList.Count; i < settingsLen; i++) { DS4ControlSettings dcs = ds4settingsList[i]; if (dcs.action != null || dcs.shiftAction != null) return true; } return false; } public bool HasCustomExtras(int deviceNum) { List<DS4ControlSettings> ds4settingsList = ds4settings[deviceNum]; for (int i = 0, settingsLen = ds4settingsList.Count; i < settingsLen; i++) { DS4ControlSettings dcs = ds4settingsList[i]; if (dcs.extras != null || dcs.shiftExtras != null) return true; } return false; } private void ResetProfile(int device) { buttonMouseInfos[device].buttonSensitivity = ButtonMouseInfo.DEFAULT_BUTTON_SENS; buttonMouseInfos[device].activeButtonSensitivity = ButtonMouseInfo.DEFAULT_BUTTON_SENS; buttonMouseInfos[device].mouseVelocityOffset = ButtonMouseInfo.MOUSESTICKANTIOFFSET; buttonMouseInfos[device].buttonVerticalScale = ButtonMouseInfo.DEFAULT_BUTTON_VERTICAL_SCALE; buttonMouseInfos[device].mouseAccel = false; enableTouchToggle[device] = true; idleDisconnectTimeout[device] = 0; enableOutputDataToDS4[device] = true; touchpadJitterCompensation[device] = true; lowerRCOn[device] = false; rumble[device] = 100; rumbleAutostopTime[device] = 0; touchSensitivity[device] = 100; l2ModInfo[device].deadZone = r2ModInfo[device].deadZone = 0; lsModInfo[device].deadZone = rsModInfo[device].deadZone = 10; lsModInfo[device].antiDeadZone = rsModInfo[device].antiDeadZone = 20; lsModInfo[device].maxZone = rsModInfo[device].maxZone = 100; lsModInfo[device].maxOutput = rsModInfo[device].maxOutput = 100.0; lsModInfo[device].fuzz = rsModInfo[device].fuzz = StickDeadZoneInfo.DEFAULT_FUZZ; l2ModInfo[device].antiDeadZone = r2ModInfo[device].antiDeadZone = 0; l2ModInfo[device].maxZone = r2ModInfo[device].maxZone = 100; l2ModInfo[device].maxOutput = r2ModInfo[device].maxOutput = 100.0; LSRotation[device] = 0.0; RSRotation[device] = 0.0; SXDeadzone[device] = SZDeadzone[device] = 0.25; SXMaxzone[device] = SZMaxzone[device] = 1.0; SXAntiDeadzone[device] = SZAntiDeadzone[device] = 0.0; l2Sens[device] = r2Sens[device] = 1; LSSens[device] = RSSens[device] = 1; SXSens[device] = SZSens[device] = 1; tapSensitivity[device] = 0; doubleTap[device] = false; scrollSensitivity[device] = 0; touchpadInvert[device] = 0; btPollRate[device] = 4; lsOutputSettings[device].ResetSettings(); rsOutputSettings[device].ResetSettings(); LightbarSettingInfo lightbarSettings = lightbarSettingInfo[device]; LightbarDS4WinInfo lightInfo = lightbarSettings.ds4winSettings; lightbarSettings.Mode = LightbarMode.DS4Win; lightInfo.m_LowLed = new DS4Color(Color.Black); //m_LowLeds[device] = new DS4Color(Color.Black); Color tempColor = Color.Blue; switch(device) { case 0: tempColor = Color.Blue; break; case 1: tempColor = Color.Red; break; case 2: tempColor = Color.Green; break; case 3: tempColor = Color.Pink; break; case 4: tempColor = Color.Blue; break; case 5: tempColor = Color.Red; break; case 6: tempColor = Color.Green; break; case 7: tempColor = Color.Pink; break; case 8: tempColor = Color.White; break; default: tempColor = Color.Blue; break; } lightInfo.m_Led = new DS4Color(tempColor); lightInfo.m_ChargingLed = new DS4Color(Color.Black); lightInfo.m_FlashLed = new DS4Color(Color.Black); lightInfo.flashAt = 0; lightInfo.flashType = 0; lightInfo.chargingType = 0; lightInfo.rainbow = 0; lightInfo.maxRainbowSat = 1.0; lightInfo.ledAsBattery = false; launchProgram[device] = string.Empty; dinputOnly[device] = false; startTouchpadOff[device] = false; touchOutMode[device] = TouchpadOutMode.Mouse; sATriggers[device] = "-1"; sATriggerCond[device] = true; gyroOutMode[device] = GyroOutMode.Controls; sAMouseStickTriggers[device] = "-1"; sAMouseStickTriggerCond[device] = true; gyroMStickInfo[device].Reset(); gyroMouseStickToggle[device] = false; gyroMouseStickTriggerTurns[device] = true; sASteeringWheelEmulationAxis[device] = SASteeringWheelEmulationAxisType.None; sASteeringWheelEmulationRange[device] = 360; saWheelFuzzValues[device] = 0; wheelSmoothInfo[device].Reset(); touchDisInvertTriggers[device] = new int[1] { -1 }; lsCurve[device] = rsCurve[device] = 0; gyroSensitivity[device] = 100; gyroSensVerticalScale[device] = 100; gyroInvert[device] = 0; gyroTriggerTurns[device] = true; gyroMouseInfo[device].Reset(); gyroMouseHorizontalAxis[device] = 0; gyroMouseToggle[device] = false; squStickInfo[device].lsMode = false; squStickInfo[device].rsMode = false; squStickInfo[device].lsRoundness = 5.0; squStickInfo[device].rsRoundness = 5.0; setLsOutCurveMode(device, 0); setRsOutCurveMode(device, 0); setL2OutCurveMode(device, 0); setR2OutCurveMode(device, 0); setSXOutCurveMode(device, 0); setSZOutCurveMode(device, 0); trackballMode[device] = false; trackballFriction[device] = 10.0; touchpadAbsMouse[device].Reset(); touchpadRelMouse[device].Reset(); outputDevType[device] = OutContType.X360; ds4Mapping = false; } public void LoadBlankProfile(int device, bool launchprogram, ControlService control, string propath = "", bool xinputChange = true, bool postLoad = true) { bool xinputPlug = false; bool xinputStatus = false; OutContType oldContType = Global.activeOutDevType[device]; // Make sure to reset currently set profile values before parsing ResetProfile(device); // Only change xinput devices under certain conditions. Avoid // performing this upon program startup before loading devices. if (xinputChange) { CheckOldDevicestatus(device, control, oldContType, out xinputPlug, out xinputStatus); } foreach (DS4ControlSettings dcs in ds4settings[device]) dcs.Reset(); profileActions[device].Clear(); containsCustomAction[device] = false; containsCustomExtras[device] = false; // If a device exists, make sure to transfer relevant profile device // options to device instance if (postLoad && device < Global.MAX_DS4_CONTROLLER_COUNT) { PostLoadSnippet(device, control, xinputStatus, xinputPlug); } } public void LoadDefaultGamepadGyroProfile(int device, bool launchprogram, ControlService control, string propath = "", bool xinputChange = true, bool postLoad = true) { bool xinputPlug = false; bool xinputStatus = false; OutContType oldContType = Global.activeOutDevType[device]; // Make sure to reset currently set profile values before parsing ResetProfile(device); // Only change xinput devices under certain conditions. Avoid // performing this upon program startup before loading devices. if (xinputChange) { CheckOldDevicestatus(device, control, oldContType, out xinputPlug, out xinputStatus); } foreach (DS4ControlSettings dcs in ds4settings[device]) dcs.Reset(); profileActions[device].Clear(); containsCustomAction[device] = false; containsCustomExtras[device] = false; gyroOutMode[device] = GyroOutMode.MouseJoystick; sAMouseStickTriggers[device] = "4"; sAMouseStickTriggerCond[device] = true; gyroMouseStickTriggerTurns[device] = false; gyroMStickInfo[device].useSmoothing = true; gyroMStickInfo[device].smoothingMethod = GyroMouseStickInfo.SmoothingMethod.OneEuro; // If a device exists, make sure to transfer relevant profile device // options to device instance if (postLoad && device < Global.MAX_DS4_CONTROLLER_COUNT) { PostLoadSnippet(device, control, xinputStatus, xinputPlug); } } public void LoadDefaultMixedGyroMouseProfile(int device, bool launchprogram, ControlService control, string propath = "", bool xinputChange = true, bool postLoad = true) { bool xinputPlug = false; bool xinputStatus = false; OutContType oldContType = Global.activeOutDevType[device]; // Make sure to reset currently set profile values before parsing ResetProfile(device); // Only change xinput devices under certain conditions. Avoid // performing this upon program startup before loading devices. if (xinputChange) { CheckOldDevicestatus(device, control, oldContType, out xinputPlug, out xinputStatus); } foreach (DS4ControlSettings dcs in ds4settings[device]) dcs.Reset(); profileActions[device].Clear(); containsCustomAction[device] = false; containsCustomExtras[device] = false; gyroOutMode[device] = GyroOutMode.Mouse; sATriggers[device] = "4"; sATriggerCond[device] = true; gyroTriggerTurns[device] = false; gyroMouseInfo[device].enableSmoothing = true; gyroMouseInfo[device].smoothingMethod = GyroMouseInfo.SmoothingMethod.OneEuro; StickDeadZoneInfo rsInfo = rsModInfo[device]; rsInfo.deadZone = (int)(0.10 * 127); rsInfo.antiDeadZone = 0; rsInfo.maxZone = 90; // If a device exists, make sure to transfer relevant profile device // options to device instance if (postLoad && device < Global.MAX_DS4_CONTROLLER_COUNT) { PostLoadSnippet(device, control, xinputStatus, xinputPlug); } } public void LoadDefaultMixedControlsProfile(int device, bool launchprogram, ControlService control, string propath = "", bool xinputChange = true, bool postLoad = true) { bool xinputPlug = false; bool xinputStatus = false; OutContType oldContType = Global.activeOutDevType[device]; // Make sure to reset currently set profile values before parsing ResetProfile(device); // Only change xinput devices under certain conditions. Avoid // performing this upon program startup before loading devices. if (xinputChange) { CheckOldDevicestatus(device, control, oldContType, out xinputPlug, out xinputStatus); } foreach (DS4ControlSettings dcs in ds4settings[device]) dcs.Reset(); profileActions[device].Clear(); containsCustomAction[device] = false; containsCustomExtras[device] = false; DS4ControlSettings setting = getDS4CSetting(device, DS4Controls.RYNeg); setting.UpdateSettings(false, X360Controls.MouseUp, "", DS4KeyType.None); setting = getDS4CSetting(device, DS4Controls.RYPos); setting.UpdateSettings(false, X360Controls.MouseDown, "", DS4KeyType.None); setting = getDS4CSetting(device, DS4Controls.RXNeg); setting.UpdateSettings(false, X360Controls.MouseLeft, "", DS4KeyType.None); setting = getDS4CSetting(device, DS4Controls.RXPos); setting.UpdateSettings(false, X360Controls.MouseRight, "", DS4KeyType.None); StickDeadZoneInfo rsInfo = rsModInfo[device]; rsInfo.deadZone = (int)(0.035 * 127); rsInfo.antiDeadZone = 0; rsInfo.maxZone = 90; // If a device exists, make sure to transfer relevant profile device // options to device instance if (postLoad && device < Global.MAX_DS4_CONTROLLER_COUNT) { PostLoadSnippet(device, control, xinputStatus, xinputPlug); } } public void LoadDefaultKBMProfile(int device, bool launchprogram, ControlService control, string propath = "", bool xinputChange = true, bool postLoad = true) { bool xinputPlug = false; bool xinputStatus = false; OutContType oldContType = Global.activeOutDevType[device]; // Make sure to reset currently set profile values before parsing ResetProfile(device); // Only change xinput devices under certain conditions. Avoid // performing this upon program startup before loading devices. if (xinputChange) { CheckOldDevicestatus(device, control, oldContType, out xinputPlug, out xinputStatus); } foreach (DS4ControlSettings dcs in ds4settings[device]) dcs.Reset(); profileActions[device].Clear(); containsCustomAction[device] = false; containsCustomExtras[device] = false; StickDeadZoneInfo lsInfo = lsModInfo[device]; lsInfo.antiDeadZone = 0; StickDeadZoneInfo rsInfo = rsModInfo[device]; rsInfo.deadZone = (int)(0.035 * 127); rsInfo.antiDeadZone = 0; rsInfo.maxZone = 90; // Flag to unplug virtual controller dinputOnly[device] = true; DS4ControlSettings setting = getDS4CSetting(device, DS4Controls.LYNeg); setting.UpdateSettings(false, KeyInterop.VirtualKeyFromKey(Key.W), "", DS4KeyType.None); setting = getDS4CSetting(device, DS4Controls.LXNeg); setting.UpdateSettings(false, KeyInterop.VirtualKeyFromKey(Key.A), "", DS4KeyType.None); setting = getDS4CSetting(device, DS4Controls.LYPos); setting.UpdateSettings(false, KeyInterop.VirtualKeyFromKey(Key.S), "", DS4KeyType.None); setting = getDS4CSetting(device, DS4Controls.LXPos); setting.UpdateSettings(false, KeyInterop.VirtualKeyFromKey(Key.D), "", DS4KeyType.None); setting = getDS4CSetting(device, DS4Controls.L3); setting.UpdateSettings(false, KeyInterop.VirtualKeyFromKey(Key.LeftShift), "", DS4KeyType.None); setting = getDS4CSetting(device, DS4Controls.RYNeg); setting.UpdateSettings(false, X360Controls.MouseUp, "", DS4KeyType.None); setting = getDS4CSetting(device, DS4Controls.RYPos); setting.UpdateSettings(false, X360Controls.MouseDown, "", DS4KeyType.None); setting = getDS4CSetting(device, DS4Controls.RXNeg); setting.UpdateSettings(false, X360Controls.MouseLeft, "", DS4KeyType.None); setting = getDS4CSetting(device, DS4Controls.RXPos); setting.UpdateSettings(false, X360Controls.MouseRight, "", DS4KeyType.None); setting = getDS4CSetting(device, DS4Controls.R3); setting.UpdateSettings(false, KeyInterop.VirtualKeyFromKey(Key.LeftCtrl), "", DS4KeyType.None); setting = getDS4CSetting(device, DS4Controls.DpadUp); setting.UpdateSettings(false, X360Controls.Unbound, "", DS4KeyType.None); setting = getDS4CSetting(device, DS4Controls.DpadRight); setting.UpdateSettings(false, X360Controls.WDOWN, "", DS4KeyType.None); setting = getDS4CSetting(device, DS4Controls.DpadDown); setting.UpdateSettings(false, X360Controls.Unbound, "", DS4KeyType.None); setting = getDS4CSetting(device, DS4Controls.DpadLeft); setting.UpdateSettings(false, X360Controls.WUP, "", DS4KeyType.None); setting = getDS4CSetting(device, DS4Controls.Cross); setting.UpdateSettings(false, KeyInterop.VirtualKeyFromKey(Key.Space), "", DS4KeyType.None); setting = getDS4CSetting(device, DS4Controls.Square); setting.UpdateSettings(false, KeyInterop.VirtualKeyFromKey(Key.F), "", DS4KeyType.None); setting = getDS4CSetting(device, DS4Controls.Triangle); setting.UpdateSettings(false, KeyInterop.VirtualKeyFromKey(Key.E), "", DS4KeyType.None); setting = getDS4CSetting(device, DS4Controls.Circle); setting.UpdateSettings(false, KeyInterop.VirtualKeyFromKey(Key.C), "", DS4KeyType.None); setting = getDS4CSetting(device, DS4Controls.L1); setting.UpdateSettings(false, KeyInterop.VirtualKeyFromKey(Key.Q), "", DS4KeyType.None); setting = getDS4CSetting(device, DS4Controls.L2); setting.UpdateSettings(false, X360Controls.RightMouse, "", DS4KeyType.None); setting = getDS4CSetting(device, DS4Controls.R1); setting.UpdateSettings(false, KeyInterop.VirtualKeyFromKey(Key.R), "", DS4KeyType.None); setting = getDS4CSetting(device, DS4Controls.R2); setting.UpdateSettings(false, X360Controls.LeftMouse, "", DS4KeyType.None); setting = getDS4CSetting(device, DS4Controls.Share); setting.UpdateSettings(false, KeyInterop.VirtualKeyFromKey(Key.Tab), "", DS4KeyType.None); setting = getDS4CSetting(device, DS4Controls.Options); setting.UpdateSettings(false, KeyInterop.VirtualKeyFromKey(Key.Escape), "", DS4KeyType.None); // If a device exists, make sure to transfer relevant profile device // options to device instance if (postLoad && device < Global.MAX_DS4_CONTROLLER_COUNT) { PostLoadSnippet(device, control, xinputStatus, xinputPlug); } } public void LoadDefaultKBMGyroMouseProfile(int device, bool launchprogram, ControlService control, string propath = "", bool xinputChange = true, bool postLoad = true) { bool xinputPlug = false; bool xinputStatus = false; OutContType oldContType = Global.activeOutDevType[device]; // Make sure to reset currently set profile values before parsing ResetProfile(device); // Only change xinput devices under certain conditions. Avoid // performing this upon program startup before loading devices. if (xinputChange) { CheckOldDevicestatus(device, control, oldContType, out xinputPlug, out xinputStatus); } foreach (DS4ControlSettings dcs in ds4settings[device]) dcs.Reset(); profileActions[device].Clear(); containsCustomAction[device] = false; containsCustomExtras[device] = false; StickDeadZoneInfo lsInfo = lsModInfo[device]; lsInfo.antiDeadZone = 0; StickDeadZoneInfo rsInfo = rsModInfo[device]; rsInfo.deadZone = (int)(0.105 * 127); rsInfo.antiDeadZone = 0; rsInfo.maxZone = 90; gyroOutMode[device] = GyroOutMode.Mouse; sATriggers[device] = "4"; sATriggerCond[device] = true; gyroTriggerTurns[device] = false; gyroMouseInfo[device].enableSmoothing = true; gyroMouseInfo[device].smoothingMethod = GyroMouseInfo.SmoothingMethod.OneEuro; // Flag to unplug virtual controller dinputOnly[device] = true; DS4ControlSettings setting = getDS4CSetting(device, DS4Controls.LYNeg); setting.UpdateSettings(false, KeyInterop.VirtualKeyFromKey(Key.W), "", DS4KeyType.None); setting = getDS4CSetting(device, DS4Controls.LXNeg); setting.UpdateSettings(false, KeyInterop.VirtualKeyFromKey(Key.A), "", DS4KeyType.None); setting = getDS4CSetting(device, DS4Controls.LYPos); setting.UpdateSettings(false, KeyInterop.VirtualKeyFromKey(Key.S), "", DS4KeyType.None); setting = getDS4CSetting(device, DS4Controls.LXPos); setting.UpdateSettings(false, KeyInterop.VirtualKeyFromKey(Key.D), "", DS4KeyType.None); setting = getDS4CSetting(device, DS4Controls.L3); setting.UpdateSettings(false, KeyInterop.VirtualKeyFromKey(Key.LeftShift), "", DS4KeyType.None); setting = getDS4CSetting(device, DS4Controls.RYNeg); setting.UpdateSettings(false, X360Controls.MouseUp, "", DS4KeyType.None); setting = getDS4CSetting(device, DS4Controls.RYPos); setting.UpdateSettings(false, X360Controls.MouseDown, "", DS4KeyType.None); setting = getDS4CSetting(device, DS4Controls.RXNeg); setting.UpdateSettings(false, X360Controls.MouseLeft, "", DS4KeyType.None); setting = getDS4CSetting(device, DS4Controls.RXPos); setting.UpdateSettings(false, X360Controls.MouseRight, "", DS4KeyType.None); setting = getDS4CSetting(device, DS4Controls.R3); setting.UpdateSettings(false, KeyInterop.VirtualKeyFromKey(Key.LeftCtrl), "", DS4KeyType.None); setting = getDS4CSetting(device, DS4Controls.DpadUp); setting.UpdateSettings(false, X360Controls.Unbound, "", DS4KeyType.None); setting = getDS4CSetting(device, DS4Controls.DpadRight); setting.UpdateSettings(false, X360Controls.WDOWN, "", DS4KeyType.None); setting = getDS4CSetting(device, DS4Controls.DpadDown); setting.UpdateSettings(false, X360Controls.Unbound, "", DS4KeyType.None); setting = getDS4CSetting(device, DS4Controls.DpadLeft); setting.UpdateSettings(false, X360Controls.WUP, "", DS4KeyType.None); setting = getDS4CSetting(device, DS4Controls.Cross); setting.UpdateSettings(false, KeyInterop.VirtualKeyFromKey(Key.Space), "", DS4KeyType.None); setting = getDS4CSetting(device, DS4Controls.Square); setting.UpdateSettings(false, KeyInterop.VirtualKeyFromKey(Key.F), "", DS4KeyType.None); setting = getDS4CSetting(device, DS4Controls.Triangle); setting.UpdateSettings(false, KeyInterop.VirtualKeyFromKey(Key.E), "", DS4KeyType.None); setting = getDS4CSetting(device, DS4Controls.Circle); setting.UpdateSettings(false, KeyInterop.VirtualKeyFromKey(Key.C), "", DS4KeyType.None); setting = getDS4CSetting(device, DS4Controls.L1); setting.UpdateSettings(false, KeyInterop.VirtualKeyFromKey(Key.Q), "", DS4KeyType.None); setting = getDS4CSetting(device, DS4Controls.L2); setting.UpdateSettings(false, X360Controls.RightMouse, "", DS4KeyType.None); setting = getDS4CSetting(device, DS4Controls.R1); setting.UpdateSettings(false, KeyInterop.VirtualKeyFromKey(Key.R), "", DS4KeyType.None); setting = getDS4CSetting(device, DS4Controls.R2); setting.UpdateSettings(false, X360Controls.LeftMouse, "", DS4KeyType.None); setting = getDS4CSetting(device, DS4Controls.Share); setting.UpdateSettings(false, KeyInterop.VirtualKeyFromKey(Key.Tab), "", DS4KeyType.None); setting = getDS4CSetting(device, DS4Controls.Options); setting.UpdateSettings(false, KeyInterop.VirtualKeyFromKey(Key.Escape), "", DS4KeyType.None); // If a device exists, make sure to transfer relevant profile device // options to device instance if (postLoad && device < Global.MAX_DS4_CONTROLLER_COUNT) { PostLoadSnippet(device, control, xinputStatus, xinputPlug); } } private void CheckOldDevicestatus(int device, ControlService control, OutContType oldContType, out bool xinputPlug, out bool xinputStatus) { xinputPlug = false; xinputStatus = false; if (device < Global.MAX_DS4_CONTROLLER_COUNT) { bool oldUseDInputOnly = Global.useDInputOnly[device]; DS4Device tempDevice = control.DS4Controllers[device]; bool exists = tempBool = (tempDevice != null); bool synced = tempBool = exists ? tempDevice.isSynced() : false; bool isAlive = tempBool = exists ? tempDevice.IsAlive() : false; if (dinputOnly[device] != oldUseDInputOnly) { if (dinputOnly[device] == true) { xinputPlug = false; xinputStatus = true; } else if (synced && isAlive) { xinputPlug = true; xinputStatus = true; } } else if (!dinputOnly[device] && oldContType != outputDevType[device]) { xinputPlug = true; xinputStatus = true; } } } private void PostLoadSnippet(int device, ControlService control, bool xinputStatus, bool xinputPlug) { DS4Device tempDev = control.DS4Controllers[device]; if (tempDev != null && tempDev.isSynced()) { tempDev.queueEvent(() => { tempDev.setIdleTimeout(idleDisconnectTimeout[device]); tempDev.setBTPollRate(btPollRate[device]); if (xinputStatus && xinputPlug) { OutputDevice tempOutDev = control.outputDevices[device]; if (tempOutDev != null) { tempOutDev = null; //Global.activeOutDevType[device] = OutContType.None; control.UnplugOutDev(device, tempDev); } OutContType tempContType = outputDevType[device]; control.PluginOutDev(device, tempDev); //Global.useDInputOnly[device] = false; } else if (xinputStatus && !xinputPlug) { //Global.activeOutDevType[device] = OutContType.None; control.UnplugOutDev(device, tempDev); } tempDev.RumbleAutostopTime = rumbleAutostopTime[device]; tempDev.setRumble(0, 0); tempDev.LightBarColor = Global.getMainColor(device); }); Program.rootHub.touchPad[device]?.ResetTrackAccel(trackballFriction[device]); } } } public class SpecialAction { public enum ActionTypeId { None, Key, Program, Profile, Macro, DisconnectBT, BatteryCheck, MultiAction, XboxGameDVR, SASteeringWheelEmulationCalibrate } public string name; public List<DS4Controls> trigger = new List<DS4Controls>(); public string type; public ActionTypeId typeID; public string controls; public List<int> macro = new List<int>(); public string details; public List<DS4Controls> uTrigger = new List<DS4Controls>(); public string ucontrols; public double delayTime = 0; public string extra; public bool pressRelease = false; public DS4KeyType keyType; public bool tappedOnce = false; public bool firstTouch = false; public bool secondtouchbegin = false; public DateTime pastTime; public DateTime firstTap; public DateTime TimeofEnd; public bool automaticUntrigger = false; public string prevProfileName; // Name of the previous profile where automaticUntrigger would jump back to (could be regular or temporary profile. Empty name is the same as regular profile) public bool synchronized = false; // If the same trigger has both "key down" and "key released" macros then run those synchronized if this attribute is TRUE (ie. key down macro fully completed before running the key release macro) public bool keepKeyState = false; // By default special action type "Macro" resets all keys used in the macro back to default "key up" state after completing the macro even when the macro itself doesn't do it explicitly. If this is TRUE then key states are NOT reset automatically (macro is expected to do it or to leave a key to down state on purpose) public SpecialAction(string name, string controls, string type, string details, double delay = 0, string extras = "") { this.name = name; this.type = type; this.typeID = ActionTypeId.None; this.controls = controls; delayTime = delay; string[] ctrls = controls.Split('/'); foreach (string s in ctrls) trigger.Add(getDS4ControlsByName(s)); if (type == "Key") { typeID = ActionTypeId.Key; this.details = details.Split(' ')[0]; if (!string.IsNullOrEmpty(extras)) { string[] exts = extras.Split('\n'); pressRelease = exts[0] == "Release"; this.ucontrols = exts[1]; string[] uctrls = exts[1].Split('/'); foreach (string s in uctrls) uTrigger.Add(getDS4ControlsByName(s)); } if (details.Contains("Scan Code")) keyType |= DS4KeyType.ScanCode; } else if (type == "Program") { typeID = ActionTypeId.Program; this.details = details; if (extras != string.Empty) extra = extras; } else if (type == "Profile") { typeID = ActionTypeId.Profile; this.details = details; if (extras != string.Empty) { extra = extras; } } else if (type == "Macro") { typeID = ActionTypeId.Macro; string[] macs = details.Split('/'); foreach (string s in macs) { int v; if (int.TryParse(s, out v)) macro.Add(v); } if (extras.Contains("Scan Code")) keyType |= DS4KeyType.ScanCode; if (extras.Contains("RunOnRelease")) pressRelease = true; if (extras.Contains("Sync")) synchronized = true; if (extras.Contains("KeepKeyState")) keepKeyState = true; if (extras.Contains("Repeat")) keyType |= DS4KeyType.RepeatMacro; } else if (type == "DisconnectBT") { typeID = ActionTypeId.DisconnectBT; } else if (type == "BatteryCheck") { typeID = ActionTypeId.BatteryCheck; string[] dets = details.Split('|'); this.details = string.Join(",", dets); } else if (type == "MultiAction") { typeID = ActionTypeId.MultiAction; this.details = details; } else if (type == "XboxGameDVR") { this.typeID = ActionTypeId.XboxGameDVR; string[] dets = details.Split(','); List<string> macros = new List<string>(); //string dets = ""; int typeT = 0; for (int i = 0; i < 3; i++) { if (int.TryParse(dets[i], out typeT)) { switch (typeT) { case 0: macros.Add("91/71/71/91"); break; case 1: macros.Add("91/164/82/82/164/91"); break; case 2: macros.Add("91/164/44/44/164/91"); break; case 3: macros.Add(dets[3] + "/" + dets[3]); break; case 4: macros.Add("91/164/71/71/164/91"); break; } } } this.type = "MultiAction"; type = "MultiAction"; this.details = string.Join(",", macros); } else if (type == "SASteeringWheelEmulationCalibrate") { typeID = ActionTypeId.SASteeringWheelEmulationCalibrate; } else this.details = details; if (type != "Key" && !string.IsNullOrEmpty(extras)) { this.ucontrols = extras; string[] uctrls = extras.Split('/'); foreach (string s in uctrls) { if (s == "AutomaticUntrigger") this.automaticUntrigger = true; else uTrigger.Add(getDS4ControlsByName(s)); } } } private DS4Controls getDS4ControlsByName(string key) { switch (key) { case "Share": return DS4Controls.Share; case "L3": return DS4Controls.L3; case "R3": return DS4Controls.R3; case "Options": return DS4Controls.Options; case "Up": return DS4Controls.DpadUp; case "Right": return DS4Controls.DpadRight; case "Down": return DS4Controls.DpadDown; case "Left": return DS4Controls.DpadLeft; case "L1": return DS4Controls.L1; case "R1": return DS4Controls.R1; case "Triangle": return DS4Controls.Triangle; case "Circle": return DS4Controls.Circle; case "Cross": return DS4Controls.Cross; case "Square": return DS4Controls.Square; case "PS": return DS4Controls.PS; case "Left Stick Left": return DS4Controls.LXNeg; case "Left Stick Up": return DS4Controls.LYNeg; case "Right Stick Left": return DS4Controls.RXNeg; case "Right Stick Up": return DS4Controls.RYNeg; case "Left Stick Right": return DS4Controls.LXPos; case "Left Stick Down": return DS4Controls.LYPos; case "Right Stick Right": return DS4Controls.RXPos; case "Right Stick Down": return DS4Controls.RYPos; case "L2": return DS4Controls.L2; case "R2": return DS4Controls.R2; case "Left Touch": return DS4Controls.TouchLeft; case "Multitouch": return DS4Controls.TouchMulti; case "Upper Touch": return DS4Controls.TouchUpper; case "Right Touch": return DS4Controls.TouchRight; case "Swipe Up": return DS4Controls.SwipeUp; case "Swipe Down": return DS4Controls.SwipeDown; case "Swipe Left": return DS4Controls.SwipeLeft; case "Swipe Right": return DS4Controls.SwipeRight; case "Tilt Up": return DS4Controls.GyroZNeg; case "Tilt Down": return DS4Controls.GyroZPos; case "Tilt Left": return DS4Controls.GyroXPos; case "Tilt Right": return DS4Controls.GyroXNeg; } return 0; } } }
50.501579
504
0.587665
[ "MIT" ]
DreamTheFirst/unknown
DS4Windows/DS4Control/ScpUtil.cs
335,787
C#
using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using System; using System.Collections.Generic; using System.Net.NetworkInformation; using System.Text; namespace Titan.Entity { public class TitanDbContext:DbContext { public TitanDbContext(DbContextOptions options) : base(options) { } //public TitanDbContext() //{ //} //protected override void OnConfiguring(DbContextOptionsBuilder builder) //{ // builder.UseSqlServer("Server=DESKTOP-KK1QB16;Database=TitanDb;Trusted_Connection=True"); // base.OnConfiguring(builder); //} public DbSet<TestEntity> TestEntitys { get; set; } } }
22.787879
102
0.647606
[ "MIT" ]
Kasunjith-Bimal/Titan
Titan.Entity/TitanDbContext.cs
754
C#
// (c) Copyright HutongGames, LLC 2010-2011. All rights reserved. #if (UNITY_4_3 || UNITY_4_5 || UNITY_4_6 || UNITY_4_7 || UNITY_5_0) #define UNITY_PRE_5_1 #endif using System; using UnityEditor; using UnityEditorInternal; using UnityEngine; namespace HutongGames.PlayMakerEditor { /// <summary> /// Welcome Window with getting started shortcuts /// </summary> [InitializeOnLoad] public class PlayMakerWelcomeWindow : EditorWindow { private const string installCurrentVersion = "1.7.8.4"; private const string installBetaVersion = "1.8.0 BETA RC42"; private const string editorPrefsLastVersion = "PlayMaker.LastVersion"; private const string editorPrefsShowAtStartup = "PlayMaker.ShowWelcomeScreen"; private const string editorPrefsSavedPage = "PlayMaker.WelcomeScreenPage"; private const string editorPrefsShowUpgradeGuide = "PlayMaker.ShowUpgradeGuide"; private const string urlSamples = "http://www.hutonggames.com/samples.php"; private const string urlTutorials = "http://www.hutonggames.com/tutorials.html"; private const string urlDocs = "https://hutonggames.fogbugz.com/default.asp?W1"; private const string urlForums = "http://hutonggames.com/playmakerforum/index.php"; private const string urlPhotonAddon = "https://hutonggames.fogbugz.com/default.asp?W928"; private const string urlAddonsWiki = "https://hutonggames.fogbugz.com/default.asp?W714"; private const string urlEcosystemWiki = "https://hutonggames.fogbugz.com/default.asp?W1181"; //private const string urlStore = "http://www.hutonggames.com/store.html"; //private const string photonID = "1786"; private const float windowWidth = 500; private const float windowHeight = 440; private const float pageTop = 70; private const float pagePadding = 95; private static bool setupPhoton; private static string currentVersion; private static string currentVersionLabel; private static string currentVersionShort; private static int majorVersion; // 1.8 -> 18 for easier comparisons private enum Page { Welcome = 0, Install = 1, GettingStarted = 2, UpgradeGuide = 3, Addons = 4 } private Page currentPage = Page.Welcome; private Page nextPage; private Rect currentPageRect; private Rect nextPageRect; private float currentPageMoveTo; private Rect headerRect; private Rect backButtonRect; private bool pageInTransition; private float transitionStartTime; private const float transitionDuration = 0.5f; private Vector2 scrollPosition; private static bool showAtStartup; private static GUIStyle playMakerHeader; private static GUIStyle labelWithWordWrap; private static GUIStyle largeTitleWithLogo; private static GUIStyle versionLabel; private static Texture samplesIcon; private static Texture docsIcon; private static Texture videosIcon; private static Texture forumsIcon; private static Texture addonsIcon; private static Texture photonIcon; private static Texture backButton; private static bool stylesInitialized; [MenuItem("PlayMaker/Welcome Screen", false, 45)] public static void OpenWelcomeWindow() { GetWindow<PlayMakerWelcomeWindow>(true); } static PlayMakerWelcomeWindow() { EditorApplication.playmodeStateChanged -= OnPlayModeChanged; EditorApplication.playmodeStateChanged += OnPlayModeChanged; showAtStartup = EditorPrefs.GetBool(editorPrefsShowAtStartup, true) || EditorPrefs.GetString(editorPrefsLastVersion, "") != installBetaVersion; if (showAtStartup) { // Delay until first update EditorApplication.update -= OpenAtStartup; EditorApplication.update += OpenAtStartup; } // Only show first time EditorPrefs.SetString(editorPrefsLastVersion, installBetaVersion); } static void OnPlayModeChanged() { //Debug.Log("OnPlayModeChanged - remove welcome callback"); // don't show welcome screen on playmode change EditorApplication.update -= OpenAtStartup; EditorApplication.playmodeStateChanged -= OnPlayModeChanged; } static void OpenAtStartup() { OpenWelcomeWindow(); EditorApplication.update -= OpenAtStartup; } public void OnEnable() { #if UNITY_PRE_5_1 title = "Welcome To PlayMaker"; #else titleContent = new GUIContent("Welcome To PlayMaker"); #endif maxSize = new Vector2(windowWidth, windowHeight); minSize = maxSize; // Try to get current playmaker version if installed GetPlayMakerVersion(); // Is PlayMakerPhotonWizard available? setupPhoton = GetType("PlayMakerPhotonWizard") != null; // Setup pages currentPageRect = new Rect(0, pageTop, windowWidth, windowHeight - pagePadding); nextPageRect = new Rect(0, pageTop, windowWidth, windowHeight - pagePadding); headerRect = new Rect(0, 0, windowWidth, 60); backButtonRect = new Rect(0, windowHeight-24, 123, 24); // Save page to survive recompile...? //currentPage = (Page)EditorPrefs.GetInt(editorPrefsPage, (int)Page.Welcome); currentPage = Page.Welcome; // We want to show the Upgrade Guide after installing // However, installation forces a recompile so we save an EditorPref var showUpgradeGuide = EditorPrefs.GetBool(editorPrefsShowUpgradeGuide, false); if (showUpgradeGuide) { //currentPage = Page.UpgradeGuide; //TODO: This was problematic, need a better solution EditorPrefs.SetBool(editorPrefsShowUpgradeGuide, false); // reset EditorUtility.DisplayDialog("PlayMaker", "Please check the Upgrade Guide for more information on this release.", "OK"); } SetPage(currentPage); Update(); } private void GetPlayMakerVersion() { var versionInfo = GetType("HutongGames.PlayMakerEditor.VersionInfo"); if (versionInfo != null) { currentVersion = versionInfo.GetMethod("GetAssemblyInformationalVersion").Invoke(null, null) as string; if (currentVersion != null) { currentVersionShort = currentVersion.Substring(0, currentVersion.LastIndexOf('.')); currentVersionLabel = "version " + currentVersionShort; majorVersion = int.Parse(currentVersionShort.Substring(0, 3).Replace(".", "")); } else { currentVersionLabel = "version unkown"; currentVersionShort = ""; majorVersion = -1; } } else { currentVersionLabel = "Not installed"; currentVersionShort = ""; majorVersion = -1; } } private void InitStyles() { if (!stylesInitialized) { playMakerHeader = new GUIStyle { normal = { background = Resources.Load("playMakerHeader") as Texture2D, textColor = Color.white }, border = new RectOffset(253, 0, 0, 0), }; largeTitleWithLogo = new GUIStyle { normal = { background = Resources.Load("logoHeader") as Texture2D, textColor = Color.white }, border = new RectOffset(60, 0, 0, 0), padding = new RectOffset(60, 0, 0, 0), margin = new RectOffset(0, 0, 0, 0), contentOffset = new Vector2(0, 0), alignment = TextAnchor.MiddleLeft, fixedHeight = 60, fontSize = 36, fontStyle = FontStyle.Bold, }; labelWithWordWrap = new GUIStyle(EditorStyles.label) { wordWrap = true }; versionLabel = new GUIStyle(EditorStyles.label) { alignment = TextAnchor.LowerRight}; samplesIcon = (Texture) Resources.Load("linkSamples"); videosIcon = (Texture) Resources.Load("linkVideos"); docsIcon = (Texture) Resources.Load("linkDocs"); forumsIcon = (Texture) Resources.Load("linkForums"); addonsIcon = (Texture) Resources.Load("linkAddons"); photonIcon = (Texture) Resources.Load("photonIcon"); backButton = (Texture) Resources.Load("backButton"); } stylesInitialized = true; } public void OnGUI() { InitStyles(); GUILayout.BeginVertical(); DoHeader(); GUILayout.BeginVertical(); DoPage(currentPage, currentPageRect); if (pageInTransition) { DoPage(nextPage, nextPageRect); } // Bottom line GUILayout.FlexibleSpace(); GUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); var show = GUILayout.Toggle(showAtStartup, "Show At Startup"); if (show != showAtStartup) { showAtStartup = show; EditorPrefs.SetBool(editorPrefsShowAtStartup, showAtStartup); } GUILayout.Space(10); GUILayout.EndHorizontal(); GUILayout.EndVertical(); GUILayout.EndVertical(); if (currentPage != Page.Welcome && !pageInTransition) { DoBackButton(Page.Welcome); } } private void DoHeader() { switch (nextPage) { case Page.Welcome: GUI.Box(headerRect, "", playMakerHeader); break; case Page.Install: GUI.Box(headerRect, "Installation", largeTitleWithLogo); break; case Page.GettingStarted: GUI.Box(headerRect, "Getting Started", largeTitleWithLogo); break; case Page.UpgradeGuide: GUI.Box(headerRect, "Upgrade Guide", largeTitleWithLogo); break; case Page.Addons: GUI.Box(headerRect, "Add-Ons", largeTitleWithLogo); break; default: throw new ArgumentOutOfRangeException(); } // Version if (!string.IsNullOrEmpty(currentVersion) && majorVersion > 17) { GUI.Box(headerRect, currentVersionLabel, versionLabel); } // reserve space in layout GUILayoutUtility.GetRect(position.width, 60); } private void DoPage(Page page, Rect pageRect) { pageRect.height = position.height - pagePadding; GUILayout.BeginArea(pageRect); switch (page) { case Page.Welcome: DoWelcomePage(); break; case Page.Install: DoInstallPage(); break; case Page.GettingStarted: DoGettingStartedPage(); break; case Page.UpgradeGuide: DoUpgradeGuidePage(); break; case Page.Addons: DoAddonsPage(); break; } GUILayout.EndArea(); } private void DoWelcomePage() { GUILayout.BeginVertical(); GUILayout.FlexibleSpace(); DrawLink(samplesIcon, "Install PlayMaker", "Import the latest version of PlayMaker.", GotoPage, Page.Install); DrawLink(docsIcon, "Upgrade Guide", "Guide to upgrading Unity/PlayMaker.", GotoPage, Page.UpgradeGuide); DrawLink(videosIcon, "Getting Started", "Links to samples, tutorials, forums etc.", GotoPage, Page.GettingStarted); DrawLink(addonsIcon, "Add-Ons", "Extend PlayMaker with these powerful add-ons.", GotoPage, Page.Addons); GUILayout.FlexibleSpace(); GUILayout.EndVertical(); } private void DoInstallPage() { ShowBackupHelpBox(); GUILayout.BeginVertical(); GUILayout.Space(30); DrawLink(samplesIcon, "Install PlayMaker " + installCurrentVersion, "The current official release.", InstallLatest, null); DrawLink(samplesIcon, "Install PlayMaker " + installBetaVersion, "The latest public beta version.", InstallBeta, null); GUILayout.FlexibleSpace(); GUILayout.EndVertical(); } private void DoGettingStartedPage() { GUILayout.BeginVertical(); GUILayout.FlexibleSpace(); DrawLink(samplesIcon, "Samples", "Download sample scenes and complete projects.", OpenUrl, urlSamples); DrawLink(videosIcon, "Tutorials", "Watch tutorials on the PlayMaker YouTube channel.", OpenUrl, urlTutorials); DrawLink(docsIcon, "Docs", "Browse the online manual.", OpenUrl, urlDocs); DrawLink(forumsIcon, "Forums", "Join the PlayMaker community!", OpenUrl, urlForums); GUILayout.FlexibleSpace(); GUILayout.EndVertical(); } private void DoUpgradeGuidePage() { ShowBackupHelpBox(); scrollPosition = EditorGUILayout.BeginScrollView(scrollPosition); GUILayout.Label("Version 1.8.0", EditorStyles.boldLabel); EditorGUILayout.HelpBox("FSMs saved with 1.8.0 cannot be opened in earlier versions of PlayMaker! Please BACKUP projects!", MessageType.Warning); GUILayout.Label("Unity 5 Upgrade Notes", EditorStyles.boldLabel); EditorGUILayout.HelpBox("If you run into problems updating a Unity 4.x project please check the Troubleshooting guide on the PlayMaker Wiki.", MessageType.Warning); EditorGUILayout.HelpBox("Unity 5 removed component property shortcuts from GameObject. " + "\n\nThe Unity auto update process replaces these properties with GetComponent calls. " + "In many cases this is fine, but some third party actions and addons might need manual updating! " + "Please post on the PlayMaker forums and contact the original authors for help." + "\n\nIf you used these GameObject properties in Get Property or Set Property actions " + "they are no longer valid, and you need to instead point to the Component directly. " + "E.g., Drag the Component (NOT the GameObject) into the Target Object field." + "\n", MessageType.Warning); GUILayout.Label("Unity 4.6 Upgrade Notes", EditorStyles.boldLabel); EditorGUILayout.HelpBox("Find support for the new Unity GUI online in our Addons page.", MessageType.Info); EditorGUILayout.HelpBox("PlayMakerGUI is only needed if you use OnGUI Actions. " + "If you don't use OnGUI actions un-check Auto-Add PlayMakerGUI in PlayMaker Preferences.", MessageType.Info); EditorGUILayout.EndScrollView(); //FsmEditorGUILayout.Divider(); } private void DoAddonsPage() { GUILayout.BeginVertical(); GUILayout.FlexibleSpace(); DrawLink(addonsIcon, "Ecosystem", "An integrated online browser for custom actions, samples and addons.", OpenUrl, urlEcosystemWiki); DrawLink(addonsIcon, "Add-Ons", "Find action packs and add-ons for NGUI, 2D Toolkit, Mecanim, Pathfinding, Smooth Moves, Ultimate FPS...", OpenUrl, urlAddonsWiki); if (setupPhoton) { DrawLink(photonIcon, "Photon Cloud", "Build scalable MMOGs, FPS or any other multiplayer game " + "and application for PC, Mac, Browser, Mobile or Console.", LaunchPhotonSetupWizard, null); } else { DrawLink(photonIcon, "Photon Cloud", "Build scalable MMOGs, FPS or any other multiplayer game " + "and application for PC, Mac, Browser, Mobile or Console.", OpenUrl, urlPhotonAddon); } GUILayout.FlexibleSpace(); GUILayout.EndVertical(); } private static void ShowBackupHelpBox() { GUILayout.BeginHorizontal(); EditorGUILayout.HelpBox("Always BACKUP projects before updating!\nUse Version Control to manage changes!", MessageType.Error); GUILayout.Space(5); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); EditorGUILayout.HelpBox("With Unity 5.3 please install the 1.8.0 Beta Version to address compatibility issues!", MessageType.Error); GUILayout.Space(5); GUILayout.EndHorizontal(); } private static void DrawLink(Texture texture, string heading, string body, LinkFunction func, object userData) { GUILayout.BeginHorizontal(); GUILayout.Space(64); GUILayout.Box(texture, GUIStyle.none, GUILayout.MaxWidth(48)); GUILayout.Space(10); GUILayout.BeginVertical(); GUILayout.Space(1); GUILayout.Label(heading, EditorStyles.boldLabel); GUILayout.Label(body, labelWithWordWrap); GUILayout.EndVertical(); GUILayout.EndHorizontal(); var rect = GUILayoutUtility.GetLastRect(); EditorGUIUtility.AddCursorRect(rect, MouseCursor.Link); if (Event.current.type == EventType.mouseDown && rect.Contains(Event.current.mousePosition)) { func(userData); GUIUtility.ExitGUI(); } GUILayout.Space(10); } private void DoBackButton(Page toPage) { GUI.Box(backButtonRect, backButton, GUIStyle.none); EditorGUIUtility.AddCursorRect(backButtonRect, MouseCursor.Link); if (Event.current.type == EventType.mouseDown && backButtonRect.Contains(Event.current.mousePosition)) { GotoPage(toPage); GUIUtility.ExitGUI(); } } void Update() { if (pageInTransition) { DoPageTransition(); } } void DoPageTransition() { var t = (Time.realtimeSinceStartup - transitionStartTime) / transitionDuration; if (t > 1f) { SetPage(nextPage); return; } var nextPageX = Mathf.SmoothStep(nextPageRect.x, 0, t); var currentPageX = Mathf.SmoothStep(currentPageRect.x, currentPageMoveTo, t); currentPageRect.Set(currentPageX, pageTop, windowWidth, position.height); nextPageRect.Set(nextPageX, pageTop, windowWidth, position.height); Repaint(); } bool DisplayInstallDialog(string versionInfo, string notes) { return EditorUtility.DisplayDialog("PlayMaker", "Install PlayMaker " + versionInfo + "\n" + notes + "\n\nAlways backup projects before updating Unity or PlayMaker!", "I Made a Backup. Go Ahead!", "Cancel"); } // Button actions: public delegate void LinkFunction(object userData); private void InstallLatest(object userData) { if (majorVersion > 17 && EditorUtility.DisplayDialog("PlayMaker", "This project uses a newer version of PlayMaker not compatible with 1.7.8.4. Installing 1.7.8.4 is NOT a good idea!", "Cancel", "Do it anyway!")) { return; } if (DisplayInstallDialog(installCurrentVersion, "The latest release version of PlayMaker.")) { EditorPrefs.SetBool(editorPrefsShowUpgradeGuide, true); //ImportPackage("Assets/PlayMaker/Editor/Install/PlayMaker.1.7.8.4.unitypackage"); // Use GUID in case user has moved Playmaker folder ImportPackage(AssetDatabase.GUIDToAssetPath("dd583cbbf618ba54983cdf396b28e49b")); } } private void InstallBeta(object userData) { if (DisplayInstallDialog(installBetaVersion, "The latest BETA version of PlayMaker." + "\n\nNOTE: Projects saved with PlayMaker 1.8.0 cannot be opened in older versions of PlayMaker!")) { EditorPrefs.SetBool(editorPrefsShowUpgradeGuide, true); //ImportPackage("Assets/PlayMaker/Editor/Install/PlayMaker.1.8.0.unitypackage"); // Use GUID in case user has moved Playmaker folder ImportPackage(AssetDatabase.GUIDToAssetPath("f982487afa4f0444ea11e90a9d05b94e")); } } private void ImportPackage(string package) { try { AssetDatabase.ImportPackage(package, true); } catch (Exception) { Debug.LogError("Failed to import package: " + package); throw; } // This didn't work that well // Instead let the user open the upgrade guide //GotoPage(Page.UpgradeGuide); } private void LaunchPhotonSetupWizard(object userData) { GetType("PlayMakerPhotonWizard").GetMethod("Init").Invoke(null, null); } private void OpenUrl(object userData) { Application.OpenURL(userData as string); } public void OpenInAssetStore(object userData) { AssetStore.Open("content/" + userData); } private void GotoPage(object userData) { nextPage = (Page)userData; pageInTransition = true; transitionStartTime = Time.realtimeSinceStartup; // next page slides in from the right // welcome screen slides offscreen left // reversed if returning to the welcome screen if (nextPage == Page.Welcome) { nextPageRect.x = -windowWidth; currentPageMoveTo = windowWidth; } else { nextPageRect.x = windowWidth; currentPageMoveTo = -windowWidth; } GUIUtility.ExitGUI(); } private void SetPage(Page page) { currentPage = page; nextPage = page; pageInTransition = false; currentPageRect.x = 0; SaveCurrentPage(); Repaint(); } private void SaveCurrentPage() { EditorPrefs.SetInt(editorPrefsSavedPage, (int)currentPage); } // Normally we would use ReflectionUtils.GetGlobalType but this window now needs to be standalone // Instead of copy/pasting ReflectionUtils, decided to try this code from UnityAnswers: // http://answers.unity3d.com/questions/206665/typegettypestring-does-not-work-in-unity.html public static Type GetType(string typeName) { // Try Type.GetType() first. This will work with types defined // by the Mono runtime, in the same assembly as the caller, etc. var type = Type.GetType(typeName); // If it worked, then we're done here if (type != null) return type; // otherwise look in loaded assemblies foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies()) { type = assembly.GetType(typeName); if (type != null) { break; } } return type; } public static Type FindTypeInLoadedAssemblies(string typeName) { Type _type = null; foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies()) { _type = assembly.GetType(typeName); if (_type != null) break; } return _type; } } }
36.755216
223
0.550687
[ "MIT" ]
TristanIbanezFiveSides/FourSides
Assets/PlayMaker/Editor/PlayMakerWelcomeWindow.cs
26,429
C#
using Chloe.DbExpressions; using Chloe.RDBMS; using System; namespace Chloe.MySql.MethodHandlers { class Parse_Handler : IMethodHandler { public bool CanProcess(DbMethodCallExpression exp) { if (exp.Arguments.Count != 1) return false; DbExpression arg = exp.Arguments[0]; if (arg.Type != PublicConstants.TypeOfString) return false; Type retType = exp.Method.ReturnType; if (exp.Method.DeclaringType != retType) return false; return true; } public void Process(DbMethodCallExpression exp, SqlGeneratorBase generator) { DbExpression arg = exp.Arguments[0]; DbExpression e = DbExpression.Convert(arg, exp.Method.ReturnType); if (exp.Method.ReturnType == PublicConstants.TypeOfBoolean) { e.Accept(generator); generator.SqlBuilder.Append(" = "); DbConstantExpression.True.Accept(generator); } else e.Accept(generator); } } }
29.25641
83
0.565294
[ "MIT" ]
johnnyleecn/Chloe
src/Chloe.MySql/MethodHandlers/Parse_Handler.cs
1,143
C#
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using System.Web.Http; namespace jack_sparrow.api.Results { public class ChallengeResult : IHttpActionResult { public ChallengeResult(string loginProvider, ApiController controller) { LoginProvider = loginProvider; Request = controller.Request; } public string LoginProvider { get; set; } public HttpRequestMessage Request { get; set; } public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken) { Request.GetOwinContext().Authentication.Challenge(LoginProvider); HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.Unauthorized); response.RequestMessage = Request; return Task.FromResult(response); } } }
29.181818
96
0.694704
[ "MIT" ]
stone-pagamentos/jack-sparrow
jack-sparrow.api/Results/ChallengeResult.cs
965
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.HttpsPolicy; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; namespace MQTT_API { public class Startup { public Startup(IConfiguration configuration) { MQTT.Init(); //Initialises the MQTT client Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseMvc(); } } }
31.52
143
0.658629
[ "MIT" ]
arkeror/MQTT-API
MQTT API/Startup.cs
1,578
C#
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.Windows; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Adornments; namespace Microsoft.VisualStudio.Language.Intellisense { /// <summary> /// Defines an IntelliSense presenter that is rendered as a popup within an /// <see cref="Microsoft.VisualStudio.Text.Editor.ITextView"/>. /// </summary> public interface IPopupIntellisensePresenter : IIntellisensePresenter { /// <summary> /// Gets the WPF <see cref="UIElement"/> that the presenter wants to be displayed inside a /// <see cref="Microsoft.VisualStudio.Text.Editor.ITextView"/> popup. /// </summary> UIElement SurfaceElement { get; } /// <summary> /// Occurs when the WPF SurfaceElement is changed. /// </summary> event EventHandler SurfaceElementChanged; /// <summary> /// Gets the <see cref="ITrackingSpan"/> to which this presenter is related. /// </summary> /// <remarks> /// This property is used to determine where to /// place the <see cref="Microsoft.VisualStudio.Text.Editor.ITextView"/> popup inside of which the presenter's /// SurfaceElement is hosted. /// </remarks> ITrackingSpan PresentationSpan { get; } /// <summary> /// Occurs when the PresentationSpan property changes. /// </summary> /// <remarks> /// This is the way popup presenters signal that they should be moved. /// </remarks> event EventHandler PresentationSpanChanged; /// <summary> /// Gets a set of flags that determine the popup style. /// </summary> PopupStyles PopupStyles { get; } /// <summary> /// Occurs when the PopupStyles property changes. /// </summary> event EventHandler<ValueChangedEventArgs<PopupStyles>> PopupStylesChanged; /// <summary> /// Gets the name of the space reservation manager that should be used to create popups for this presenter. /// </summary> /// <remarks> /// Space reservation /// managers can be ordered, thus ensuring predictable popup placement. /// </remarks> string SpaceReservationManagerName { get; } /// <summary> /// Gets or sets the opacity of this popup presenter. /// </summary> /// <remarks> /// The presenter should use this property to set the /// opacity of its surface element and of any other text-obscuring UI elements it has provided. /// </remarks> double Opacity { get; set; } } }
39.342105
133
0.562542
[ "MIT" ]
Microsoft/vs-editor-api
src/Editor/Language/Def/Intellisense/IPopupIntellisensePresenter.cs
2,992
C#
using ContestExecution.App.Data; using ContestExecution.App.Common; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using System.Windows.Input; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; // The Universal Hub Application project template is documented at http://go.microsoft.com/fwlink/?LinkID=391955 namespace ContestExecution.App { /// <summary> /// A page that displays details for a single item within a group. /// </summary> public sealed partial class ItemPage : Page { private NavigationHelper navigationHelper; private ObservableDictionary defaultViewModel = new ObservableDictionary(); public ItemPage() { this.InitializeComponent(); this.navigationHelper = new NavigationHelper(this); this.navigationHelper.LoadState += this.NavigationHelper_LoadState; } /// <summary> /// Gets the NavigationHelper used to aid in navigation and process lifetime management. /// </summary> public NavigationHelper NavigationHelper { get { return this.navigationHelper; } } /// <summary> /// Gets the DefaultViewModel. This can be changed to a strongly typed view model. /// </summary> public ObservableDictionary DefaultViewModel { get { return this.defaultViewModel; } } /// <summary> /// Populates the page with content passed during navigation. Any saved state is also /// provided when recreating a page from a prior session. /// </summary> /// <param name="sender"> /// The source of the event; typically <see cref="NavigationHelper"/> /// </param> /// <param name="e">Event data that provides both the navigation parameter passed to /// <see cref="Frame.Navigate(Type, object)"/> when this page was initially requested and /// a dictionary of state preserved by this page during an earlier /// session. The state will be null the first time a page is visited.</param> private async void NavigationHelper_LoadState(object sender, LoadStateEventArgs e) { // TODO: Create an appropriate data model for your problem domain to replace the sample data var item = await SampleDataSource.GetItemAsync((string)e.NavigationParameter); this.DefaultViewModel["Item"] = item; } #region NavigationHelper registration /// <summary> /// The methods provided in this section are simply used to allow /// NavigationHelper to respond to the page's navigation methods. /// Page specific logic should be placed in event handlers for the /// <see cref="Common.NavigationHelper.LoadState"/> /// and <see cref="Common.NavigationHelper.SaveState"/>. /// The navigation parameter is available in the LoadState method /// in addition to page state preserved during an earlier session. /// </summary> protected override void OnNavigatedTo(NavigationEventArgs e) { this.navigationHelper.OnNavigatedTo(e); } protected override void OnNavigatedFrom(NavigationEventArgs e) { this.navigationHelper.OnNavigatedFrom(e); } #endregion } }
38.25
112
0.66585
[ "MIT" ]
KBVStollhamm/Ramp-Festival
ContestExecution.App/ContestExecution.App.Windows/ItemPage.xaml.cs
3,674
C#
/** * This file is part of OmniAPI, licensed under the MIT License (MIT). * * Copyright (c) 2017 Helion3 http://helion3.com/ * * 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 OmniAPI.Items; namespace OmniAPI.Services.Economy { /// <summary> /// Represents merchandise - an item with an associated currency value. /// </summary> public class Merchandise { /// <summary> /// The item available for trade. The currently available quantity /// is maintained as the quantity field on this Item. /// </summary> public readonly Item Item; /// <summary> /// The cost paid *TO* someone selling this item to this merchant. /// </summary> public readonly float BuyCost; /// <summary> /// The price paid *BY* someone buying this item from this merchant. /// </summary> public readonly float SellCost; public Merchandise(Item item, float buyCost, float sellCost) { this.Item = item; this.BuyCost = buyCost; this.SellCost = sellCost; } } }
39.722222
80
0.682051
[ "MIT" ]
OutpostOmni/OmniAPI
OmniAPI/Services/Economy/Merchandise.cs
2,147
C#
using System; using MikhailKhalizev.Processor.x86.BinToCSharp; namespace MikhailKhalizev.Max.Program { public partial class RawProgram { [MethodInfo("0x100a_9f78-803b37a8")] public void Method_100a_9f78() { ii(0x100a_9f78, 5); push(0x24); /* push 0x24 */ ii(0x100a_9f7d, 5); call(Definitions.sys_check_available_stack_size, 0xb_bdd0);/* call 0x10165d52 */ ii(0x100a_9f82, 1); push(ebx); /* push ebx */ ii(0x100a_9f83, 1); push(ecx); /* push ecx */ ii(0x100a_9f84, 1); push(esi); /* push esi */ ii(0x100a_9f85, 1); push(edi); /* push edi */ ii(0x100a_9f86, 1); push(ebp); /* push ebp */ ii(0x100a_9f87, 2); mov(ebp, esp); /* mov ebp, esp */ ii(0x100a_9f89, 6); sub(esp, 0xc); /* sub esp, 0xc */ ii(0x100a_9f8f, 3); mov(memd[ss, ebp - 8], eax); /* mov [ebp-0x8], eax */ ii(0x100a_9f92, 3); mov(memd[ss, ebp - 4], edx); /* mov [ebp-0x4], edx */ ii(0x100a_9f95, 3); mov(edi, memd[ss, ebp - 8]); /* mov edi, [ebp-0x8] */ ii(0x100a_9f98, 3); mov(esi, memd[ss, ebp - 4]); /* mov esi, [ebp-0x4] */ ii(0x100a_9f9b, 1); movsd(); /* movsd */ ii(0x100a_9f9c, 1); movsd(); /* movsd */ ii(0x100a_9f9d, 1); movsd(); /* movsd */ ii(0x100a_9f9e, 3); mov(eax, memd[ss, ebp - 8]); /* mov eax, [ebp-0x8] */ ii(0x100a_9fa1, 3); mov(memd[ss, ebp - 12], eax); /* mov [ebp-0xc], eax */ ii(0x100a_9fa4, 3); mov(eax, memd[ss, ebp - 12]); /* mov eax, [ebp-0xc] */ ii(0x100a_9fa7, 2); mov(esp, ebp); /* mov esp, ebp */ ii(0x100a_9fa9, 1); pop(ebp); /* pop ebp */ ii(0x100a_9faa, 1); pop(edi); /* pop edi */ ii(0x100a_9fab, 1); pop(esi); /* pop esi */ ii(0x100a_9fac, 1); pop(ecx); /* pop ecx */ ii(0x100a_9fad, 1); pop(ebx); /* pop ebx */ ii(0x100a_9fae, 1); ret(); /* ret */ } } }
65.625
114
0.394667
[ "Apache-2.0" ]
mikhail-khalizev/max
source/MikhailKhalizev.Max/source/Program/Auto/z-100a-9f78.cs
2,625
C#
// ========================================================================== // Squidex Headless CMS // ========================================================================== // Copyright (c) Squidex UG (haftungsbeschraenkt) // All rights reserved. Licensed under the MIT license. // ========================================================================== using System; using System.Collections.Generic; using System.IO; using System.Threading; using System.Threading.Tasks; using FakeItEasy; using Squidex.Domain.Apps.Core.Tags; using Squidex.Domain.Apps.Entities.Assets.State; using Squidex.Domain.Apps.Entities.Backup; using Squidex.Domain.Apps.Events.Assets; using Squidex.Infrastructure; using Squidex.Infrastructure.Commands; using Squidex.Infrastructure.EventSourcing; using Squidex.Infrastructure.Tasks; using Xunit; #pragma warning disable IDE0067 // Dispose objects before losing scope namespace Squidex.Domain.Apps.Entities.Assets { public class BackupAssetsTests { private readonly Rebuilder rebuilder = A.Fake<Rebuilder>(); private readonly IAssetFileStore assetFileStore = A.Fake<IAssetFileStore>(); private readonly ITagService tagService = A.Fake<ITagService>(); private readonly Guid appId = Guid.NewGuid(); private readonly RefToken actor = new RefToken(RefTokenType.Subject, "123"); private readonly BackupAssets sut; public BackupAssetsTests() { sut = new BackupAssets(rebuilder, assetFileStore, tagService); } [Fact] public void Should_provide_name() { Assert.Equal("Assets", sut.Name); } [Fact] public async Task Should_writer_tags() { var tags = new TagsExport(); var context = CreateBackupContext(); A.CallTo(() => tagService.GetExportableTagsAsync(appId, TagGroups.Assets)) .Returns(tags); await sut.BackupAsync(context); A.CallTo(() => context.Writer.WriteJsonAsync(A<string>.Ignored, tags)) .MustHaveHappened(); } [Fact] public async Task Should_read_tags() { var tags = new TagsExport(); var context = CreateRestoreContext(); A.CallTo(() => context.Reader.ReadJsonAttachmentAsync<TagsExport>(A<string>.Ignored)) .Returns(tags); await sut.RestoreAsync(context); A.CallTo(() => tagService.RebuildTagsAsync(appId, TagGroups.Assets, tags)) .MustHaveHappened(); } [Fact] public async Task Should_backup_created_asset() { var @event = new AssetCreated { AssetId = Guid.NewGuid() }; await TestBackupEventAsync(@event, 0); } [Fact] public async Task Should_backup_updated_asset() { var @event = new AssetUpdated { AssetId = Guid.NewGuid(), FileVersion = 3 }; await TestBackupEventAsync(@event, @event.FileVersion); } private async Task TestBackupEventAsync(AssetEvent @event, long version) { var assetStream = new MemoryStream(); var assetId = @event.AssetId; var context = CreateBackupContext(); A.CallTo(() => context.Writer.WriteBlobAsync($"{assetId}_{version}.asset", A<Func<Stream, Task>>.Ignored)) .Invokes((string _, Func<Stream, Task> handler) => handler(assetStream)); await sut.BackupEventAsync(Envelope.Create(@event), context); A.CallTo(() => assetFileStore.DownloadAsync(assetId, version, assetStream, default)) .MustHaveHappened(); } [Fact] public async Task Should_restore_created_asset() { var @event = new AssetCreated { AssetId = Guid.NewGuid() }; await TestRestoreAsync(@event, 0); } [Fact] public async Task Should_restore_updated_asset() { var @event = new AssetUpdated { AssetId = Guid.NewGuid(), FileVersion = 3 }; await TestRestoreAsync(@event, @event.FileVersion); } private async Task TestRestoreAsync(AssetEvent @event, long version) { var oldId = Guid.NewGuid(); var assetStream = new MemoryStream(); var assetId = @event.AssetId; var context = CreateRestoreContext(); A.CallTo(() => context.Reader.OldGuid(assetId)) .Returns(oldId); A.CallTo(() => context.Reader.ReadBlobAsync($"{oldId}_{version}.asset", A<Func<Stream, Task>>.Ignored)) .Invokes((string _, Func<Stream, Task> handler) => handler(assetStream)); await sut.RestoreEventAsync(Envelope.Create(@event), context); A.CallTo(() => assetFileStore.UploadAsync(assetId, version, assetStream, default)) .MustHaveHappened(); } [Fact] public async Task Should_restore_states_for_all_assets() { var assetId1 = Guid.NewGuid(); var assetId2 = Guid.NewGuid(); var context = CreateRestoreContext(); await sut.RestoreEventAsync(Envelope.Create(new AssetCreated { AssetId = assetId1 }), context); await sut.RestoreEventAsync(Envelope.Create(new AssetCreated { AssetId = assetId2 }), context); await sut.RestoreEventAsync(Envelope.Create(new AssetDeleted { AssetId = assetId2 }), context); var rebuildAssets = new HashSet<Guid>(); var add = new Func<Guid, Task>(id => { rebuildAssets.Add(id); return TaskHelper.Done; }); A.CallTo(() => rebuilder.InsertManyAsync<AssetState, AssetGrain>(A<IdSource>.Ignored, A<CancellationToken>.Ignored)) .Invokes((IdSource source, CancellationToken _) => source(add)); await sut.RestoreAsync(context); Assert.Equal(new HashSet<Guid> { assetId1, assetId2 }, rebuildAssets); } [Fact] public async Task Should_restore_states_for_all_asset_folders() { var assetFolderId1 = Guid.NewGuid(); var assetFolderId2 = Guid.NewGuid(); var context = CreateRestoreContext(); await sut.RestoreEventAsync(Envelope.Create(new AssetFolderCreated { AssetFolderId = assetFolderId1 }), context); await sut.RestoreEventAsync(Envelope.Create(new AssetFolderCreated { AssetFolderId = assetFolderId2 }), context); await sut.RestoreEventAsync(Envelope.Create(new AssetFolderDeleted { AssetFolderId = assetFolderId2 }), context); var rebuildAssets = new HashSet<Guid>(); var add = new Func<Guid, Task>(id => { rebuildAssets.Add(id); return TaskHelper.Done; }); A.CallTo(() => rebuilder.InsertManyAsync<AssetFolderState, AssetFolderGrain>(A<IdSource>.Ignored, A<CancellationToken>.Ignored)) .Invokes((IdSource source, CancellationToken _) => source(add)); await sut.RestoreAsync(context); Assert.Equal(new HashSet<Guid> { assetFolderId1, assetFolderId2 }, rebuildAssets); } private BackupContext CreateBackupContext() { return new BackupContext(appId, CreateUserMapping(), A.Fake<IBackupWriter>()); } private RestoreContext CreateRestoreContext() { return new RestoreContext(appId, CreateUserMapping(), A.Fake<IBackupReader>()); } private IUserMapping CreateUserMapping() { var mapping = A.Fake<IUserMapping>(); A.CallTo(() => mapping.Initiator).Returns(actor); return mapping; } } }
31.984436
140
0.570195
[ "MIT" ]
lelongho89/squidex
backend/tests/Squidex.Domain.Apps.Entities.Tests/Assets/BackupAssetsTests.cs
8,222
C#
/* * Assembly API * * Assembly (formely PromisePay) is a powerful payments engine custom-built for platforms and marketplaces. * * The version of the OpenAPI document: 2.0 * Contact: support@assemblypayments.com * Generated by: https://github.com/openapitools/openapi-generator.git */ using System; using System.Collections.Generic; using System.Runtime.Serialization; using System.Text; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; namespace AssemblyPay.Sdk.Model { /// <summary> /// BankAccountRequestBody /// </summary> [DataContract(Name = "bank_account_requestBody")] public partial class BankAccountRequestBody : IEquatable<BankAccountRequestBody>, IValidatableObject { /// <summary> /// Bank account type (savings or checking) /// </summary> /// <value>Bank account type (savings or checking)</value> [JsonConverter(typeof(StringEnumConverter))] public enum AccountTypeEnum { /// <summary> /// Enum Savings for value: savings /// </summary> [EnumMember(Value = "savings")] Savings = 1, /// <summary> /// Enum Checking for value: checking /// </summary> [EnumMember(Value = "checking")] Checking = 2 } /// <summary> /// Bank account type (savings or checking) /// </summary> /// <value>Bank account type (savings or checking)</value> [DataMember(Name = "account_type", IsRequired = true, EmitDefaultValue = false)] public AccountTypeEnum AccountType { get; set; } /// <summary> /// Holder type (personal or business) /// </summary> /// <value>Holder type (personal or business)</value> [JsonConverter(typeof(StringEnumConverter))] public enum HolderTypeEnum { /// <summary> /// Enum Personal for value: personal /// </summary> [EnumMember(Value = "personal")] Personal = 1, /// <summary> /// Enum Business for value: business /// </summary> [EnumMember(Value = "business")] Business = 2 } /// <summary> /// Holder type (personal or business) /// </summary> /// <value>Holder type (personal or business)</value> [DataMember(Name = "holder_type", IsRequired = true, EmitDefaultValue = false)] public HolderTypeEnum HolderType { get; set; } /// <summary> /// Initializes a new instance of the <see cref="BankAccountRequestBody" /> class. /// </summary> [JsonConstructorAttribute] protected BankAccountRequestBody() { } /// <summary> /// Initializes a new instance of the <see cref="BankAccountRequestBody" /> class. /// </summary> /// <param name="userId">User ID (required) (default to &quot;aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee&quot;).</param> /// <param name="bankName">Bank name (required) (default to &quot;Bank of Australia&quot;).</param> /// <param name="accountName">Account name (required) (default to &quot;Samuel Seller&quot;).</param> /// <param name="routingNumber">*Required conditionally* - Routing number / SWIFT code / BSB number. See [Bank account formats by country](https://developer.assemblypayments.com/docs/input-formats). (required) (default to &quot;111123&quot;).</param> /// <param name="accountNumber">Account number / IBAN. See [Bank account formats by country](https://developer.assemblypayments.com/docs/input-formats). (required) (default to &quot;111234&quot;).</param> /// <param name="accountType">Bank account type (savings or checking) (required) (default to AccountTypeEnum.Checking).</param> /// <param name="holderType">Holder type (personal or business) (required) (default to HolderTypeEnum.Personal).</param> /// <param name="country">[ISO 3166-1 alpha-3](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-3#Officially_assigned_code_elements) country code (3 char) (required) (default to &quot;AUS&quot;).</param> /// <param name="payoutCurrency">[ISO 4217 alpha-3](https://en.wikipedia.org/wiki/ISO_4217#Active_codes) currency code. This parameter determines the currency with which funds are paid out..</param> /// <param name="currency">[ISO 4217 alpha-3](https://en.wikipedia.org/wiki/ISO_4217#Active_codes) currency code. This is an optional field and if not provided, the item will be created with the default currency of the marketplace..</param> public BankAccountRequestBody(string userId = "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee", string bankName = "Bank of Australia", string accountName = "Samuel Seller", string routingNumber = "111123", string accountNumber = "111234", AccountTypeEnum accountType = AccountTypeEnum.Checking, HolderTypeEnum holderType = HolderTypeEnum.Personal, string country = "AUS", string payoutCurrency = default(string), string currency = default(string)) { // to ensure "userId" is required (not null) if (userId == null) { throw new ArgumentNullException("userId is a required property for BankAccountRequestBody and cannot be null"); } this.UserId = userId; // to ensure "bankName" is required (not null) if (bankName == null) { throw new ArgumentNullException("bankName is a required property for BankAccountRequestBody and cannot be null"); } this.BankName = bankName; // to ensure "accountName" is required (not null) if (accountName == null) { throw new ArgumentNullException("accountName is a required property for BankAccountRequestBody and cannot be null"); } this.AccountName = accountName; // to ensure "routingNumber" is required (not null) if (routingNumber == null) { throw new ArgumentNullException("routingNumber is a required property for BankAccountRequestBody and cannot be null"); } this.RoutingNumber = routingNumber; // to ensure "accountNumber" is required (not null) if (accountNumber == null) { throw new ArgumentNullException("accountNumber is a required property for BankAccountRequestBody and cannot be null"); } this.AccountNumber = accountNumber; this.AccountType = accountType; this.HolderType = holderType; // to ensure "country" is required (not null) if (country == null) { throw new ArgumentNullException("country is a required property for BankAccountRequestBody and cannot be null"); } this.Country = country; this.PayoutCurrency = payoutCurrency; this.Currency = currency; } /// <summary> /// User ID /// </summary> /// <value>User ID</value> [DataMember(Name = "user_id", IsRequired = true, EmitDefaultValue = false)] public string UserId { get; set; } /// <summary> /// Bank name /// </summary> /// <value>Bank name</value> [DataMember(Name = "bank_name", IsRequired = true, EmitDefaultValue = false)] public string BankName { get; set; } /// <summary> /// Account name /// </summary> /// <value>Account name</value> [DataMember(Name = "account_name", IsRequired = true, EmitDefaultValue = false)] public string AccountName { get; set; } /// <summary> /// *Required conditionally* - Routing number / SWIFT code / BSB number. See [Bank account formats by country](https://developer.assemblypayments.com/docs/input-formats). /// </summary> /// <value>*Required conditionally* - Routing number / SWIFT code / BSB number. See [Bank account formats by country](https://developer.assemblypayments.com/docs/input-formats). </value> [DataMember(Name = "routing_number", IsRequired = true, EmitDefaultValue = false)] public string RoutingNumber { get; set; } /// <summary> /// Account number / IBAN. See [Bank account formats by country](https://developer.assemblypayments.com/docs/input-formats). /// </summary> /// <value>Account number / IBAN. See [Bank account formats by country](https://developer.assemblypayments.com/docs/input-formats). </value> [DataMember(Name = "account_number", IsRequired = true, EmitDefaultValue = false)] public string AccountNumber { get; set; } /// <summary> /// [ISO 3166-1 alpha-3](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-3#Officially_assigned_code_elements) country code (3 char) /// </summary> /// <value>[ISO 3166-1 alpha-3](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-3#Officially_assigned_code_elements) country code (3 char)</value> [DataMember(Name = "country", IsRequired = true, EmitDefaultValue = false)] public string Country { get; set; } /// <summary> /// [ISO 4217 alpha-3](https://en.wikipedia.org/wiki/ISO_4217#Active_codes) currency code. This parameter determines the currency with which funds are paid out. /// </summary> /// <value>[ISO 4217 alpha-3](https://en.wikipedia.org/wiki/ISO_4217#Active_codes) currency code. This parameter determines the currency with which funds are paid out.</value> [DataMember(Name = "payout_currency", EmitDefaultValue = false)] public string PayoutCurrency { get; set; } /// <summary> /// [ISO 4217 alpha-3](https://en.wikipedia.org/wiki/ISO_4217#Active_codes) currency code. This is an optional field and if not provided, the item will be created with the default currency of the marketplace. /// </summary> /// <value>[ISO 4217 alpha-3](https://en.wikipedia.org/wiki/ISO_4217#Active_codes) currency code. This is an optional field and if not provided, the item will be created with the default currency of the marketplace.</value> [DataMember(Name = "currency", EmitDefaultValue = false)] public string Currency { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("class BankAccountRequestBody {\n"); sb.Append(" UserId: ").Append(UserId).Append("\n"); sb.Append(" BankName: ").Append(BankName).Append("\n"); sb.Append(" AccountName: ").Append(AccountName).Append("\n"); sb.Append(" RoutingNumber: ").Append(RoutingNumber).Append("\n"); sb.Append(" AccountNumber: ").Append(AccountNumber).Append("\n"); sb.Append(" AccountType: ").Append(AccountType).Append("\n"); sb.Append(" HolderType: ").Append(HolderType).Append("\n"); sb.Append(" Country: ").Append(Country).Append("\n"); sb.Append(" PayoutCurrency: ").Append(PayoutCurrency).Append("\n"); sb.Append(" Currency: ").Append(Currency).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public virtual string ToJson() { return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as BankAccountRequestBody); } /// <summary> /// Returns true if BankAccountRequestBody instances are equal /// </summary> /// <param name="input">Instance of BankAccountRequestBody to be compared</param> /// <returns>Boolean</returns> public bool Equals(BankAccountRequestBody input) { if (input == null) { return false; } return ( this.UserId == input.UserId || (this.UserId != null && this.UserId.Equals(input.UserId)) ) && ( this.BankName == input.BankName || (this.BankName != null && this.BankName.Equals(input.BankName)) ) && ( this.AccountName == input.AccountName || (this.AccountName != null && this.AccountName.Equals(input.AccountName)) ) && ( this.RoutingNumber == input.RoutingNumber || (this.RoutingNumber != null && this.RoutingNumber.Equals(input.RoutingNumber)) ) && ( this.AccountNumber == input.AccountNumber || (this.AccountNumber != null && this.AccountNumber.Equals(input.AccountNumber)) ) && ( this.AccountType == input.AccountType || this.AccountType.Equals(input.AccountType) ) && ( this.HolderType == input.HolderType || this.HolderType.Equals(input.HolderType) ) && ( this.Country == input.Country || (this.Country != null && this.Country.Equals(input.Country)) ) && ( this.PayoutCurrency == input.PayoutCurrency || (this.PayoutCurrency != null && this.PayoutCurrency.Equals(input.PayoutCurrency)) ) && ( this.Currency == input.Currency || (this.Currency != null && this.Currency.Equals(input.Currency)) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.UserId != null) { hashCode = (hashCode * 59) + this.UserId.GetHashCode(); } if (this.BankName != null) { hashCode = (hashCode * 59) + this.BankName.GetHashCode(); } if (this.AccountName != null) { hashCode = (hashCode * 59) + this.AccountName.GetHashCode(); } if (this.RoutingNumber != null) { hashCode = (hashCode * 59) + this.RoutingNumber.GetHashCode(); } if (this.AccountNumber != null) { hashCode = (hashCode * 59) + this.AccountNumber.GetHashCode(); } hashCode = (hashCode * 59) + this.AccountType.GetHashCode(); hashCode = (hashCode * 59) + this.HolderType.GetHashCode(); if (this.Country != null) { hashCode = (hashCode * 59) + this.Country.GetHashCode(); } if (this.PayoutCurrency != null) { hashCode = (hashCode * 59) + this.PayoutCurrency.GetHashCode(); } if (this.Currency != null) { hashCode = (hashCode * 59) + this.Currency.GetHashCode(); } return hashCode; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> public IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> Validate(ValidationContext validationContext) { // Country (string) maxLength if (this.Country != null && this.Country.Length > 3) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Country, length must be less than 3.", new [] { "Country" }); } yield break; } } }
47.019231
445
0.572714
[ "MIT" ]
tahirahmed76/AssemblyPay.Sdk
Org.OpenAPITools/Model/BankAccountRequestBody.cs
17,115
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using System.Threading.Tasks; using System.Threading; using KHMemory; namespace KHTriggerRunner { /// <summary> /// Interaktionslogik für MainWindow.xaml /// </summary> public partial class MainWindow : Window { bool bRun = false; Thread th; public string World { get; set; } public string Room { get; set; } public string Event { get; set; } private List<string> expandedNodes = new List<string>(); public MainWindow() { InitializeComponent(); if (PCSX2_RAM.SeekPCSX2()) lblStatusPCSX2.Content = "PCSX2 found!"; else lblStatusPCSX2.Content = "PCSX2 NOT found!"; DataQuery.Instance.AllTriggers.CollectionChanged += AllTriggers_CollectionChanged; TreeViewItem groups = new TreeViewItem(); groups.Expanded += Groups_Expanded; groups.Collapsed += Groups_Collapsed; } private void Groups_Collapsed(object sender, RoutedEventArgs e) { TreeViewItem treeNode = sender as TreeViewItem; string header = treeNode.Header.ToString(); if (expandedNodes.Contains(header)) { expandedNodes.Remove(header); } } private void Groups_Expanded(object sender, RoutedEventArgs e) { TreeViewItem treeNode = sender as TreeViewItem; string header = treeNode.Header.ToString(); if (expandedNodes.Contains(header) == false) { expandedNodes.Add(header); } } private void AllTriggers_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e) { lstBoxTriggers.ItemsSource = DataQuery.Instance.AllTriggers; } private void listBox_SelectionChanged(object sender, SelectionChangedEventArgs e) { } public static void ClearTreeViewSelection(TreeView tv) { if (tv != null) ClearTreeViewItemsControlSelection(tv.Items, tv.ItemContainerGenerator); } private static void ClearTreeViewItemsControlSelection(ItemCollection ic, ItemContainerGenerator icg) { if ((ic != null) && (icg != null)) for (int i = 0; i < ic.Count; i++) { TreeViewItem tvi = icg.ContainerFromIndex(i) as TreeViewItem; if (tvi != null) { ClearTreeViewItemsControlSelection(tvi.Items, tvi.ItemContainerGenerator); tvi.IsSelected = false; } } } private void btnAddCode_Click(object sender, RoutedEventArgs e) { TriggerEdit ed = new TriggerEdit(); var item = lstBoxTriggers.SelectedItem; if (item is TriggerList) { ed.ShowNewTrigger(item as TriggerList); lstBoxTriggers.Items.Refresh(); foreach (var it in lstBoxTriggers.Items) { if (it is TriggerList) { TriggerList item2 = item as TriggerList; TriggerList bg34 = it as TriggerList; if (item2.DisplayName == bg34.DisplayName) item2.IsExpanded = true; } } } else { //trying to get parent itemlist TriggerList trytofind = DataQuery.Instance.FindParentList(item as Trigger); if (trytofind != null) ed.ShowNewTrigger(trytofind); else ed.ShowNewTrigger(); lstBoxTriggers.Items.Refresh(); foreach (var it in lstBoxTriggers.Items) { if (it is TriggerList) { TriggerList bg34 = it as TriggerList; if (trytofind.DisplayName == bg34.DisplayName) bg34.IsExpanded = true; } } } //Refresh gui //http://stackoverflow.com/questions/11540459/create-refresh-a-wpf-treeview-and-remember-expanded-nodes-without-xaml //lstBoxTriggers.UpdateLayout(); } private void lstBoxTriggers_MouseDoubleClick(object sender, MouseButtonEventArgs e) { var selected = lstBoxTriggers.SelectedItem; if (selected is Trigger) { TriggerEdit ed = new TriggerEdit(); ed.ShowEditTrigger(selected as Trigger); } } private void btnTest_Click(object sender, RoutedEventArgs e) { waiting.Visibility = Visibility.Visible; bRun = true; th = new Thread(new ThreadStart(RunLoop)); th.Start(); } private void RunLoop() { while (bRun) { RoomInformation r = ReadRoomInforation(); World= r.WorldNumber.ToString("X"); Room = r.RoomNumber.ToString("X"); Event = r.EventNumberMain.ToString("X"); foreach (var item in DataQuery.Instance.AllTriggers) { if (item.HasChildren()) { var list = item as TriggerList; foreach (Trigger child in list.Children) { RunTrigger(child, r); } } else { var t = item as Trigger; RunTrigger(t, r); } } } } public void RunTrigger(Trigger t, RoomInformation r) { if (t.IsTriggered(r)) { if (t.StopWhenMapIsLoaded) { if (PCSX2_RAM.IsRoomWithPlayerLoaded()) { return; } } //Console.WriteLine("Executing trigger - " + t.RoomInfo.ToString()); t.CodeEntries.Execute(); } } public static RoomInformation ReadRoomInforation() { RoomInformation r = new RoomInformation(); r.WorldNumber = PCSX2_RAM.ReadBytes(IngameConstants.WORLD_PTR, 1)[0]; r.RoomNumber = PCSX2_RAM.ReadShort(IngameConstants.ROOM_PTR); r.EventNumberMain = PCSX2_RAM.ReadShort(IngameConstants.EVENT1_PTR); return r; } private void btnLoad_Click(object sender, RoutedEventArgs e) { var list = TriggerSerializer.DeserializeTrigger(); foreach (var item in list) { DataQuery.Instance.AllTriggers.Add(item); } } private void btnSave_Click(object sender, RoutedEventArgs e) { TriggerSerializer.SerializeTrigger(DataQuery.Instance.AllTriggers); } private void btnTestMap_Click(object sender, RoutedEventArgs e) { MessageBox.Show("" + PCSX2_RAM.IsRoomWithPlayerLoaded()); } private void Window_Loaded(object sender, RoutedEventArgs e) { //TriggerList l = new TriggerList(); //l.DisplayName = "TEST"; //l.Children.Add(new Trigger(1, 2, 3)); //DataQuery.Instance.AllTriggers.Add(l); //DataQuery.Instance.AllTriggers.Add(new Trigger(5,6,5)); //TriggerList x = new TriggerList(); //x.DisplayName = "TEST2"; //x.Children.Add(new Trigger(6, 4, 7)); //DataQuery.Instance.AllTriggers.Add(x); } private void lstBoxTriggers_MouseDown(object sender, MouseButtonEventArgs e) { ClearTreeViewSelection(lstBoxTriggers); } private void btnAddGroup_Click(object sender, RoutedEventArgs e) { InputBox.Visibility = Visibility.Visible; } private void YesButton_Click(object sender, RoutedEventArgs e) { if (InputTextBox.Text != string.Empty) { TriggerList l = new TriggerList(); l.DisplayName = InputTextBox.Text; DataQuery.Instance.AllTriggers.Add(l); InputBox.Visibility = Visibility.Collapsed; } } private void NoButton_Click(object sender, RoutedEventArgs e) { InputBox.Visibility = Visibility.Collapsed; InputTextBox.Text = string.Empty; } private void Window_Closed(object sender, EventArgs e) { bRun = false; } private void btnStop_Click(object sender, RoutedEventArgs e) { bRun = false; th.Abort(); waiting.Visibility = Visibility.Collapsed; } private void lstBoxTriggers_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e) { var item = lstBoxTriggers.SelectedItem; if (item is TriggerList) lstBoxTriggers.ContextMenu = lstBoxTriggers.Resources["contextGroup"] as System.Windows.Controls.ContextMenu; else if (item is Trigger) lstBoxTriggers.ContextMenu = lstBoxTriggers.Resources["contextItem"] as System.Windows.Controls.ContextMenu; } private void lstBoxTriggers_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { } private void contextEditTrigger_Click(object sender, RoutedEventArgs e) { var selected = lstBoxTriggers.SelectedItem; if (selected is Trigger) { TriggerEdit ed = new TriggerEdit(); ed.ShowEditTrigger(selected as Trigger); } } } }
34.204545
132
0.540769
[ "MIT" ]
Rikux3/KHMemoryTools
KHTriggerRunner/UI/MainWindow.xaml.cs
10,538
C#
// SampSharp // Copyright 2017 Tim Potze // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; namespace SampSharp.Core.Communication { /// <summary> /// Contains the possible SampShap server command argument types. /// </summary> [Flags] public enum ServerCommandArgument : byte { /// <summary> /// A terminator value to indicate no more arguments are past this point. /// </summary> Terminator = 0 << 0, /// <summary> /// A value to indicate the next argument is an integer or float. /// </summary> Value = 1 << 0, /// <summary> /// A value to indicate the next argument is an array of integers or floats. /// </summary> Array = 1 << 1, /// <summary> /// A value to indicate the next argument is a string. /// </summary> String = 1 << 2, /// <summary> /// A value to indicate the next argument is a reference. /// </summary> Reference = 1 << 3, /// <summary> /// A value to indicate the next argument is a value reference. /// </summary> ValueReference = Value | Reference, /// <summary> /// A value to indicate the next argument is an array reference. /// </summary> ArrayReference = Array | Reference, /// <summary> /// A value to indicate the next argument is a string reference. /// </summary> StringReference = String | Reference } }
31.681818
88
0.590626
[ "Apache-2.0" ]
BlasterDv/SampSharp
src/SampSharp.Core/Communication/ServerCommandArgument.cs
2,093
C#
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.CommandLine.Parsing; using System.Linq; using Microsoft.DotNet.Cli; using Microsoft.DotNet.Tools.Test; namespace Microsoft.DotNet.Tools.VSTest { public class VSTestCommand { public static int Run(ParseResult parseResult) { parseResult.HandleDebugSwitch(); // We use also current process id for the correlation id for possible future usage in case we need to know the parent process // from the VSTest side. string testSessionCorrelationId = $"{Environment.ProcessId}_{Guid.NewGuid()}"; var args = new List<string>(); args.AddRange(GetArgs(parseResult)); if (!FeatureFlag.Instance.IsSet(FeatureFlag.DISABLE_ARTIFACTS_POSTPROCESSING)) { // Add artifacts processing mode and test session id for the artifact post-processing args.Add("--artifactsProcessingMode-collect"); args.Add($"--testSessionCorrelationId:{testSessionCorrelationId}"); } VSTestForwardingApp vsTestforwardingApp = new(args); int exitCode = vsTestforwardingApp.Execute(); // We run post processing also if execution is failed for possible partial successful result to post process. exitCode |= TestCommand.RunArtifactPostProcessingIfNeeded(testSessionCorrelationId, parseResult, FeatureFlag.Instance); return exitCode; } private static string[] GetArgs(ParseResult parseResult) { IEnumerable<string> args = parseResult.GetArguments(); if (parseResult.HasOption(CommonOptions.TestLoggerOption)) { // System command line might have mutated the options, reformat test logger option so vstest recognizes it string loggerValue = parseResult.GetValueForOption(CommonOptions.TestLoggerOption); args = args.Where(a => !a.Equals(loggerValue) && !CommonOptions.TestLoggerOption.Aliases.Contains(a)); args = args.Prepend($"{CommonOptions.TestLoggerOption.Aliases.First()}:{loggerValue}"); } return args.ToArray(); } } }
41.050847
137
0.666804
[ "MIT" ]
AlexanderSemenyak/sdk
src/Cli/dotnet/commands/dotnet-vstest/Program.cs
2,424
C#
using System; using ChartDirector; namespace CSharpChartExplorer { public class multiradar : DemoModule { //Name of demo module public string getName() { return "Multi Radar Chart"; } //Number of charts produced in this demo module public int getNoOfCharts() { return 1; } //Main code for creating chart. //Note: the argument chartIndex is unused because this demo only has 1 chart. public void createChart(WinChartViewer viewer, int chartIndex) { // The data for the chart double[] data0 = {90, 60, 85, 75, 55}; double[] data1 = {60, 80, 70, 80, 85}; // The labels for the chart string[] labels = {"Speed", "Reliability", "Comfort", "Safety", "Efficiency"}; // Create a PolarChart object of size 480 x 380 pixels. Set background color to gold, // with 1 pixel 3D border effect PolarChart c = new PolarChart(480, 380, Chart.goldColor(), 0x000000, 1); // Add a title to the chart using 15pt Times Bold Italic font. The title text is white // (ffffff) on a deep blue (000080) background c.addTitle("Space Travel Vehicles Compared", "Times New Roman Bold Italic", 15, 0xffffff ).setBackground(0x000080); // Set plot area center at (240, 210), with 150 pixels radius, and a white (ffffff) // background. c.setPlotArea(240, 210, 150, 0xffffff); // Add a legend box at top right corner (470, 35) using 10pt Arial Bold font. Set the // background to silver, with 1 pixel 3D border effect. LegendBox b = c.addLegend(470, 35, true, "Arial Bold", 10); b.setAlignment(Chart.TopRight); b.setBackground(Chart.silverColor(), Chart.Transparent, 1); // Add an area layer to the chart using semi-transparent blue (0x806666cc). Add a blue // (0x6666cc) line layer using the same data with 3 pixel line width to highlight the // border of the area. c.addAreaLayer(data0, unchecked((int)0x806666cc), "Model Saturn"); c.addLineLayer(data0, 0x6666cc).setLineWidth(3); // Add an area layer to the chart using semi-transparent red (0x80cc6666). Add a red // (0xcc6666) line layer using the same data with 3 pixel line width to highlight the // border of the area. c.addAreaLayer(data1, unchecked((int)0x80cc6666), "Model Jupiter"); c.addLineLayer(data1, 0xcc6666).setLineWidth(3); // Set the labels to the angular axis as spokes. c.angularAxis().setLabels(labels); // Output the chart viewer.Chart = c; //include tool tip for the chart viewer.ImageMap = c.getHTMLImageMap("clickable", "", "title='[{dataSetName}] {label}: score = {value}'"); } } }
43.101449
100
0.600202
[ "Apache-2.0" ]
jojogreen/Orbital-Mechanix-Suite
NetWinCharts/CSharpWinCharts/multiradar.cs
2,974
C#
using System.Collections.Generic; namespace EfCore.Shaman { public interface IShamanAnnotatable { IDictionary<string, object> Annotations { get; } } public static class ShamanAnnotatableExtensions { public static string GetStringAnnotation(this IShamanAnnotatable annotatable, string key) { if (annotatable == null) return null; if (annotatable.Annotations.TryGetValue(key, out var value)) return value as string; return null; } } }
26.571429
97
0.623656
[ "MIT" ]
isukces/EfCore.Shaman
src/EfCore.Shaman/_interfaces/IShamanAnnotatable.cs
558
C#
using System.Collections.Generic; using TcpMonitor.Models; namespace TcpMonitor.Services { public interface ITcpConnectionService { IEnumerable<TcpConnectionModel> GetTcpConnections(); } }
19.181818
60
0.753555
[ "Apache-2.0" ]
brian-pickens-web/TcpMonitor
src/TcpMonitor/Services/ITcpConnectionService.cs
213
C#
namespace R8 { partial class FormMain { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.menuStrip1 = new System.Windows.Forms.MenuStrip(); this.toolStripMenuItemTest = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItemFile = new System.Windows.Forms.ToolStripMenuItem(); this.newToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.openToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.saveToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem(); this.saveAsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.sortAndSaveAsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.exportToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem(); this.exportBatchFileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.exportCFileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.reLoadToolBoxToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.languageToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.enToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.jpToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.zhCNToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.zhTWToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.exitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItemUndo = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItemRedo = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItemLibrary = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItemRun = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItemDebug = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItemWorkSpace = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripWorkSpaceTextBox = new System.Windows.Forms.ToolStripTextBox(); this.toolStripMenuItemAbout = new System.Windows.Forms.ToolStripMenuItem(); this.zh_twToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.engToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.menuStrip1.SuspendLayout(); this.SuspendLayout(); // // menuStrip1 // this.menuStrip1.Font = new System.Drawing.Font("Microsoft Sans Serif", 14.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(136))); this.menuStrip1.ImageScalingSize = new System.Drawing.Size(32, 32); this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.toolStripMenuItemTest, this.toolStripMenuItemFile, this.toolStripMenuItemLibrary, this.toolStripMenuItemUndo, this.toolStripMenuItemRedo, this.toolStripMenuItemRun, this.toolStripMenuItemDebug, this.toolStripMenuItemWorkSpace, this.toolStripWorkSpaceTextBox, this.toolStripMenuItemAbout}); this.menuStrip1.Location = new System.Drawing.Point(0, 0); this.menuStrip1.Name = "menuStrip1"; this.menuStrip1.Size = new System.Drawing.Size(722, 32); this.menuStrip1.TabIndex = 1; this.menuStrip1.Text = "menuStrip1"; this.menuStrip1.ItemClicked += new System.Windows.Forms.ToolStripItemClickedEventHandler(this.menuStrip1_ItemClicked); // // toolStripMenuItemTest // this.toolStripMenuItemTest.Name = "toolStripMenuItemTest"; this.toolStripMenuItemTest.Size = new System.Drawing.Size(12, 28); this.toolStripMenuItemTest.Visible = false; // // toolStripMenuItemFile // this.toolStripMenuItemFile.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.newToolStripMenuItem, this.openToolStripMenuItem, this.saveToolStripMenuItem1, this.saveAsToolStripMenuItem, this.sortAndSaveAsToolStripMenuItem, this.exportToolStripMenuItem1, this.reLoadToolBoxToolStripMenuItem, this.languageToolStripMenuItem, this.exitToolStripMenuItem}); this.toolStripMenuItemFile.Name = "toolStripMenuItemFile"; this.toolStripMenuItemFile.Size = new System.Drawing.Size(53, 28); this.toolStripMenuItemFile.Text = "File"; // // newToolStripMenuItem // this.newToolStripMenuItem.Name = "newToolStripMenuItem"; this.newToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.N))); this.newToolStripMenuItem.Size = new System.Drawing.Size(221, 28); this.newToolStripMenuItem.Text = "New"; this.newToolStripMenuItem.Click += new System.EventHandler(this.newToolStripMenuItem_Click); // // openToolStripMenuItem // this.openToolStripMenuItem.Name = "openToolStripMenuItem"; this.openToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.O))); this.openToolStripMenuItem.Size = new System.Drawing.Size(221, 28); this.openToolStripMenuItem.Text = "Open"; this.openToolStripMenuItem.Click += new System.EventHandler(this.openToolStripMenuItem_Click); // // saveToolStripMenuItem1 // this.saveToolStripMenuItem1.Name = "saveToolStripMenuItem1"; this.saveToolStripMenuItem1.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.S))); this.saveToolStripMenuItem1.Size = new System.Drawing.Size(221, 28); this.saveToolStripMenuItem1.Text = "Save"; this.saveToolStripMenuItem1.Click += new System.EventHandler(this.saveToolStripMenuItem_Click); // // saveAsToolStripMenuItem // this.saveAsToolStripMenuItem.Name = "saveAsToolStripMenuItem"; this.saveAsToolStripMenuItem.Size = new System.Drawing.Size(221, 28); this.saveAsToolStripMenuItem.Text = "Save As"; this.saveAsToolStripMenuItem.Click += new System.EventHandler(this.saveAsToolStripMenuItem_Click); // // sortAndSaveAsToolStripMenuItem // this.sortAndSaveAsToolStripMenuItem.Name = "sortAndSaveAsToolStripMenuItem"; this.sortAndSaveAsToolStripMenuItem.Size = new System.Drawing.Size(221, 28); this.sortAndSaveAsToolStripMenuItem.Text = "Save As (Sorted)"; this.sortAndSaveAsToolStripMenuItem.Visible = false; this.sortAndSaveAsToolStripMenuItem.Click += new System.EventHandler(this.sortAndSaveAsToolStripMenuItem_Click); // // exportToolStripMenuItem1 // this.exportToolStripMenuItem1.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.exportBatchFileToolStripMenuItem, this.exportCFileToolStripMenuItem}); this.exportToolStripMenuItem1.Name = "exportToolStripMenuItem1"; this.exportToolStripMenuItem1.Size = new System.Drawing.Size(221, 28); this.exportToolStripMenuItem1.Text = "Export"; this.exportToolStripMenuItem1.Click += new System.EventHandler(this.exportToolStripMenuItem1_Click_1); // // exportBatchFileToolStripMenuItem // this.exportBatchFileToolStripMenuItem.Name = "exportBatchFileToolStripMenuItem"; this.exportBatchFileToolStripMenuItem.Size = new System.Drawing.Size(317, 28); this.exportBatchFileToolStripMenuItem.Text = "Export to Windows batch file"; this.exportBatchFileToolStripMenuItem.Click += new System.EventHandler(this.exportToolStripMenuItem1_Click); // // exportCFileToolStripMenuItem // this.exportCFileToolStripMenuItem.Name = "exportCFileToolStripMenuItem"; this.exportCFileToolStripMenuItem.Size = new System.Drawing.Size(317, 28); this.exportCFileToolStripMenuItem.Text = "Export to Visual C++ file"; this.exportCFileToolStripMenuItem.Click += new System.EventHandler(this.exportCFileToolStripMenuItem_Click); // // reLoadToolBoxToolStripMenuItem // this.reLoadToolBoxToolStripMenuItem.Name = "reLoadToolBoxToolStripMenuItem"; this.reLoadToolBoxToolStripMenuItem.Size = new System.Drawing.Size(221, 28); this.reLoadToolBoxToolStripMenuItem.Text = "Refresh ToolBox"; this.reLoadToolBoxToolStripMenuItem.Visible = false; this.reLoadToolBoxToolStripMenuItem.Click += new System.EventHandler(this.reLoadToolBoxToolStripMenuItem_Click); // // languageToolStripMenuItem // this.languageToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.enToolStripMenuItem, this.jpToolStripMenuItem, this.zhCNToolStripMenuItem, this.zhTWToolStripMenuItem}); this.languageToolStripMenuItem.Name = "languageToolStripMenuItem"; this.languageToolStripMenuItem.Size = new System.Drawing.Size(221, 28); this.languageToolStripMenuItem.Text = "Language"; // // enToolStripMenuItem // this.enToolStripMenuItem.Name = "enToolStripMenuItem"; this.enToolStripMenuItem.Size = new System.Drawing.Size(140, 28); this.enToolStripMenuItem.Text = "en"; this.enToolStripMenuItem.Click += new System.EventHandler(this.enToolStripMenuItem_Click); // // jpToolStripMenuItem // this.jpToolStripMenuItem.Name = "jpToolStripMenuItem"; this.jpToolStripMenuItem.Size = new System.Drawing.Size(140, 28); this.jpToolStripMenuItem.Text = "jp"; this.jpToolStripMenuItem.Click += new System.EventHandler(this.jpToolStripMenuItem_Click); // // zhCNToolStripMenuItem // this.zhCNToolStripMenuItem.Name = "zhCNToolStripMenuItem"; this.zhCNToolStripMenuItem.Size = new System.Drawing.Size(140, 28); this.zhCNToolStripMenuItem.Text = "zh_CN"; this.zhCNToolStripMenuItem.Click += new System.EventHandler(this.zhCNToolStripMenuItem_Click); // // zhTWToolStripMenuItem // this.zhTWToolStripMenuItem.Name = "zhTWToolStripMenuItem"; this.zhTWToolStripMenuItem.Size = new System.Drawing.Size(140, 28); this.zhTWToolStripMenuItem.Text = "zh_TW"; this.zhTWToolStripMenuItem.Click += new System.EventHandler(this.zhTWToolStripMenuItem_Click); // // exitToolStripMenuItem // this.exitToolStripMenuItem.Name = "exitToolStripMenuItem"; this.exitToolStripMenuItem.Size = new System.Drawing.Size(221, 28); this.exitToolStripMenuItem.Text = "Exit"; this.exitToolStripMenuItem.Click += new System.EventHandler(this.exitToolStripMenuItem_Click); // // toolStripMenuItemUndo // this.toolStripMenuItemUndo.Name = "toolStripMenuItemUndo"; this.toolStripMenuItemUndo.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.Z))); this.toolStripMenuItemUndo.Size = new System.Drawing.Size(68, 28); this.toolStripMenuItemUndo.Text = "Undo"; this.toolStripMenuItemUndo.Click += new System.EventHandler(this.toolStripMenuItemUndo_Click); // // toolStripMenuItemRedo // this.toolStripMenuItemRedo.Name = "toolStripMenuItemRedo"; this.toolStripMenuItemRedo.ShortcutKeys = ((System.Windows.Forms.Keys)(((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.Shift) | System.Windows.Forms.Keys.Z))); this.toolStripMenuItemRedo.Size = new System.Drawing.Size(68, 28); this.toolStripMenuItemRedo.Text = "Redo"; this.toolStripMenuItemRedo.Click += new System.EventHandler(this.toolStripMenuItemRedo_Click); // // toolStripMenuItemLibrary // this.toolStripMenuItemLibrary.Name = "toolStripMenuItemLibrary"; this.toolStripMenuItemLibrary.Size = new System.Drawing.Size(78, 28); this.toolStripMenuItemLibrary.Text = "Library"; this.toolStripMenuItemLibrary.Click += new System.EventHandler(this.toolStripMenuItemLibrary_Click); // // toolStripMenuItemRun // this.toolStripMenuItemRun.Name = "toolStripMenuItemRun"; this.toolStripMenuItemRun.Size = new System.Drawing.Size(57, 28); this.toolStripMenuItemRun.Text = "Run"; this.toolStripMenuItemRun.ToolTipText = "Run this program in release mode."; this.toolStripMenuItemRun.Click += new System.EventHandler(this.toolStripMenuItemRun_Click); // // toolStripMenuItemDebug // this.toolStripMenuItemDebug.Name = "toolStripMenuItemDebug"; this.toolStripMenuItemDebug.Size = new System.Drawing.Size(79, 28); this.toolStripMenuItemDebug.Text = "Debug"; this.toolStripMenuItemDebug.ToolTipText = "Run this program in debug mode."; this.toolStripMenuItemDebug.Click += new System.EventHandler(this.debugToolStripMenuItem_Click); // // toolStripMenuItemWorkSpace // this.toolStripMenuItemWorkSpace.Name = "toolStripMenuItemWorkSpace"; this.toolStripMenuItemWorkSpace.Size = new System.Drawing.Size(117, 28); this.toolStripMenuItemWorkSpace.Text = "Workspace"; this.toolStripMenuItemWorkSpace.Click += new System.EventHandler(this.selectPathToolStripMenuItem_Click); // // toolStripWorkSpaceTextBox // this.toolStripWorkSpaceTextBox.Name = "toolStripWorkSpaceTextBox"; this.toolStripWorkSpaceTextBox.ReadOnly = true; this.toolStripWorkSpaceTextBox.Size = new System.Drawing.Size(550, 28); // // toolStripMenuItemAbout // this.toolStripMenuItemAbout.Name = "toolStripMenuItemAbout"; this.toolStripMenuItemAbout.Size = new System.Drawing.Size(72, 28); this.toolStripMenuItemAbout.Text = "About"; this.toolStripMenuItemAbout.Click += new System.EventHandler(this.toolStripMenuItemAbout_Click); // // zh_twToolStripMenuItem // this.zh_twToolStripMenuItem.Name = "zh_twToolStripMenuItem"; this.zh_twToolStripMenuItem.Size = new System.Drawing.Size(32, 19); // // engToolStripMenuItem // this.engToolStripMenuItem.Name = "engToolStripMenuItem"; this.engToolStripMenuItem.Size = new System.Drawing.Size(32, 19); // // FormMain // this.AllowDrop = true; this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.AutoSize = true; this.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Center; this.ClientSize = new System.Drawing.Size(722, 393); this.Controls.Add(this.menuStrip1); this.DoubleBuffered = true; this.IsMdiContainer = true; this.MainMenuStrip = this.menuStrip1; this.Margin = new System.Windows.Forms.Padding(4, 2, 4, 2); this.Name = "FormMain"; this.StartPosition = System.Windows.Forms.FormStartPosition.Manual; this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.FormMain_FormClosing); this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.FormMain_FormClosed); this.Load += new System.EventHandler(this.FormMain_Load); this.MdiChildActivate += new System.EventHandler(this.FormMain_MdiChildActivate); this.DragDrop += new System.Windows.Forms.DragEventHandler(this.FormMain_DragDrop); this.DragEnter += new System.Windows.Forms.DragEventHandler(this.FormMain_DragEnter); this.menuStrip1.ResumeLayout(false); this.menuStrip1.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.MenuStrip menuStrip1; private System.Windows.Forms.ToolStripMenuItem zh_twToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem engToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItemTest; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItemFile; private System.Windows.Forms.ToolStripMenuItem openToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem saveToolStripMenuItem1; private System.Windows.Forms.ToolStripMenuItem saveAsToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItemDebug; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItemWorkSpace; private System.Windows.Forms.ToolStripTextBox toolStripWorkSpaceTextBox; private System.Windows.Forms.ToolStripMenuItem exitToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem newToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem reLoadToolBoxToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItemAbout; private System.Windows.Forms.ToolStripMenuItem exportToolStripMenuItem1; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItemRun; private System.Windows.Forms.ToolStripMenuItem sortAndSaveAsToolStripMenuItem; public System.Windows.Forms.ToolStripMenuItem toolStripMenuItemUndo; public System.Windows.Forms.ToolStripMenuItem toolStripMenuItemRedo; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItemLibrary; private System.Windows.Forms.ToolStripMenuItem exportBatchFileToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem exportCFileToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem languageToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem zhTWToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem enToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem jpToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem zhCNToolStripMenuItem; } }
58.330484
175
0.670167
[ "Unlicense" ]
alexcvig/OpenR8
src/R8/R8_app/FormMain.Designer.cs
20,476
C#
using System; using DevSubmarine.LukeDictionary.Database.Conventions; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using MongoDB.Bson; using MongoDB.Bson.Serialization.Conventions; using MongoDB.Driver; namespace DevSubmarine.LukeDictionary.Database.Services { public class MongoDatabaseClient : IMongoDatabaseClient { private Lazy<MongoClient> _client; public MongoClient Client => this._client.Value; private readonly MongoOptions _options; private readonly ILogger<MongoDatabaseClient> _log; public MongoDatabaseClient(IOptions<MongoOptions> options, ILogger<MongoDatabaseClient> log) { this._options = options.Value; this._log = log; this._client = new Lazy<MongoClient>(() => { this._log.LogTrace("Establishing connection to MongoDB..."); FixMongoMapping(); return new MongoClient(this._options.ConnectionString); }); } public IMongoCollection<TDocument> GetCollection<TDocument>(string name, MongoCollectionSettings settings = null) => this.GetDatabase(this._options.DatabaseName).GetCollection<TDocument>(name, settings); private static void FixMongoMapping() { // because ImmutableTypeClassMapConvention messes up when there's an object that has only readonly props // we need to remove it. To do it, we need to... unregister default conventions and re-register them manually... sigh // ref: https://www.codewrecks.com/post/nosql/replace-immutable-serializer-in-mongodb/ // src of default conventions: https://github.com/mongodb/mongo-csharp-driver/blob/master/src/MongoDB.Bson/Serialization/Conventions/DefaultConventionPack.cs const string packName = "__defaults__"; ConventionRegistry.Remove(packName); // init mongodb mapping conventions ConventionPack conventions = new ConventionPack(); conventions.Add(new ReadWriteMemberFinderConvention()); conventions.Add(new NamedIdMemberConvention(new[] { "Id", "id", "_id", "ID" })); // adding "ID" as a bonus here conventions.Add(new NamedExtraElementsMemberConvention(new[] { "ExtraElements" })); conventions.Add(new IgnoreExtraElementsConvention(true)); // bonus - don't throw if not all properties match conventions.Add(new NamedParameterCreatorMapConvention()); conventions.Add(new StringObjectIdIdGeneratorConvention()); conventions.Add(new LookupIdGeneratorConvention()); // custom conventions conventions.Add(new MapReadOnlyPropertiesConvention()); conventions.Add(new GuidAsStandardRepresentationConvention()); ConventionRegistry.Register(packName, conventions, _ => true); // guid serialization #pragma warning disable CS0618 // Type or member is obsolete BsonDefaults.GuidRepresentationMode = GuidRepresentationMode.V3; #pragma warning restore CS0618 // Type or member is obsolete } } }
49.061538
169
0.682032
[ "Apache-2.0" ]
DevSubmarine/LukeDictionary
LukeDictionary.Bot/Database/MongoDatabaseClient.cs
3,191
C#
using Abp.Application.Services.Dto; using Abp.AutoMapper; using CarPlusGo.CVAS.Car; using CarPlusGo.CVAS.Common; using System; using System.Collections.Generic; using System.Text; namespace CarPlusGo.CVAS.OrdersFile.Dto { [AutoMap(typeof(Orders))] public class OrdersListDto : EntityDto<long> { public Inc Inc { get; set; } //public long TradeItemAuto { get; set; } public TradeItem TradeItem { get; set; } public long CarBaseAuto { get; set; } public long SalesAuto { get; set; } public int CustSource { get; set; } public int CarSource { get; set; } //public long FactoryBrandAuto { get; set; } public FactoryBrand FactoryBrand { get; set; } //public long BrandAuto { get; set; } public Brand Brand { get; set; } //public long ClasenAuto { get; set; } public Clasen Clasen { get; set; } public DateTime? CarDt { get; set; } public string MakNo { get; set; } public decimal ListPrice { get; set; } public decimal DisPrice { get; set; } public decimal GetPrice { get; set; } public decimal Accessary { get; set; } public decimal CarCost { get; set; } public decimal OverAmt { get; set; } public decimal DptAmt { get; set; } public decimal MakNoCost { get; set; } public int OrderType { get; set; } public decimal RentAmt { get; set; } public int RentType { get; set; } public decimal FinalMcost { get; set; } public decimal Mamt { get; set; } public decimal? RentAmtT { get; set; } public decimal RentRate { get; set; } public int OrderStatus { get; set; } public string OrderStatusName { get; set; } public string Memo { get; set; } public DateTime Cdt { get; set; } public int PostType { get; set; } public int? IsCustomerCare { get; set; } public decimal RateRate { get; set; } } }
37.388889
54
0.597821
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
MakingBugs/carplusgo.cvas
src/CarPlusGo.CVAS.Application/OrdersFile/Dto/OrdersListDto.cs
2,021
C#
using System; using System.Linq; namespace NToDec { class Program { static void Main(string[] args) { int[] input = Console.ReadLine() .Split() .Select(int.Parse) .ToArray(); int nSystem = input[0]; int num = input[1]; string output = ConvertToDec(num, nSystem); Console.WriteLine(output); } private static string ConvertToDec(int num, int nSystem) { double result = 0, pow = 0; while (num > 0) { int curr = num % 10; num /= 10; result += curr * Math.Pow(nSystem, pow++); } return result.ToString(); } } }
20.789474
64
0.439241
[ "MIT" ]
MartsTech/IT-Career
02. Programming/05 - Character strings/21. Character-strings-intro/02. NToDec/Program.cs
792
C#
namespace AxiosControls.Converters { using System; using System.Globalization; using Xamarin.Forms; public class HasDataHeightRequestConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value is string stringVal) { return string.IsNullOrEmpty(stringVal) ? 0 : -1; } return value is null ? 0 : -1; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return value; } } }
25.76
103
0.600932
[ "CC0-1.0" ]
Rades98/DrobnyZivnostnik
AxiosControls/Converters/HasDataHeightRequestConverter.cs
646
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.Collections.Generic; using JetBrains.Annotations; using Microsoft.EntityFrameworkCore.Infrastructure; namespace Microsoft.EntityFrameworkCore.Scaffolding.Metadata { /// <summary> /// A simple model for a database primary key used when reverse engineering an existing database. /// </summary> public class DatabasePrimaryKey : Annotatable { /// <summary> /// The table on which the primary key is defined. /// </summary> public virtual DatabaseTable Table { get; [param: CanBeNull] set; } /// <summary> /// The name of the primary key. /// </summary> public virtual string Name { get; [param: CanBeNull] set; } /// <summary> /// The ordered list of columns that make up the primary key. /// </summary> public virtual IList<DatabaseColumn> Columns { get; } = new List<DatabaseColumn>(); /// <inheritdoc /> public override string ToString() => Name ?? "<UNKNOWN>"; } }
34.714286
111
0.633745
[ "Apache-2.0" ]
0b01/efcore
src/EFCore.Relational/Scaffolding/Metadata/DatabasePrimaryKey.cs
1,215
C#
using System; using System.Collections.Generic; using System.Linq; using UnityEngine; namespace UniDebugMenu.Example { /// <summary> /// ゲームオブジェクトのリストを作成するクラス /// </summary> [Serializable] public sealed class GameObjectListCreator : ListCreatorBase<CommandData> { //============================================================================== // クラス //============================================================================== /// <summary> /// ゲームオブジェクトの情報を管理するクラス /// </summary> private sealed class GameObjectData { //========================================================================== // 変数(readonly) //========================================================================== public readonly int m_index ; public readonly string m_name ; public readonly int m_parentCount ; //========================================================================== // 変数 //========================================================================== public GameObject m_gameObject; // 削除後に null を代入するので readonly ではない //========================================================================== // プロパティ //========================================================================== public string Text { get { var line = ( m_index + 1 ).ToString( "0000" ); var indent = " ".Repeat( m_parentCount ); var isDestroyed = m_gameObject == null; var isActive = !isDestroyed && m_gameObject.activeInHierarchy && m_gameObject.activeSelf; var colorTag = isDestroyed ? "red" : isActive ? "while" : "silver"; return $"<color={colorTag}>{line} {indent}{m_name}</color>"; } } //========================================================================== // 関数 //========================================================================== /// <summary> /// コンストラクタ /// </summary> public GameObjectData( int index, GameObject gameObject ) { m_index = index ; m_gameObject = gameObject ; m_name = gameObject.name ; m_parentCount = m_gameObject.GetAllParent().Length; } /// <summary> /// アクティブかどうかを切り替えます /// </summary> public void ToggleActive() { m_gameObject?.SetActive( !m_gameObject.activeSelf ); } /// <summary> /// ゲームオブジェクトを削除します /// </summary> public void Destroy() { GameObject.Destroy( m_gameObject ); m_gameObject = null; } } //============================================================================== // 変数 //============================================================================== private IList<CommandData> m_list; //============================================================================== // プロパティ //============================================================================== public override int Count => m_list.Count; //============================================================================== // 関数 //============================================================================== /// <summary> /// リストの表示に使用するデータを作成します /// </summary> protected override void DoCreate( ListCreateData data ) { /* * http://baba-s.hatenablog.com/entry/2019/03/13/214323 * ゲームオブジェクトを順番に並べるために * Resources.FindObjectsOfTypeAll ではなく * GameObject.FindObjectsOfType を使用しています */ m_list = GameObject .FindObjectsOfType<GameObject>() .Where( c => c.transform.parent == null ) .SelectMany( c => c.GetComponentsInChildren<Transform>( true ) ) .Select( c => c.gameObject ) .Select( ( val, index ) => new GameObjectData( index, val ) ) .Where( c => data.IsMatch( c.Text ) ) .Select( c => { var elemData = new CommandData ( () => c.Text, new ActionData( "詳細", () => { var components = c.m_gameObject .GetComponents<MonoBehaviour>() .Select( behaviour => JsonUtility.ToJson( behaviour, true ) ) ; var infoText = string.Join( "\n", components ); OpenAdd( DMType.TEXT_TAB_6, new SimpleTextListDataCreator( infoText ) ); } ), new ActionData( "削除", () => { c.Destroy(); Refresh(); } ), new ActionData( "アクティブ\n切り替え", () => { c.ToggleActive(); Refresh(); } ) ) { IsLeft = true, }; return elemData; } ) .ToArray() .ReverseIf( data.IsReverse ) ; } /// <summary> /// 指定されたインデックスの要素の表示に使用するデータを返します /// </summary> protected override CommandData DoGetElemData( int index ) => m_list.ElementAtOrDefault( index ); } }
29.583333
98
0.435536
[ "MIT" ]
baba-s/uni-debug-menu
app/Assets/UniDebugMenu/Example/Scripts/GameObjectListCreator.cs
5,039
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.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Text; using Silk.NET.Core; using Silk.NET.Core.Native; using Silk.NET.Core.Attributes; using Silk.NET.Core.Contexts; using Silk.NET.Core.Loader; #pragma warning disable 1591 namespace Silk.NET.Direct3D12 { [NativeName("Name", "D3D12_FEATURE_DATA_VIDEO_EXTENSION_COMMAND_PARAMETER_COUNT")] public unsafe partial struct FeatureDataVideoExtensionCommandParameterCount { public FeatureDataVideoExtensionCommandParameterCount ( Guid? commandId = null, VideoExtensionCommandParameterStage? stage = null, uint? parameterCount = null, uint? parameterPacking = null ) : this() { if (commandId is not null) { CommandId = commandId.Value; } if (stage is not null) { Stage = stage.Value; } if (parameterCount is not null) { ParameterCount = parameterCount.Value; } if (parameterPacking is not null) { ParameterPacking = parameterPacking.Value; } } [NativeName("Type", "GUID")] [NativeName("Type.Name", "GUID")] [NativeName("Name", "CommandId")] public Guid CommandId; [NativeName("Type", "D3D12_VIDEO_EXTENSION_COMMAND_PARAMETER_STAGE")] [NativeName("Type.Name", "D3D12_VIDEO_EXTENSION_COMMAND_PARAMETER_STAGE")] [NativeName("Name", "Stage")] public VideoExtensionCommandParameterStage Stage; [NativeName("Type", "UINT")] [NativeName("Type.Name", "UINT")] [NativeName("Name", "ParameterCount")] public uint ParameterCount; [NativeName("Type", "UINT")] [NativeName("Type.Name", "UINT")] [NativeName("Name", "ParameterPacking")] public uint ParameterPacking; } }
29.342466
86
0.614846
[ "MIT" ]
Ar37-rs/Silk.NET
src/Microsoft/Silk.NET.Direct3D12/Structs/FeatureDataVideoExtensionCommandParameterCount.gen.cs
2,142
C#
using System; using Stylet; using StyletIoC; using LocalXamler.Pages; namespace LocalXamler { public class Bootstrapper : Bootstrapper<ShellViewModel> { protected override void ConfigureIoC(IStyletIoCBuilder builder) { // Configure the IoC container in here } protected override void Configure() { // Perform any other configuration before the application starts } } }
21.714286
76
0.651316
[ "MIT" ]
ajdre2015/WPFLocalizationRDTool
LocalXamler/LocalXamler/Bootstrapper.cs
458
C#
namespace Xamarin.Forms.Controls { public class LabelGallery : ContentPage { public LabelGallery() { var normal = new Label { Text = "Normal Label" }; var center = new Label { Text = "Center Label" }; var right = new Label { Text = "Right Label" }; var moving = new Label { Text = "Move On Click" }; var click = new Label { Text = "Click Label" }; var rotate = new Label { Text = "Rotate Label" }; var transparent = new Label { Text = "Transparent Label" }; var color = new Label { Text = "Color Change" }; var micro = new Label { Text = "Micro Label" }; var small = new Label { Text = "Small Label" }; var medium = new Label { Text = "Medium Label" }; var large = new Label { Text = "Large Label", VerticalOptions = LayoutOptions.FillAndExpand, VerticalTextAlignment = TextAlignment.Center }; var bold = new Label { Text = "Bold Label" }; var italic = new Label { Text = "Italic Label" }; var bolditalic = new Label { Text = "Bold Italic Label" }; var customFont = new Label { Text = "Custom Font" }; var italicfont = new Label { Text = "Custom Italic Font" }; var boldfont = new Label { Text = "Custom Bold Font" }; var bolditalicfont = new Label { Text = "Custom Bold Italic Font" }; var toggleUnderline = new Label { Text = "Tap to toggle Underline", TextDecorations = TextDecorations.Underline }; toggleUnderline.GestureRecognizers.Add(new TapGestureRecognizer { Command = new Command(() => { toggleUnderline.TextDecorations ^= TextDecorations.Underline; }) }); var toggleStrike = new Label { Text = "Tap to toggle StrikeThrough", TextDecorations = TextDecorations.Strikethrough }; toggleStrike.GestureRecognizers.Add(new TapGestureRecognizer { Command = new Command(() => { toggleStrike.TextDecorations ^= TextDecorations.Strikethrough; }) }); var toggleBoth = new Label { Text = "Tap to toggle both", TextDecorations = TextDecorations.Strikethrough | TextDecorations.Underline }; toggleBoth.GestureRecognizers.Add(new TapGestureRecognizer { Command = new Command(() => { toggleBoth.TextDecorations ^= TextDecorations.Strikethrough; toggleBoth.TextDecorations ^= TextDecorations.Underline; }) }); var huge = new Label { Text = "This is the label that never ends, yes it go on and on my friend. " + "Some people started catting it not knowing what it was, and they'll continue catting it forever just because...", LineBreakMode = LineBreakMode.WordWrap }; var formatted = new Label { FormattedText = new FormattedString { Spans = { new Span {Text="FormattedStrings ", TextColor=Color.Blue, BackgroundColor = Color.Yellow, FontAttributes = FontAttributes.Bold, FontSize = Device.GetNamedSize(NamedSize.Large, typeof(Label))}, } } }; var underlineSpan = new Span { Text = "are ", TextColor = Color.Red, BackgroundColor = Color.Gray, TextDecorations = TextDecorations.Underline }; var strikeSpan = new Span { Text = "not pretty!", TextColor = Color.Green, TextDecorations = TextDecorations.Strikethrough }; formatted.FormattedText.Spans.Add(underlineSpan); formatted.FormattedText.Spans.Add(strikeSpan); var missingfont = new Label { Text = "Missing font: use default" }; micro.FontSize = Device.GetNamedSize(NamedSize.Micro, typeof(Label)); small.FontSize = Device.GetNamedSize(NamedSize.Small, typeof(Label)); medium.FontSize = Device.GetNamedSize(NamedSize.Medium, typeof(Label)); large.FontSize = Device.GetNamedSize(NamedSize.Large, typeof(Label)); bold.FontSize = Device.GetNamedSize(NamedSize.Medium, typeof(Label)); bold.FontAttributes = FontAttributes.Bold; italic.FontSize = Device.GetNamedSize(NamedSize.Medium, typeof(Label)); italic.FontAttributes = FontAttributes.Italic; bolditalic.FontSize = Device.GetNamedSize(NamedSize.Medium, typeof(Label)); bolditalic.FontAttributes = FontAttributes.Bold | FontAttributes.Italic; string fontName; switch (Device.RuntimePlatform) { default: case Device.iOS: fontName = "Georgia"; break; case Device.Android: fontName = "sans-serif-light"; break; case Device.UWP: fontName = "Comic Sans MS"; break; } customFont.FontFamily = fontName; customFont.FontSize = Device.GetNamedSize(NamedSize.Medium, typeof(Label)); italicfont.FontFamily = fontName; italicfont.FontSize = Device.GetNamedSize(NamedSize.Medium, typeof(Label)); italicfont.FontAttributes = FontAttributes.Italic; boldfont.FontFamily = fontName; boldfont.FontSize = Device.GetNamedSize(NamedSize.Medium, typeof(Label)); boldfont.FontAttributes = FontAttributes.Bold; bolditalicfont.FontFamily = fontName; bolditalicfont.FontSize = Device.GetNamedSize(NamedSize.Medium, typeof(Label)); bolditalicfont.FontAttributes = FontAttributes.Bold | FontAttributes.Italic; customFont.GestureRecognizers.Add(new TapGestureRecognizer { Command = new Command(o => { customFont.FontAttributes = FontAttributes.None; customFont.FontFamily = null; customFont.FontSize = 0; }) }); missingfont.FontFamily = "FooBar"; missingfont.FontSize = 20; center.HorizontalTextAlignment = TextAlignment.Center; right.HorizontalTextAlignment = TextAlignment.End; int i = 1; click.GestureRecognizers.Add(new TapGestureRecognizer { Command = new Command(o => click.Text = "Clicked " + i++) }); rotate.GestureRecognizers.Add(new TapGestureRecognizer { Command = new Command(o => rotate.RelRotateTo(180)) }); transparent.Opacity = .5; moving.GestureRecognizers.Add(new TapGestureRecognizer { Command = new Command(o => moving.HorizontalTextAlignment = TextAlignment.End) }); color.GestureRecognizers.Add(new TapGestureRecognizer { Command = new Command(o => { color.TextColor = new Color(1, 0, 0); color.BackgroundColor = new Color(0, 1, 0); }) }); Thickness padding = new Thickness(20); // Padding Adjust for iPad if (Device.RuntimePlatform == Device.iOS && Device.Idiom == TargetIdiom.Tablet) Padding = new Thickness(20, 20, 20, 60); Content = new ScrollView { Content = new StackLayout { Padding = padding, Children = { formatted, normal, center, right, huge, moving, click, rotate, transparent, color, micro, small, medium, large, bold, italic, bolditalic, toggleUnderline, toggleStrike, toggleBoth, customFont, italicfont, boldfont, bolditalicfont, missingfont, } } }; } } }
37.116667
198
0.688969
[ "MIT" ]
gywerd/CPUI
src/ControlGallery/src/Xamarin.Forms.Controls/GalleryPages/LabelGallery.cs
6,683
C#
using System; using TypewiseAlert.Alerts; using TypewiseAlert.Models; using Xunit; using static TypewiseAlert.TypewiseAlert; namespace TypewiseAlert.Test { public class TypewiseAlertTest { [Fact] public void TestAlerEmailandController() { Alerter _alert = new Alerter(); //Email Sender _alert.SetTarget(new SenderEmail()); // Test email NORMAL _alert.SetBreachType(BreachType.NORMAL); _alert.SendTo(); // Test email TOO_LOW _alert.SetBreachType(BreachType.TOO_LOW); _alert.SendTo(); // Test email TOO_HIGH _alert.SetBreachType(BreachType.TOO_HIGH); _alert.SendTo(); Assert.True(_alert.sendTo == true); // Controller Sender _alert.SetTarget(new SenderController()); // Test email NORMAL _alert.SetBreachType(BreachType.NORMAL); _alert.SendTo(); // Test email TOO_LOW _alert.SetBreachType(BreachType.TOO_LOW); _alert.SendTo(); // Test email TOO_HIGH _alert.SetBreachType(BreachType.TOO_HIGH); _alert.SendTo(); Assert.True(_alert.sendTo == true); } [Fact] public void InfersBreachAsPerLimits() { Assert.True(TypewiseAlert.InferBreach(25, 20, 30) == TypewiseAlert.BreachType.NORMAL); Assert.True(TypewiseAlert.InferBreach(10, 20, 30) == TypewiseAlert.BreachType.TOO_LOW); Assert.True(TypewiseAlert.InferBreach(31, 20, 30) == TypewiseAlert.BreachType.TOO_HIGH); } } }
21.725
100
0.573072
[ "MIT" ]
clean-code-craft-tcq-2/coverage-in-cs-RicardoMoralesG
TypewiseAlert.Test/TypewiseAlertTest.cs
1,738
C#
using System; using System.Collections.Specialized; using System.Globalization; using NLog; using System.Web; namespace Mios.Payment.Providers { public class SamlinkPaymentProvider : IPaymentProvider { static readonly Logger log = LogManager.GetCurrentClassLogger(); public int Version { get; set; } public string Account { get; set; } public string Secret { get; set; } public string KeyVersion { get; set; } public string Url { get; set; } public SamlinkPaymentProvider() { Version = 1; } public SamlinkPaymentProvider(string parameterString) : this() { var parameters = HttpUtility.ParseQueryString(parameterString); if(parameters["account"] == null) { throw new ArgumentException("Missing 'account' parameter in initialization string."); } if(parameters["secret"] == null) { throw new ArgumentException("Missing 'secret' parameter in initialization string."); } if(parameters["url"] == null) { throw new ArgumentException("Missing 'url' parameter in initialization string."); } Account = parameters["account"]; Secret = parameters["secret"]; Url = parameters["url"]; } public PaymentDetails GenerateDetails(string identifier, decimal amount, string returnUrl, string errorUrl, string message) { var referenceNumber = ReferenceCalculator.GenerateReferenceNumber(identifier); var details = new PaymentDetails { Url = Url, Fields = new NameValueCollection(StringComparer.Ordinal) { {"NET_STAMP",identifier}, {"NET_SELLER_ID",Account}, {"NET_AMOUNT",amount.ToString("N2",CultureInfo.CreateSpecificCulture("fi-fi"))}, {"NET_CUR","EUR"}, {"NET_REF",referenceNumber}, {"NET_DATE","EXPRESS"}, {"NET_MSG",message}, {"NET_RETURN",returnUrl}, {"NET_CANCEL",errorUrl}, {"NET_REJECT",errorUrl}, {"NET_CONFIRM","YES"}, } }; if(Version==1) { SignV1(details.Fields); } else if(Version==3) { SignV3(details.Fields); } else if(Version==10) { SignV10(details.Fields); } else { throw new InvalidOperationException(String.Format("Specified version {0} is not supported, supported values are 1, 3, and 10", Version)); } return details; } private void SignV1(NameValueCollection fields) { fields["NET_VERSION"] = "001"; fields["NET_LOGON"] = "TRUE"; fields["NET_MAC"] = Hash("MD5", fields["NET_VERSION"], fields["NET_STAMP"], Account, fields["NET_AMOUNT"], fields["NET_REF"], fields["NET_DATE"], fields["NET_CUR"], Secret ); } private void SignV3(NameValueCollection fields) { fields["NET_VERSION"] = "003"; fields["NET_ALG"] = "03"; fields["NET_MAC"] = Hash("SHA256", fields["NET_VERSION"], fields["NET_STAMP"], Account, fields["NET_AMOUNT"], fields["NET_REF"], fields["NET_DATE"], fields["NET_CUR"], fields["NET_RETURN"], fields["NET_CANCEL"], fields["NET_REJECT"], fields["NET_ALG"], Secret ); } private void SignV10(NameValueCollection fields) { fields["NET_VERSION"] = "010"; fields["NET_ALG"] = "03"; fields["NET_KEYVERS"] = KeyVersion; fields["NET_MAC"] = Hash("SHA256", fields["NET_VERSION"], fields["NET_STAMP"], Account, fields["NET_AMOUNT"], fields["NET_REF"], fields["NET_DATE"], fields["NET_CUR"], fields["NET_RETURN"], fields["NET_CANCEL"], fields["NET_REJECT"], fields["NET_ALG"], fields["NET_KEYVERS"], Secret ); } private string Hash(string algorithm, params string[] parts) { var str = String.Join("&", parts)+"&"; var hash = (String.Join("&", parts)+"&").Hash(algorithm).ToUpperInvariant(); log.Trace("Produced hash {0} using {1} for {2}", hash, algorithm, str); return hash; } public bool VerifyResponse(string identifier, decimal amount, NameValueCollection fields) { if(!identifier.Equals(fields["NET_RETURN_STAMP"])) { log.Error("Identifier comparison failed when verifying response from Sampo, expected {0} found {1}", identifier, fields["NET_RETURN_STAMP"]); return false; } switch(fields["NET_RETURN_VERSION"]) { case "001": return VerifyV1(fields); case "003": return VerifyV3(fields); case "010": return VerifyV10(fields); default: throw new InvalidOperationException("Unsupported version "+fields["NET_RETURN_VERSION"]+"."); } } private bool VerifyV1(NameValueCollection fields) { var expected = Hash("MD5", fields["NET_RETURN_VERSION"], fields["NET_RETURN_STAMP"], fields["NET_RETURN_REF"], fields["NET_RETURN_PAID"], Secret ); if(expected.Equals(fields["NET_RETURN_MAC"])) { return true; } log.Error( "Hash check failed when verifying response from Sampo, expected {0} found {1}, value computed from {2}&{3}&{4}&{5}&{6}&", expected, fields["TARKISTE"], fields["NET_RETURN_VERSION"], fields["NET_RETURN_STAMP"], fields["NET_RETURN_REF"], fields["NET_RETURN_PAID"], "SECRET" ); return false; } private bool VerifyV3(NameValueCollection fields) { var expected = Hash("SHA256", fields["NET_RETURN_VERSION"], fields["NET_RETURN_STAMP"], fields["NET_RETURN_REF"], fields["NET_RETURN_PAID"], fields["NET_ALG"], Secret ); if(expected.Equals(fields["NET_RETURN_MAC"])) { return true; } log.Error( "Hash check failed when verifying response from processor, expected {0} found {1}, value computed from {2}&{3}&{4}&{5}&{6}&{7}&", expected, fields["TARKISTE"], fields["NET_RETURN_VERSION"], fields["NET_RETURN_STAMP"], fields["NET_RETURN_REF"], fields["NET_RETURN_PAID"], fields["NET_ALG"], "SECRET" ); return false; } private bool VerifyV10(NameValueCollection fields) { var expected = Hash("SHA256", fields["NET_RETURN_VERSION"], fields["NET_ALG"], fields["NET_RETURN_STAMP"], fields["NET_RETURN_REF"], fields["NET_RETURN_PAID"], fields["NET_KEYVERS"], Secret ); if(expected.Equals(fields["NET_RETURN_MAC"])) { return true; } log.Error( "Hash check failed when verifying response from processor, expected {0} found {1}, value computed from {2}&{3}&{4}&{5}&{6}&{7}&{8}&", expected, fields["TARKISTE"], fields["NET_RETURN_VERSION"], fields["NET_ALG"], fields["NET_RETURN_STAMP"], fields["NET_RETURN_REF"], fields["NET_RETURN_PAID"], fields["NET_KEYVERS"], "SECRET" ); return false; } } }
29.480349
142
0.632055
[ "BSD-2-Clause" ]
mios-fi/mios.payment
core/Providers/SamlinkPaymentProvider.cs
6,753
C#
// /*************************************************************** // * 项目名称:第七史诗 // * 类 名 称:NewClass // * 功能简介: // * 版 本 号:v1.0.0.0 // * 作 者:Robert Xu // * CLR 版本:4.0.30319.42000 ( mono-4.0 ) // * C# 版 本:4.7.1 // * 创建时间:2020/8/31 17:9:38 // **************************************************************** // * Copyright @ Xu Donghao 2020 . All rights reserved. // ***************************************************************/ using System; using UnityEngine; using UnityEngine.UI; public class LoopScrollStaticCell : LoopScrollCell { public override LoopScrollCellLoadType LoadType => LoopScrollCellLoadType.Static; public LoopScrollStaticCell() { } public static LoopScrollStaticCell Create(GameObject goSource, int idx) { var go = GameObject.Instantiate(goSource); go.name += idx.ToString(); var obj = go.GetComponent<LoopScrollStaticCell>(); if (obj == null) { obj = go.AddComponent<LoopScrollStaticCell>(); } obj.Init(); return obj; } }
25.619048
85
0.490706
[ "MIT" ]
Angolar/LoopScrollRect
Assets/Scripts/LoopScrollStaticCell.cs
1,150
C#
using Microsoft.Azure.WebJobs; using Microsoft.Azure.WebJobs.Extensions.Http; using Microsoft.Azure.WebJobs.Host; using Newtonsoft.Json; using System; using System.Linq; using System.Net; using System.Net.Http; using System.Threading.Tasks; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Text; using Microsoft.Azure.Documents.Client; using Microsoft.Azure.Documents; namespace CCTitanFunction { public static class GetAllActiveShipments { [FunctionName("GetAllActiveShipments")] public static async Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)]HttpRequestMessage req, TraceWriter log) { log.Info("C# HTTP trigger function processed a request."); var NOsqlconnectionstring = Environment.GetEnvironmentVariable("NoSQLConnectionString"); var SQLconnectionstring = Environment.GetEnvironmentVariable("SQLConnectionString"); var PrimaryKey = Environment.GetEnvironmentVariable("NoSqlPrimaryKey"); DocumentClient client = new DocumentClient(new Uri(NOsqlconnectionstring), PrimaryKey); FeedOptions feedOptions = new FeedOptions(); Database databaseInfo = client.CreateDatabaseQuery().Where(x => x.Id == "TitanCosmosDB").AsEnumerable().FirstOrDefault(); string DB = databaseInfo.SelfLink; DocumentCollection documentCollection = new DocumentCollection { Id = "TitanTelemetryCollection" }; //string param = "eadd3a4f3531"; //string cosmosQuery = "SELECT TOP 1 c.temperature,c.humidity,f.current_system_time,c.humidity_alert,c.temperature_alert,c.tamper_alert FROM f JOIN c IN f.sensor_Values WHERE c.sensorID = '"+ param + "' order by f.current_system_time desc"; var collectionlinK = UriFactory.CreateDocumentCollectionUri("TitanCosmosDB", "TitanTelemetryCollection"); //var collectionAlert = UriFactory.CreateDocumentCollectionUri("TitanCosmosDB", "CCAlertCollection"); List<ActiveShipments> shipMasterList = new List<ActiveShipments>(); string SqlSelect = "SELECT[ShipmasterID],[ShipmentID],[ShipmentStatus],[CreatedBy],[CreatedTime],[SourceLoc],[DestinationLoc],[LogisticPartner],[DateofShipment],[DeliveryDate]," + "[InvoiceDocRef],[PONumber],[BlockchainStatus],[GatewayCount],[PalletCount],[CartonCount],[BoxCount],[ProductCount],[BeaconCount]," + "[CurrrentLat],[CurrrentLong],[TemperatureBreach],[HumidityBreach],[TamperBreach],[VibrationBreach],[UnreachableDevice],[IsActive],[AlertStatus] " + " FROM [VW_AssociatedShipments] "; using (SqlConnection conn = new SqlConnection(SQLconnectionstring)) { using (SqlCommand cmd = new SqlCommand(SqlSelect, conn)) { conn.Open(); SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { ActiveShipments shipMaster = new ActiveShipments(); shipMaster.ShipmasterID = (int)reader["ShipmasterID"]; shipMaster.ShipmentID = reader["ShipmentID"].ToString(); shipMaster.ShipmentStatus = reader["ShipmentStatus"].ToString(); shipMaster.CreatedBy = reader["CreatedBy"].ToString(); shipMaster.CreatedDateTime = (DateTime)reader["CreatedTime"]; shipMaster.SourceLoc = reader["SourceLoc"].ToString(); shipMaster.DestinationLoc = reader["DestinationLoc"].ToString(); shipMaster.LogisticPartner = reader["LogisticPartner"].ToString(); shipMaster.DateofShipment = (DateTime)reader["DateofShipment"]; shipMaster.DeliveryDate = (DateTime)reader["DeliveryDate"]; shipMaster.InvoiceDocRef = reader["InvoiceDocRef"].ToString(); shipMaster.PONumber = reader["PONumber"].ToString(); shipMaster.AlertStatus = reader["AlertStatus"].ToString(); shipMaster.IsActive = (bool)reader["IsActive"]; shipMaster.GatewayCount = (int)reader["GatewayCount"]; shipMaster.PalletCount = (int)reader["PalletCount"]; shipMaster.CartonCount = (int)reader["CartonCount"]; shipMaster.BoxCount = (int)reader["BoxCount"]; shipMaster.ProductCount = (int)reader["ProductCount"]; shipMaster.BeaconCount = (int)reader["BeaconCount"]; shipMaster.BlockchainStatus = reader["BlockchainStatus"].ToString(); shipMaster.TemperatureBreachCount = (int)reader["TemperatureBreach"]; shipMaster.HumidityBreachCount = (int)reader["HumidityBreach"]; shipMaster.ShockVibrationCount = (int)reader["VibrationBreach"]; shipMaster.TamperBreachCount = (int)reader["TamperBreach"]; shipMaster.UnreachableDeviceCount = (int)reader["UnreachableDevice"]; string gatewayID = GetMacId(shipMaster.ShipmasterID); GatewayLocation objLocation= new GatewayLocation(); string cosmosTelemeterySelect = "SELECT TOP 1 c.gatewayId, c.current_longitude,c.current_latitude,c.current_system_time,c.current_gps_time, " + "c.last_recorded_latitude,c.last_recorded_longitude ,c.last_recorded_gps_time FROM c where c.gatewayId = '" + gatewayID + "' order by c.current_system_time desc"; //var test = "SELECT * FROM c where c.current_gps_time='235952.207'"; IQueryable<GatewayLocation> cosTelemetry = client.CreateDocumentQuery<GatewayLocation>(collectionlinK, cosmosTelemeterySelect); objLocation = cosTelemetry.ToList().SingleOrDefault(); if (objLocation != null) { if (objLocation.current_latitude == 0) { shipMaster.CurrentLatitude = objLocation.last_recorded_latitude; } else { shipMaster.CurrentLatitude = objLocation.current_latitude; } if (objLocation.current_longitude == 0) { shipMaster.CurrentLongitude = objLocation.last_recorded_longitude; } else { shipMaster.CurrentLongitude = objLocation.current_longitude; } //if (objLocation.current_gps_time.ToString() == "0" || objLocation.current_gps_time.ToString() == "0.0" ||string.IsNullOrEmpty(objLocation.current_gps_time.ToString()) ) //{ // shipMaster.CurrentGPSTime = objLocation.last_recorded_gps_time; //} if (string.IsNullOrEmpty(objLocation.current_gps_time)) { shipMaster.CurrentGPSTime = objLocation.last_recorded_gps_time; } else { shipMaster.CurrentGPSTime = objLocation.current_gps_time; } } ///GPS Data Test GatewayLocation objGPS= new GatewayLocation(); int trackerId = GetTrackerId(gatewayID); objGPS = GetGPSData(trackerId); shipMaster.CurrentLatitude = objGPS.current_latitude; shipMaster.CurrentLongitude = objGPS.current_longitude; shipMaster.CurrentGPSTime = objGPS.current_gps_time; /////GPS///////////////// shipMasterList.Add(shipMaster); } reader.Close(); conn.Close(); } } return new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(JsonConvert.SerializeObject(shipMasterList, Formatting.Indented), Encoding.UTF8, "application/json") }; } private static string GetMacId(int shipmasterID) { string macId = ""; string qrySelectMAcId = " SELECT TOP 1 [MacId] from [dbo].[VW_Gateway_Pallet_ShipmentAssociation] WHERE [ShipmasterID] = @ShipmasterID"; var Connectionstring = Environment.GetEnvironmentVariable("SQLConnectionString"); SqlConnection connMac = new SqlConnection(Connectionstring); SqlCommand commandMac = new SqlCommand(qrySelectMAcId, connMac); commandMac.Parameters.Clear(); commandMac.Parameters.Add("@ShipmasterID", SqlDbType.Int).Value = shipmasterID; connMac.Open(); var gatewayDeviceId = commandMac.ExecuteScalar(); connMac.Close(); if (gatewayDeviceId != null) { macId = (string)gatewayDeviceId; } return macId; } private static int GetTrackerId(string macId) { int trackerId = 0; string qrySelectTrackerId = "SELECT a.tracker_id FROM[VW_Gateway_Pallet_ShipmentAssociation] a WHERE a.MacId = @MacID"; var Connectionstring = Environment.GetEnvironmentVariable("SQLConnectionString"); SqlConnection connMac = new SqlConnection(Connectionstring); SqlCommand commandMac = new SqlCommand(qrySelectTrackerId, connMac); commandMac.Parameters.Clear(); commandMac.Parameters.Add("@MacID", SqlDbType.NVarChar).Value = macId; connMac.Open(); var gatewayTrackerId = commandMac.ExecuteScalar(); connMac.Close(); if (gatewayTrackerId != null) { trackerId = (int)gatewayTrackerId; } return trackerId; } private static GatewayLocation GetGPSData(int trackerId) { string qrySelecGPS = "SELECT TOP 1 a.id,a.[TrackerId],a.[Latitude],a.[Longitude],a.[Timestamp] FROM[dbo].[GPS_Data] a INNER JOIN[DeviceInfo] d on a.[TrackerId] = d.macid " + " WHERE d.deviceid = @TrackerId ORDER BY a.[Timestamp] desc"; var Connectionstring = Environment.GetEnvironmentVariable("SQLConnectionString"); SqlConnection connGPS = new SqlConnection(Connectionstring); SqlCommand commandGPS = new SqlCommand(qrySelecGPS, connGPS); commandGPS.Parameters.Clear(); commandGPS.Parameters.Add("@TrackerId", SqlDbType.Int).Value = trackerId; connGPS.Open(); SqlDataReader reader = commandGPS.ExecuteReader(); GatewayLocation objLocation = new GatewayLocation(); while (reader.Read()) { objLocation.current_latitude = (double)reader["Latitude"]; objLocation.current_longitude = (double)reader["Longitude"]; objLocation.current_system_time=(DateTime)reader["Timestamp"]; objLocation.current_gps_time = reader["Timestamp"].ToString(); break; } reader.Close(); connGPS.Close(); return objLocation; } } public class ActiveShipments { public int ShipmasterID { get; set; } public string ShipmentID { get; set; } public string ShipmentStatus { get; set; } public string CreatedBy { get; set; } public DateTime CreatedDateTime { get; set; } public string SourceLoc { get; set; } public string DestinationLoc { get; set; } public string LogisticPartner { get; set; } public DateTime DateofShipment { get; set; } public DateTime DeliveryDate { get; set; } public string InvoiceDocRef { get; set; } public string PONumber { get; set; } public string BlockchainStatus { get; set; } public string TransactionHash { get; set; } public bool IsActive { get; set; } public int GatewayCount { get; set; } public int PalletCount { get; set; } public int CartonCount { get; set; } public int BoxCount { get; set; } public int ProductCount { get; set; } public int BeaconCount { get; set; } public int TemperatureBreachCount { get; set; } public int HumidityBreachCount { get; set; } public int ShockVibrationCount { get; set; } public int TamperBreachCount { get; set; } public int UnreachableDeviceCount { get; set; } public double CurrentLatitude{ get; set; } public double CurrentLongitude { get; set; } public string AlertStatus { get; set; } public string CurrentGPSTime { get; set; } } public class GatewayLocation { public string gatewayId { get; set; } public float last_recorded_latitude { get; set; } public float last_recorded_longitude { get; set; } public double current_latitude { get; set; } public double current_longitude { get; set; } public DateTime current_system_time { get; set; } public string current_gps_time { get; set; } public string last_recorded_gps_time { get; set; } } }
56.337449
253
0.600365
[ "MIT" ]
SecureColdChain/Wipro-Ltd-ColdChain
Code/FunctionAppCode/CCTitanFunction/GetAllActiveShipments.cs
13,690
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerInputs : MonoBehaviour { [HideInInspector] public Vector2 normalizedDirection; private Vector2 directionInput; [SerializeField] private float moveMargin = 0.2f; void Update() { GetInput(); } void GetInput() { float x = Input.GetAxisRaw("Horizontal"); float y = Input.GetAxisRaw("Vertical"); directionInput = Vector2.zero; if (x + moveMargin < 0) { directionInput += Vector2.left; } if (x - moveMargin > 0) { directionInput += Vector2.right; } if (y + moveMargin < 0) { directionInput += Vector2.down; } if (y - moveMargin > 0) { directionInput += Vector2.up; } if (directionInput.magnitude > 1) { normalizedDirection = directionInput / directionInput.magnitude; } else { normalizedDirection = directionInput; } } }
19.596491
76
0.542525
[ "MIT" ]
Jimdooz/GlobalGameJam2020
Assets/Scripts/Player/PlayerInputs.cs
1,119
C#
// <auto-generated> // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Gov.Lclb.Cllb.Interfaces { using Microsoft.Rest; using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for Objectidadoxiormreview. /// </summary> public static partial class ObjectidadoxiormreviewExtensions { /// <summary> /// Get objectid_adoxio_rmreview from principalobjectattributeaccessset /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='principalobjectattributeaccessid'> /// key: principalobjectattributeaccessid of principalobjectattributeaccess /// </param> /// <param name='select'> /// Select properties to be returned /// </param> /// <param name='expand'> /// Expand related entities /// </param> public static MicrosoftDynamicsCRMadoxioRmreview Get(this IObjectidadoxiormreview operations, string principalobjectattributeaccessid, IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>)) { return operations.GetAsync(principalobjectattributeaccessid, select, expand).GetAwaiter().GetResult(); } /// <summary> /// Get objectid_adoxio_rmreview from principalobjectattributeaccessset /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='principalobjectattributeaccessid'> /// key: principalobjectattributeaccessid of principalobjectattributeaccess /// </param> /// <param name='select'> /// Select properties to be returned /// </param> /// <param name='expand'> /// Expand related entities /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<MicrosoftDynamicsCRMadoxioRmreview> GetAsync(this IObjectidadoxiormreview operations, string principalobjectattributeaccessid, IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(principalobjectattributeaccessid, select, expand, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Get objectid_adoxio_rmreview from principalobjectattributeaccessset /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='principalobjectattributeaccessid'> /// key: principalobjectattributeaccessid of principalobjectattributeaccess /// </param> /// <param name='select'> /// Select properties to be returned /// </param> /// <param name='expand'> /// Expand related entities /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> public static HttpOperationResponse<MicrosoftDynamicsCRMadoxioRmreview> GetWithHttpMessages(this IObjectidadoxiormreview operations, string principalobjectattributeaccessid, IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>), Dictionary<string, List<string>> customHeaders = null) { return operations.GetWithHttpMessagesAsync(principalobjectattributeaccessid, select, expand, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult(); } } }
47.25
334
0.616057
[ "Apache-2.0" ]
BrendanBeachBC/jag-lcrb-carla-public
cllc-interfaces/Dynamics-Autorest/ObjectidadoxiormreviewExtensions.cs
4,347
C#
using System; using System.Windows; namespace Example.ChromiumFX.PackUri { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { this.InitializeComponent(); DataContext = new {text="Hello from resource"}; } protected override void OnClosed(EventArgs e) { this.wcBrowser.Dispose(); base.OnClosed(e); } } }
19.692308
59
0.564453
[ "MIT" ]
AhireSwati/TrendingCSharp
Examples/Example.ChromiumFX.PackUri/MainWindow.xaml.cs
514
C#
using JetBrains.Annotations; using System.Collections.Generic; namespace WireMock.Handlers { /// <summary> /// Handler to interact with the file system to handle folders and read and write static mapping files. /// </summary> public interface IFileSystemHandler { /// <summary> /// Gets the folder where the static mappings are located. For local file system, this would be `{CurrentFolder}/__admin/mappings`. /// </summary> /// <returns>The folder name.</returns> string GetMappingFolder(); /// <summary> /// Determines whether the given path refers to an existing directory on disk. /// </summary> /// <param name="path">The path.</param> /// <returns>true if path refers to an existing directory; false if the directory does not exist or an error occurs when trying to determine if the specified directory exists.</returns> bool FolderExists([NotNull] string path); /// <summary> /// Creates all directories and subdirectories in the specified path unless they already exist. /// </summary> /// <param name="path">The path.</param> void CreateFolder([NotNull] string path); /// <summary> /// Returns an enumerable collection of file names in a specified path. /// </summary> /// <param name="path">The path.</param> /// <param name="includeSubdirectories">A value indicating whether subdirectories should also included when enumerating files.</param> /// <returns>An enumerable collection of the full names (including paths) for the files in the directory (and optionally subdirectories) specified by path.</returns> IEnumerable<string> EnumerateFiles([NotNull] string path, bool includeSubdirectories); /// <summary> /// Read a static mapping file as text. /// </summary> /// <param name="path">The path (folder + filename with .json extension).</param> /// <returns>The file content as text.</returns> string ReadMappingFile([NotNull] string path); /// <summary> /// Write the static mapping file. /// </summary> /// <param name="path">The path (folder + filename with .json extension).</param> /// <param name="text">The text.</param> void WriteMappingFile([NotNull] string path, [NotNull] string text); /// <summary> /// Read a response body file as byte[]. /// </summary> /// <param name="path">The path or filename from the file to read.</param> /// <returns>The file content as bytes.</returns> byte[] ReadResponseBodyAsFile([NotNull] string path); /// <summary> /// Read a response body file as text. /// </summary> /// <param name="path">The path or filename from the file to read.</param> /// <returns>The file content as text.</returns> string ReadResponseBodyAsString([NotNull] string path); /// <summary> /// Delete a file. /// </summary> /// <param name="filename">The filename.</param> void DeleteFile([NotNull] string filename); /// <summary> /// Determines whether the given path refers to an existing file on disk. /// </summary> /// <param name="filename">The filename.</param> /// <returns>true if path refers to an existing file; false if the file does not exist.</returns> bool FileExists([NotNull] string filename); /// <summary> /// Write a file. /// </summary> /// <param name="filename">The filename.</param> /// <param name="bytes">The bytes.</param> void WriteFile([NotNull] string filename, [NotNull] byte[] bytes); /// <summary> /// Read a file as bytes. /// </summary> /// <param name="filename">The filename.</param> /// <returns>The file content as bytes.</returns> byte[] ReadFile([NotNull] string filename); } }
43.526882
193
0.610425
[ "Apache-2.0" ]
APIWT/WireMock.Net
src/WireMock.Net.Abstractions/Handlers/IFileSystemHandler.cs
4,050
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.DataBox.V20201101.Outputs { /// <summary> /// Copy log details for a storage account of a DataBox job /// </summary> [OutputType] public sealed class DataBoxAccountCopyLogDetailsResponse { /// <summary> /// Account name. /// </summary> public readonly string AccountName; /// <summary> /// Indicates the type of job details. /// Expected value is 'DataBox'. /// </summary> public readonly string CopyLogDetailsType; /// <summary> /// Link for copy logs. /// </summary> public readonly string CopyLogLink; /// <summary> /// Link for copy verbose logs. This will be set only when LogCollectionLevel is set to Verbose. /// </summary> public readonly string CopyVerboseLogLink; [OutputConstructor] private DataBoxAccountCopyLogDetailsResponse( string accountName, string copyLogDetailsType, string copyLogLink, string copyVerboseLogLink) { AccountName = accountName; CopyLogDetailsType = copyLogDetailsType; CopyLogLink = copyLogLink; CopyVerboseLogLink = copyVerboseLogLink; } } }
29.685185
104
0.623206
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/DataBox/V20201101/Outputs/DataBoxAccountCopyLogDetailsResponse.cs
1,603
C#
using System; using System.Threading.Tasks; using Newtonsoft.Json; namespace TdLib { /// <summary> /// Autogenerated TDLib APIs /// </summary> public static partial class TdApi { /// <summary> /// Removes 2-step verification password without previous password and access to recovery email address. The password can't be reset immediately and the request needs to be repeated after the specified time /// </summary> public class ResetPassword : Function<ResetPasswordResult> { /// <summary> /// Data type for serialization /// </summary> [JsonProperty("@type")] public override string DataType { get; set; } = "resetPassword"; /// <summary> /// Extra data attached to the function /// </summary> [JsonProperty("@extra")] public override string Extra { get; set; } } /// <summary> /// Removes 2-step verification password without previous password and access to recovery email address. The password can't be reset immediately and the request needs to be repeated after the specified time /// </summary> public static Task<ResetPasswordResult> ResetPasswordAsync( this Client client) { return client.ExecuteAsync(new ResetPassword { }); } } }
34.878049
214
0.597902
[ "MIT" ]
0x25CBFC4F/tdsharp
TDLib.Api/Functions/ResetPassword.cs
1,430
C#
using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using Odco.PointOfSales.EntityFrameworkCore; namespace Odco.PointOfSales.Migrations { [DbContext(typeof(PointOfSalesDbContext))] [Migration("20170621153937_Added_Description_And_IsActive_To_Role")] partial class Added_Description_And_IsActive_To_Role { protected override void BuildTargetModel(ModelBuilder modelBuilder) { modelBuilder .HasAnnotation("ProductVersion", "1.1.2") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("Abp.Application.Editions.Edition", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<long?>("DeleterUserId") .HasColumnType("bigint"); b.Property<DateTime?>("DeletionTime") .HasColumnType("datetime2"); b.Property<string>("DisplayName") .IsRequired() .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<DateTime?>("LastModificationTime") .HasColumnType("datetime2"); b.Property<long?>("LastModifierUserId") .HasColumnType("bigint"); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(32)") .HasMaxLength(32); b.HasKey("Id"); b.ToTable("AbpEditions"); }); modelBuilder.Entity("Abp.Application.Features.FeatureSetting", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<string>("Discriminator") .IsRequired() .HasColumnType("nvarchar(max)"); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<string>("Value") .IsRequired() .HasColumnType("nvarchar(2000)") .HasMaxLength(2000); b.HasKey("Id"); b.ToTable("AbpFeatures"); b.HasDiscriminator<string>("Discriminator").HasValue("FeatureSetting"); }); modelBuilder.Entity("Abp.Auditing.AuditLog", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); b.Property<string>("BrowserInfo") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<string>("ClientIpAddress") .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.Property<string>("ClientName") .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<string>("CustomData") .HasColumnType("nvarchar(2000)") .HasMaxLength(2000); b.Property<string>("Exception") .HasColumnType("nvarchar(2000)") .HasMaxLength(2000); b.Property<int>("ExecutionDuration") .HasColumnType("int"); b.Property<DateTime>("ExecutionTime") .HasColumnType("datetime2"); b.Property<int?>("ImpersonatorTenantId") .HasColumnType("int"); b.Property<long?>("ImpersonatorUserId") .HasColumnType("bigint"); b.Property<string>("MethodName") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<string>("Parameters") .HasColumnType("nvarchar(1024)") .HasMaxLength(1024); b.Property<string>("ServiceName") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<long?>("UserId") .HasColumnType("bigint"); b.HasKey("Id"); b.HasIndex("TenantId", "ExecutionDuration"); b.HasIndex("TenantId", "ExecutionTime"); b.HasIndex("TenantId", "UserId"); b.ToTable("AbpAuditLogs"); }); modelBuilder.Entity("Abp.Authorization.PermissionSetting", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<string>("Discriminator") .IsRequired() .HasColumnType("nvarchar(max)"); b.Property<bool>("IsGranted") .HasColumnType("bit"); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<int?>("TenantId") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("TenantId", "Name"); b.ToTable("AbpPermissions"); b.HasDiscriminator<string>("Discriminator").HasValue("PermissionSetting"); }); modelBuilder.Entity("Abp.Authorization.Roles.RoleClaim", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); b.Property<string>("ClaimType") .HasColumnType("nvarchar(450)"); b.Property<string>("ClaimValue") .HasColumnType("nvarchar(max)"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<int>("RoleId") .HasColumnType("int"); b.Property<int?>("TenantId") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("RoleId"); b.HasIndex("TenantId", "ClaimType"); b.ToTable("AbpRoleClaims"); }); modelBuilder.Entity("Abp.Authorization.Users.UserAccount", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<long?>("DeleterUserId") .HasColumnType("bigint"); b.Property<DateTime?>("DeletionTime") .HasColumnType("datetime2"); b.Property<string>("EmailAddress") .HasColumnType("nvarchar(450)"); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<DateTime?>("LastLoginTime") .HasColumnType("datetime2"); b.Property<DateTime?>("LastModificationTime") .HasColumnType("datetime2"); b.Property<long?>("LastModifierUserId") .HasColumnType("bigint"); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<long>("UserId") .HasColumnType("bigint"); b.Property<long?>("UserLinkId") .HasColumnType("bigint"); b.Property<string>("UserName") .HasColumnType("nvarchar(450)"); b.HasKey("Id"); b.HasIndex("EmailAddress"); b.HasIndex("UserName"); b.HasIndex("TenantId", "EmailAddress"); b.HasIndex("TenantId", "UserId"); b.HasIndex("TenantId", "UserName"); b.ToTable("AbpUserAccounts"); }); modelBuilder.Entity("Abp.Authorization.Users.UserClaim", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); b.Property<string>("ClaimType") .HasColumnType("nvarchar(450)"); b.Property<string>("ClaimValue") .HasColumnType("nvarchar(max)"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<long>("UserId") .HasColumnType("bigint"); b.HasKey("Id"); b.HasIndex("UserId"); b.HasIndex("TenantId", "ClaimType"); b.ToTable("AbpUserClaims"); }); modelBuilder.Entity("Abp.Authorization.Users.UserLogin", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); b.Property<string>("LoginProvider") .IsRequired() .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<string>("ProviderKey") .IsRequired() .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<long>("UserId") .HasColumnType("bigint"); b.HasKey("Id"); b.HasIndex("UserId"); b.HasIndex("TenantId", "UserId"); b.HasIndex("TenantId", "LoginProvider", "ProviderKey"); b.ToTable("AbpUserLogins"); }); modelBuilder.Entity("Abp.Authorization.Users.UserLoginAttempt", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); b.Property<string>("BrowserInfo") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<string>("ClientIpAddress") .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.Property<string>("ClientName") .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<byte>("Result") .HasColumnType("tinyint"); b.Property<string>("TenancyName") .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<long?>("UserId") .HasColumnType("bigint"); b.Property<string>("UserNameOrEmailAddress") .HasColumnType("nvarchar(255)") .HasMaxLength(255); b.HasKey("Id"); b.HasIndex("UserId", "TenantId"); b.HasIndex("TenancyName", "UserNameOrEmailAddress", "Result"); b.ToTable("AbpUserLoginAttempts"); }); modelBuilder.Entity("Abp.Authorization.Users.UserOrganizationUnit", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<long>("OrganizationUnitId") .HasColumnType("bigint"); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<long>("UserId") .HasColumnType("bigint"); b.HasKey("Id"); b.HasIndex("TenantId", "OrganizationUnitId"); b.HasIndex("TenantId", "UserId"); b.ToTable("AbpUserOrganizationUnits"); }); modelBuilder.Entity("Abp.Authorization.Users.UserRole", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<int>("RoleId") .HasColumnType("int"); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<long>("UserId") .HasColumnType("bigint"); b.HasKey("Id"); b.HasIndex("UserId"); b.HasIndex("TenantId", "RoleId"); b.HasIndex("TenantId", "UserId"); b.ToTable("AbpUserRoles"); }); modelBuilder.Entity("Abp.Authorization.Users.UserToken", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); b.Property<string>("LoginProvider") .HasColumnType("nvarchar(max)"); b.Property<string>("Name") .HasColumnType("nvarchar(max)"); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<long>("UserId") .HasColumnType("bigint"); b.Property<string>("Value") .HasColumnType("nvarchar(max)"); b.HasKey("Id"); b.HasIndex("UserId"); b.HasIndex("TenantId", "UserId"); b.ToTable("AbpUserTokens"); }); modelBuilder.Entity("Abp.BackgroundJobs.BackgroundJobInfo", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<bool>("IsAbandoned") .HasColumnType("bit"); b.Property<string>("JobArgs") .IsRequired() .HasColumnType("nvarchar(max)") .HasMaxLength(1048576); b.Property<string>("JobType") .IsRequired() .HasColumnType("nvarchar(512)") .HasMaxLength(512); b.Property<DateTime?>("LastTryTime") .HasColumnType("datetime2"); b.Property<DateTime>("NextTryTime") .HasColumnType("datetime2"); b.Property<byte>("Priority") .HasColumnType("tinyint"); b.Property<short>("TryCount") .HasColumnType("smallint"); b.HasKey("Id"); b.HasIndex("IsAbandoned", "NextTryTime"); b.ToTable("AbpBackgroundJobs"); }); modelBuilder.Entity("Abp.Configuration.Setting", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<DateTime?>("LastModificationTime") .HasColumnType("datetime2"); b.Property<long?>("LastModifierUserId") .HasColumnType("bigint"); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<long?>("UserId") .HasColumnType("bigint"); b.Property<string>("Value") .HasColumnType("nvarchar(2000)") .HasMaxLength(2000); b.HasKey("Id"); b.HasIndex("UserId"); b.HasIndex("TenantId", "Name"); b.ToTable("AbpSettings"); }); modelBuilder.Entity("Abp.Localization.ApplicationLanguage", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<long?>("DeleterUserId") .HasColumnType("bigint"); b.Property<DateTime?>("DeletionTime") .HasColumnType("datetime2"); b.Property<string>("DisplayName") .IsRequired() .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.Property<string>("Icon") .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<bool>("IsDisabled") .HasColumnType("bit"); b.Property<DateTime?>("LastModificationTime") .HasColumnType("datetime2"); b.Property<long?>("LastModifierUserId") .HasColumnType("bigint"); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(10)") .HasMaxLength(10); b.Property<int?>("TenantId") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("TenantId", "Name"); b.ToTable("AbpLanguages"); }); modelBuilder.Entity("Abp.Localization.ApplicationLanguageText", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<string>("Key") .IsRequired() .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<string>("LanguageName") .IsRequired() .HasColumnType("nvarchar(10)") .HasMaxLength(10); b.Property<DateTime?>("LastModificationTime") .HasColumnType("datetime2"); b.Property<long?>("LastModifierUserId") .HasColumnType("bigint"); b.Property<string>("Source") .IsRequired() .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<string>("Value") .IsRequired() .HasColumnType("nvarchar(max)") .HasMaxLength(67108864); b.HasKey("Id"); b.HasIndex("TenantId", "Source", "LanguageName", "Key"); b.ToTable("AbpLanguageTexts"); }); modelBuilder.Entity("Abp.Notifications.NotificationInfo", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<string>("Data") .HasColumnType("nvarchar(max)") .HasMaxLength(1048576); b.Property<string>("DataTypeName") .HasColumnType("nvarchar(512)") .HasMaxLength(512); b.Property<string>("EntityId") .HasColumnType("nvarchar(96)") .HasMaxLength(96); b.Property<string>("EntityTypeAssemblyQualifiedName") .HasColumnType("nvarchar(512)") .HasMaxLength(512); b.Property<string>("EntityTypeName") .HasColumnType("nvarchar(250)") .HasMaxLength(250); b.Property<string>("ExcludedUserIds") .HasColumnType("nvarchar(max)") .HasMaxLength(131072); b.Property<string>("NotificationName") .IsRequired() .HasColumnType("nvarchar(96)") .HasMaxLength(96); b.Property<byte>("Severity") .HasColumnType("tinyint"); b.Property<string>("TenantIds") .HasColumnType("nvarchar(max)") .HasMaxLength(131072); b.Property<string>("UserIds") .HasColumnType("nvarchar(max)") .HasMaxLength(131072); b.HasKey("Id"); b.ToTable("AbpNotifications"); }); modelBuilder.Entity("Abp.Notifications.NotificationSubscriptionInfo", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<string>("EntityId") .HasColumnType("nvarchar(96)") .HasMaxLength(96); b.Property<string>("EntityTypeAssemblyQualifiedName") .HasColumnType("nvarchar(512)") .HasMaxLength(512); b.Property<string>("EntityTypeName") .HasColumnType("nvarchar(250)") .HasMaxLength(250); b.Property<string>("NotificationName") .HasColumnType("nvarchar(96)") .HasMaxLength(96); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<long>("UserId") .HasColumnType("bigint"); b.HasKey("Id"); b.HasIndex("NotificationName", "EntityTypeName", "EntityId", "UserId"); b.HasIndex("TenantId", "NotificationName", "EntityTypeName", "EntityId", "UserId"); b.ToTable("AbpNotificationSubscriptions"); }); modelBuilder.Entity("Abp.Notifications.TenantNotificationInfo", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<string>("Data") .HasColumnType("nvarchar(max)") .HasMaxLength(1048576); b.Property<string>("DataTypeName") .HasColumnType("nvarchar(512)") .HasMaxLength(512); b.Property<string>("EntityId") .HasColumnType("nvarchar(96)") .HasMaxLength(96); b.Property<string>("EntityTypeAssemblyQualifiedName") .HasColumnType("nvarchar(512)") .HasMaxLength(512); b.Property<string>("EntityTypeName") .HasColumnType("nvarchar(250)") .HasMaxLength(250); b.Property<string>("NotificationName") .IsRequired() .HasColumnType("nvarchar(96)") .HasMaxLength(96); b.Property<byte>("Severity") .HasColumnType("tinyint"); b.Property<int?>("TenantId") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("TenantId"); b.ToTable("AbpTenantNotifications"); }); modelBuilder.Entity("Abp.Notifications.UserNotificationInfo", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<int>("State") .HasColumnType("int"); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<Guid>("TenantNotificationId") .HasColumnType("uniqueidentifier"); b.Property<long>("UserId") .HasColumnType("bigint"); b.HasKey("Id"); b.HasIndex("UserId", "State", "CreationTime"); b.ToTable("AbpUserNotifications"); }); modelBuilder.Entity("Abp.Organizations.OrganizationUnit", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); b.Property<string>("Code") .IsRequired() .HasColumnType("nvarchar(95)") .HasMaxLength(95); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<long?>("DeleterUserId") .HasColumnType("bigint"); b.Property<DateTime?>("DeletionTime") .HasColumnType("datetime2"); b.Property<string>("DisplayName") .IsRequired() .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<DateTime?>("LastModificationTime") .HasColumnType("datetime2"); b.Property<long?>("LastModifierUserId") .HasColumnType("bigint"); b.Property<long?>("ParentId") .HasColumnType("bigint"); b.Property<int?>("TenantId") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("ParentId"); b.HasIndex("TenantId", "Code"); b.ToTable("AbpOrganizationUnits"); }); modelBuilder.Entity("Odco.PointOfSales.Authorization.Roles.Role", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnType("nvarchar(max)"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<long?>("DeleterUserId") .HasColumnType("bigint"); b.Property<DateTime?>("DeletionTime") .HasColumnType("datetime2"); b.Property<string>("Description") .HasColumnType("nvarchar(max)") .HasMaxLength(5000); b.Property<string>("DisplayName") .IsRequired() .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.Property<bool>("IsActive") .HasColumnType("bit"); b.Property<bool>("IsDefault") .HasColumnType("bit"); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<bool>("IsStatic") .HasColumnType("bit"); b.Property<DateTime?>("LastModificationTime") .HasColumnType("datetime2"); b.Property<long?>("LastModifierUserId") .HasColumnType("bigint"); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(32)") .HasMaxLength(32); b.Property<string>("NormalizedName") .IsRequired() .HasColumnType("nvarchar(32)") .HasMaxLength(32); b.Property<int?>("TenantId") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("CreatorUserId"); b.HasIndex("DeleterUserId"); b.HasIndex("LastModifierUserId"); b.HasIndex("TenantId", "NormalizedName"); b.ToTable("AbpRoles"); }); modelBuilder.Entity("Odco.PointOfSales.Authorization.Users.User", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); b.Property<int>("AccessFailedCount") .HasColumnType("int"); b.Property<string>("AuthenticationSource") .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnType("nvarchar(max)"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<long?>("DeleterUserId") .HasColumnType("bigint"); b.Property<DateTime?>("DeletionTime") .HasColumnType("datetime2"); b.Property<string>("EmailAddress") .IsRequired() .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<string>("EmailConfirmationCode") .HasColumnType("nvarchar(328)") .HasMaxLength(328); b.Property<bool>("IsActive") .HasColumnType("bit"); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<bool>("IsEmailConfirmed") .HasColumnType("bit"); b.Property<bool>("IsLockoutEnabled") .HasColumnType("bit"); b.Property<bool>("IsPhoneNumberConfirmed") .HasColumnType("bit"); b.Property<bool>("IsTwoFactorEnabled") .HasColumnType("bit"); b.Property<DateTime?>("LastLoginTime") .HasColumnType("datetime2"); b.Property<DateTime?>("LastModificationTime") .HasColumnType("datetime2"); b.Property<long?>("LastModifierUserId") .HasColumnType("bigint"); b.Property<DateTime?>("LockoutEndDateUtc") .HasColumnType("datetime2"); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(32)") .HasMaxLength(32); b.Property<string>("NormalizedEmailAddress") .IsRequired() .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<string>("NormalizedUserName") .IsRequired() .HasColumnType("nvarchar(32)") .HasMaxLength(32); b.Property<string>("Password") .IsRequired() .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<string>("PasswordResetCode") .HasColumnType("nvarchar(328)") .HasMaxLength(328); b.Property<string>("PhoneNumber") .HasColumnType("nvarchar(max)"); b.Property<string>("SecurityStamp") .HasColumnType("nvarchar(max)"); b.Property<string>("Surname") .IsRequired() .HasColumnType("nvarchar(32)") .HasMaxLength(32); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<string>("UserName") .IsRequired() .HasColumnType("nvarchar(32)") .HasMaxLength(32); b.HasKey("Id"); b.HasIndex("CreatorUserId"); b.HasIndex("DeleterUserId"); b.HasIndex("LastModifierUserId"); b.HasIndex("TenantId", "NormalizedEmailAddress"); b.HasIndex("TenantId", "NormalizedUserName"); b.ToTable("AbpUsers"); }); modelBuilder.Entity("Odco.PointOfSales.MultiTenancy.Tenant", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int"); b.Property<string>("ConnectionString") .HasColumnType("nvarchar(1024)") .HasMaxLength(1024); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<long?>("DeleterUserId") .HasColumnType("bigint"); b.Property<DateTime?>("DeletionTime") .HasColumnType("datetime2"); b.Property<int?>("EditionId") .HasColumnType("int"); b.Property<bool>("IsActive") .HasColumnType("bit"); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<DateTime?>("LastModificationTime") .HasColumnType("datetime2"); b.Property<long?>("LastModifierUserId") .HasColumnType("bigint"); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<string>("TenancyName") .IsRequired() .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.HasKey("Id"); b.HasIndex("CreatorUserId"); b.HasIndex("DeleterUserId"); b.HasIndex("EditionId"); b.HasIndex("LastModifierUserId"); b.HasIndex("TenancyName"); b.ToTable("AbpTenants"); }); modelBuilder.Entity("Abp.Application.Features.EditionFeatureSetting", b => { b.HasBaseType("Abp.Application.Features.FeatureSetting"); b.Property<int>("EditionId") .HasColumnType("int"); b.HasIndex("EditionId", "Name"); b.ToTable("AbpFeatures"); b.HasDiscriminator().HasValue("EditionFeatureSetting"); }); modelBuilder.Entity("Abp.MultiTenancy.TenantFeatureSetting", b => { b.HasBaseType("Abp.Application.Features.FeatureSetting"); b.Property<int>("TenantId") .HasColumnType("int"); b.HasIndex("TenantId", "Name"); b.ToTable("AbpFeatures"); b.HasDiscriminator().HasValue("TenantFeatureSetting"); }); modelBuilder.Entity("Abp.Authorization.Roles.RolePermissionSetting", b => { b.HasBaseType("Abp.Authorization.PermissionSetting"); b.Property<int>("RoleId") .HasColumnType("int"); b.HasIndex("RoleId"); b.ToTable("AbpPermissions"); b.HasDiscriminator().HasValue("RolePermissionSetting"); }); modelBuilder.Entity("Abp.Authorization.Users.UserPermissionSetting", b => { b.HasBaseType("Abp.Authorization.PermissionSetting"); b.Property<long>("UserId") .HasColumnType("bigint"); b.HasIndex("UserId"); b.ToTable("AbpPermissions"); b.HasDiscriminator().HasValue("UserPermissionSetting"); }); modelBuilder.Entity("Abp.Authorization.Roles.RoleClaim", b => { b.HasOne("Odco.PointOfSales.Authorization.Roles.Role") .WithMany("Claims") .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.Authorization.Users.UserClaim", b => { b.HasOne("Odco.PointOfSales.Authorization.Users.User") .WithMany("Claims") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.Authorization.Users.UserLogin", b => { b.HasOne("Odco.PointOfSales.Authorization.Users.User") .WithMany("Logins") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.Authorization.Users.UserRole", b => { b.HasOne("Odco.PointOfSales.Authorization.Users.User") .WithMany("Roles") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.Authorization.Users.UserToken", b => { b.HasOne("Odco.PointOfSales.Authorization.Users.User") .WithMany("Tokens") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.Configuration.Setting", b => { b.HasOne("Odco.PointOfSales.Authorization.Users.User") .WithMany("Settings") .HasForeignKey("UserId"); }); modelBuilder.Entity("Abp.Organizations.OrganizationUnit", b => { b.HasOne("Abp.Organizations.OrganizationUnit", "Parent") .WithMany("Children") .HasForeignKey("ParentId"); }); modelBuilder.Entity("Odco.PointOfSales.Authorization.Roles.Role", b => { b.HasOne("Odco.PointOfSales.Authorization.Users.User", "CreatorUser") .WithMany() .HasForeignKey("CreatorUserId"); b.HasOne("Odco.PointOfSales.Authorization.Users.User", "DeleterUser") .WithMany() .HasForeignKey("DeleterUserId"); b.HasOne("Odco.PointOfSales.Authorization.Users.User", "LastModifierUser") .WithMany() .HasForeignKey("LastModifierUserId"); }); modelBuilder.Entity("Odco.PointOfSales.Authorization.Users.User", b => { b.HasOne("Odco.PointOfSales.Authorization.Users.User", "CreatorUser") .WithMany() .HasForeignKey("CreatorUserId"); b.HasOne("Odco.PointOfSales.Authorization.Users.User", "DeleterUser") .WithMany() .HasForeignKey("DeleterUserId"); b.HasOne("Odco.PointOfSales.Authorization.Users.User", "LastModifierUser") .WithMany() .HasForeignKey("LastModifierUserId"); }); modelBuilder.Entity("Odco.PointOfSales.MultiTenancy.Tenant", b => { b.HasOne("Odco.PointOfSales.Authorization.Users.User", "CreatorUser") .WithMany() .HasForeignKey("CreatorUserId"); b.HasOne("Odco.PointOfSales.Authorization.Users.User", "DeleterUser") .WithMany() .HasForeignKey("DeleterUserId"); b.HasOne("Abp.Application.Editions.Edition", "Edition") .WithMany() .HasForeignKey("EditionId"); b.HasOne("Odco.PointOfSales.Authorization.Users.User", "LastModifierUser") .WithMany() .HasForeignKey("LastModifierUserId"); }); modelBuilder.Entity("Abp.Application.Features.EditionFeatureSetting", b => { b.HasOne("Abp.Application.Editions.Edition", "Edition") .WithMany() .HasForeignKey("EditionId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.Authorization.Roles.RolePermissionSetting", b => { b.HasOne("Odco.PointOfSales.Authorization.Roles.Role") .WithMany("Permissions") .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.Authorization.Users.UserPermissionSetting", b => { b.HasOne("Odco.PointOfSales.Authorization.Users.User") .WithMany("Permissions") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); } } }
35.574156
117
0.432077
[ "MIT" ]
CipherLabz/Odco-PointOfSales-Material
aspnet-core/src/Odco.PointOfSales.EntityFrameworkCore/Migrations/20170621153937_Added_Description_And_IsActive_To_Role.Designer.cs
48,452
C#
using System.Windows; using Autodesk.Revit.Attributes; using Autodesk.Revit.DB; using Autodesk.Revit.UI; using Autodesk.Revit.UI.Selection; using RevitElementBipChecker.Model; using RevitElementBipChecker.View; using RevitElementBipChecker.Viewmodel; namespace RevitElementBipChecker.Command { [Transaction(TransactionMode.Manual)] [Regeneration(RegenerationOption.Manual)] [Journaling(JournalingMode.UsingCommandData)] public class Command : IExternalCommand { public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication uiapp = commandData.Application; UIDocument uidoc = uiapp.ActiveUIDocument; Document doc = uidoc.Document; BipCheckerViewmodel vm = new BipCheckerViewmodel(uidoc); MainWindows frMainWindows = new MainWindows(vm); frMainWindows.WindowStartupLocation = WindowStartupLocation.CenterScreen; frMainWindows.SetRevitAsWindowOwner(); frMainWindows.Show(); return Result.Succeeded; } } }
34.75
103
0.723022
[ "MIT" ]
chuongmep/RevitElementBipChecker
Command/Command.cs
1,114
C#
using LinqToDB.SqlQuery; namespace LinqToDB { using System; public static partial class Sql { public enum AggregateModifier { None, Distinct, All, } public enum From { None, First, Last } public enum Nulls { None, Respect, Ignore } public enum NullsPosition { None, First, Last } } public static class AnalyticFunctions { const string FunctionToken = "function"; #region Call Builders class OrderItemBuilder: Sql.IExtensionCallBuilder { public void Build(Sql.ISqExtensionBuilder builder) { var nulls = builder.GetValue<Sql.NullsPosition>("nulls"); switch (nulls) { case Sql.NullsPosition.None : break; case Sql.NullsPosition.First : builder.Expression = builder.Expression + " NULLS FIRST"; break; case Sql.NullsPosition.Last : builder.Expression = builder.Expression + " NULLS LAST"; break; default : throw new ArgumentOutOfRangeException(); } } } class ApplyAggregateModifier: Sql.IExtensionCallBuilder { public void Build(Sql.ISqExtensionBuilder builder) { var modifier = builder.GetValue<Sql.AggregateModifier>("modifier"); switch (modifier) { case Sql.AggregateModifier.None : break; case Sql.AggregateModifier.Distinct : builder.AddExpression("modifier", "DISTINCT"); break; case Sql.AggregateModifier.All : builder.AddExpression("modifier", "ALL"); break; default : throw new ArgumentOutOfRangeException(); } } } class ApplyNullsModifier: Sql.IExtensionCallBuilder { public void Build(Sql.ISqExtensionBuilder builder) { var nulls = builder.GetValue<Sql.Nulls>("nulls"); var nullsStr = GetNullsStr(nulls); if (!string.IsNullOrEmpty(nullsStr)) builder.AddExpression("modifier", nullsStr); } } static string GetNullsStr(Sql.Nulls nulls) { switch (nulls) { case Sql.Nulls.None : break; case Sql.Nulls.Respect : return "RESPECT NULLS"; case Sql.Nulls.Ignore : return "IGNORE NULLS"; default : throw new ArgumentOutOfRangeException(); } return string.Empty; } static string GetFromStr(Sql.From from) { switch (from) { case Sql.From.None : break; case Sql.From.First : return "FROM FIRST"; case Sql.From.Last : return "FROM LAST"; default : throw new ArgumentOutOfRangeException(); } return string.Empty; } class ApplyFromAndNullsModifier: Sql.IExtensionCallBuilder { public void Build(Sql.ISqExtensionBuilder builder) { var nulls = builder.GetValue<Sql.Nulls>("nulls"); var from = builder.GetValue<Sql.From>("from"); var fromStr = GetFromStr(from); var nullsStr = GetNullsStr(nulls); if (!string.IsNullOrEmpty(fromStr)) builder.AddExpression("from", fromStr); if (!string.IsNullOrEmpty(nullsStr)) builder.AddExpression("nulls", nullsStr); } } #endregion #region API Interfaces public interface IReadyToFunction<out TR> { [Sql.Extension("")] TR ToValue(); } public interface IReadyToFunctionOrOverWithPartition<out TR> : IReadyToFunction<TR> { [Sql.Extension("OVER({query_partition_clause?})", TokenName = "over")] IOverMayHavePartition<TR> Over(); } public interface IOverWithPartitionNeeded<out TR> { [Sql.Extension("OVER({query_partition_clause?})", TokenName = "over")] IOverMayHavePartition<TR> Over(); } public interface INeedOrderByAndMaybeOverWithPartition<out TR> { [Sql.Extension("ORDER BY {order_item, ', '}", TokenName = "order_by_clause")] [Sql.Extension("{expr}", TokenName = "order_item")] IOrderedAcceptOverReadyToFunction<TR> OrderBy<TKey>([ExprParameter] TKey expr); [Sql.Extension("ORDER BY {order_item, ', '}", TokenName = "order_by_clause")] [Sql.Extension("{expr}", TokenName = "order_item", BuilderType = typeof(OrderItemBuilder))] IOrderedAcceptOverReadyToFunction<TR> OrderBy<TKey>([ExprParameter] TKey expr, Sql.NullsPosition nulls); [Sql.Extension("ORDER BY {order_item, ', '}", TokenName = "order_by_clause")] [Sql.Extension("{expr} DESC", TokenName = "order_item")] IOrderedAcceptOverReadyToFunction<TR> OrderByDesc<TKey>([ExprParameter] TKey expr); [Sql.Extension("ORDER BY {order_item, ', '}", TokenName = "order_by_clause")] [Sql.Extension("{expr} DESC", TokenName = "order_item", BuilderType = typeof(OrderItemBuilder))] IOrderedAcceptOverReadyToFunction<TR> OrderByDesc<TKey>([ExprParameter] TKey expr, Sql.NullsPosition nulls); } public interface INeedSingleOrderByAndMaybeOverWithPartition<out TR> { [Sql.Extension("ORDER BY {order_item, ', '}", TokenName = "order_by_clause")] [Sql.Extension("{expr}", TokenName = "order_item")] IReadyToFunctionOrOverWithPartition<TR> OrderBy<TKey>([ExprParameter] TKey expr); [Sql.Extension("ORDER BY {order_item, ', '}", TokenName = "order_by_clause")] [Sql.Extension("{expr} DESC", TokenName = "order_item")] IReadyToFunctionOrOverWithPartition<TR> OrderByDesc<TKey>([ExprParameter] TKey expr); } public interface IOrderedAcceptOverReadyToFunction<out TR> : IReadyToFunctionOrOverWithPartition<TR> { [Sql.Extension("{expr}", TokenName = "order_item")] IOrderedAcceptOverReadyToFunction<TR> ThenBy<TKey>([ExprParameter] TKey expr); [Sql.Extension("{expr}", TokenName = "order_item", BuilderType = typeof(OrderItemBuilder))] IOrderedAcceptOverReadyToFunction<TR> ThenBy<TKey>([ExprParameter] TKey expr, Sql.NullsPosition nulls); [Sql.Extension("{expr} DESC", TokenName = "order_item")] IOrderedAcceptOverReadyToFunction<TR> ThenByDesc<TKey>([ExprParameter] TKey expr); [Sql.Extension("{expr} DESC", TokenName = "order_item", BuilderType = typeof(OrderItemBuilder))] IOrderedAcceptOverReadyToFunction<TR> ThenByDesc<TKey>([ExprParameter] TKey expr, Sql.NullsPosition nulls); } public interface IOverMayHavePartition<out TR> : IReadyToFunction<TR> { [Sql.Extension("PARTITION BY {expr, ', '}", TokenName = "query_partition_clause")] IReadyToFunction<TR> PartitionBy([ExprParameter("expr")] params object[] expressions); } public interface IPartitionedMayHaveOrder<out TR> : IReadyToFunction<TR>, INeedsOrderByOnly<TR> { } public interface IOverMayHavePartitionAndOrder<out TR> : IReadyToFunction<TR>, INeedsOrderByOnly<TR> { [Sql.Extension("PARTITION BY {expr, ', '}", TokenName = "query_partition_clause")] IPartitionedMayHaveOrder<TR> PartitionBy([ExprParameter("expr")] params object[] expressions); } public interface IAnalyticFunction<out TR> { [Sql.Extension("{function} OVER({query_partition_clause?}{_}{order_by_clause?}{_}{windowing_clause?})", TokenName = "over", ChainPrecedence = 10, SqlFlags = SqlFlags.Aggregate)] IReadyForFullAnalyticClause<TR> Over(); } public interface IAnalyticFunctionWithoutWindow<out TR> { [Sql.Extension("{function} OVER({query_partition_clause?}{_}{order_by_clause?})", TokenName = "over", ChainPrecedence = 10, SqlFlags = SqlFlags.Aggregate)] IOverMayHavePartitionAndOrder<TR> Over(); } public interface IAggregateFunction<out TR> : IAnalyticFunction<TR> {} public interface IAggregateFunctionSelfContained<out TR> : IAggregateFunction<TR>, IReadyToFunction<TR> {} public interface IOrderedReadyToFunction<out TR> : IReadyToFunction<TR> { [Sql.Extension("{expr}", TokenName = "order_item")] IOrderedReadyToFunction<TR> ThenBy<TKey>([ExprParameter] TKey expr); [Sql.Extension("{expr}", TokenName = "order_item", BuilderType = typeof(OrderItemBuilder))] IOrderedReadyToFunction<TR> ThenBy<TKey>([ExprParameter] TKey expr, Sql.NullsPosition nulls); [Sql.Extension("{expr} DESC", TokenName = "order_item")] IOrderedReadyToFunction<TR> ThenByDesc<TKey>([ExprParameter] TKey expr); [Sql.Extension("{expr} DESC", TokenName = "order_item", BuilderType = typeof(OrderItemBuilder))] IOrderedReadyToFunction<TR> ThenByDesc<TKey>([ExprParameter] TKey expr, Sql.NullsPosition nulls); } public interface INeedsWithinGroupWithOrderOnly<out TR> { [Sql.Extension("WITHIN GROUP ({order_by_clause})", TokenName = "within_group")] INeedsOrderByOnly<TR> WithinGroup { get; } } public interface INeedsWithinGroupWithOrderAndMaybePartition<out TR> { [Sql.Extension("WITHIN GROUP ({order_by_clause}){_}{over?}", TokenName = "within_group")] INeedOrderByAndMaybeOverWithPartition<TR> WithinGroup { get; } } public interface INeedsWithinGroupWithSingleOrderAndMaybePartition<out TR> { [Sql.Extension("WITHIN GROUP ({order_by_clause}){_}{over?}", TokenName = "within_group")] INeedSingleOrderByAndMaybeOverWithPartition<TR> WithinGroup { get; } } public interface INeedsOrderByOnly<out TR> { [Sql.Extension("ORDER BY {order_item, ', '}", TokenName = "order_by_clause")] [Sql.Extension("{expr}", TokenName = "order_item")] IOrderedReadyToFunction<TR> OrderBy<TKey>([ExprParameter] TKey expr); [Sql.Extension("ORDER BY {order_item, ', '}", TokenName = "order_by_clause")] [Sql.Extension("{expr}", TokenName = "order_item", BuilderType = typeof(OrderItemBuilder))] IOrderedReadyToFunction<TR> OrderBy<TKey>([ExprParameter] TKey expr, Sql.NullsPosition nulls); [Sql.Extension("ORDER BY {order_item, ', '}", TokenName = "order_by_clause")] [Sql.Extension("{expr} DESC", TokenName = "order_item")] IOrderedReadyToFunction<TR> OrderByDesc<TKey>([ExprParameter] TKey expr); [Sql.Extension("ORDER BY {order_item, ', '}", TokenName = "order_by_clause")] [Sql.Extension("{expr} DESC", TokenName = "order_item", BuilderType = typeof(OrderItemBuilder))] IOrderedReadyToFunction<TR> OrderByDesc<TKey>([ExprParameter] TKey expr, Sql.NullsPosition nulls); } #region Full Support public interface IReadyForSortingWithWindow<out TR> { [Sql.Extension("ORDER BY {order_item, ', '}", TokenName = "order_by_clause")] [Sql.Extension("{expr}", TokenName = "order_item")] IOrderedReadyToWindowing<TR> OrderBy<TKey>([ExprParameter("expr")] TKey keySelector); [Sql.Extension("ORDER BY {order_item, ', '}", TokenName = "order_by_clause")] [Sql.Extension("{expr}", TokenName = "order_item", BuilderType = typeof(OrderItemBuilder))] IOrderedReadyToWindowing<TR> OrderBy<TKey>([ExprParameter("expr")] TKey keySelector, Sql.NullsPosition nulls); [Sql.Extension("ORDER BY {order_item, ', '}", TokenName = "order_by_clause")] [Sql.Extension("{expr} DESC", TokenName = "order_item")] IOrderedReadyToWindowing<TR> OrderByDesc<TKey>([ExprParameter("expr")] TKey keySelector); [Sql.Extension("ORDER BY {order_item, ', '}", TokenName = "order_by_clause")] [Sql.Extension("{expr} DESC", TokenName = "order_item", BuilderType = typeof(OrderItemBuilder))] IOrderedReadyToWindowing<TR> OrderByDesc<TKey>([ExprParameter("expr")] TKey keySelector, Sql.NullsPosition nulls); } public interface IReadyForFullAnalyticClause<out TR> : IReadyToFunction<TR>, IReadyForSortingWithWindow<TR> { [Sql.Extension("PARTITION BY {expr, ', '}", TokenName = "query_partition_clause")] IPartitionDefinedReadyForSortingWithWindow<TR> PartitionBy([ExprParameter("expr")] params object[] expressions); } public interface IPartitionDefinedReadyForSortingWithWindow<out TR> : IReadyForSortingWithWindow<TR>, IReadyToFunction<TR> { } public interface IOrderedReadyToWindowing<out TR> : IReadyToFunction<TR> { [Sql.Extension("ROWS {boundary_clause}", TokenName = "windowing_clause")] IBoundaryExpected<TR> Rows { get; } [Sql.Extension("RANGE {boundary_clause}", TokenName = "windowing_clause")] IBoundaryExpected<TR> Range { get; } [Sql.Extension("{expr}", TokenName = "order_item")] IOrderedReadyToWindowing<TR> ThenBy<TKey>([ExprParameter] TKey expr); [Sql.Extension("{expr}", TokenName = "order_item", BuilderType = typeof(OrderItemBuilder))] IOrderedReadyToWindowing<TR> ThenBy<TKey>([ExprParameter] TKey expr, Sql.NullsPosition nulls); [Sql.Extension("{expr} DESC", TokenName = "order_item")] IOrderedReadyToWindowing<TR> ThenByDesc<TKey>([ExprParameter] TKey expr); [Sql.Extension("{expr} DESC", TokenName = "order_item", BuilderType = typeof(OrderItemBuilder))] IOrderedReadyToWindowing<TR> ThenByDesc<TKey>([ExprParameter] TKey expr, Sql.NullsPosition nulls); } public interface IBoundaryExpected<out TR> { [Sql.Extension("UNBOUNDED PRECEDING", TokenName = "boundary_clause")] IReadyToFunction<TR> UnboundedPreceding { get; } [Sql.Extension("CURRENT ROW", TokenName = "boundary_clause")] IReadyToFunction<TR> CurrentRow { get; } [Sql.Extension("{value_expr} PRECEDING", TokenName = "boundary_clause")] IReadyToFunction<TR> ValuePreceding<T>([ExprParameter("value_expr")] T value); [Sql.Extension("BETWEEN {start_boundary} AND {end_boundary}", TokenName = "boundary_clause")] IBetweenStartExpected<TR> Between { get; } } public interface IBetweenStartExpected<out TR> { [Sql.Extension("UNBOUNDED PRECEDING", TokenName = "start_boundary")] IAndExpected<TR> UnboundedPreceding { get; } [Sql.Extension("CURRENT ROW", TokenName = "start_boundary")] IAndExpected<TR> CurrentRow { get; } [Sql.Extension("{value_expr} PRECEDING", TokenName = "start_boundary")] IAndExpected<TR> ValuePreceding<T>([ExprParameter("value_expr")] T value); } public interface IAndExpected<out TR> { [Sql.Extension("")] ISecondBoundaryExpected<TR> And { get; } } public interface ISecondBoundaryExpected<out TR> { [Sql.Extension("UNBOUNDED FOLLOWING", TokenName = "end_boundary")] IReadyToFunction<TR> UnboundedFollowing { get; } [Sql.Extension("CURRENT ROW", TokenName = "end_boundary")] IReadyToFunction<TR> CurrentRow { get; } [Sql.Extension("{value_expr} PRECEDING", TokenName = "end_boundary")] IReadyToFunction<TR> ValuePreceding<T>([ExprParameter("value_expr")] T value); [Sql.Extension("{value_expr} FOLLOWING", TokenName = "end_boundary")] IReadyToFunction<TR> ValueFollowing<T>([ExprParameter("value_expr")] T value); } #endregion Full Support #endregion API Interfaces #region Analytic functions [Sql.Extension("AVG({expr})", TokenName = FunctionToken, ChainPrecedence = 1, SqlFlags = SqlFlags.Aggregate)] public static IAggregateFunctionSelfContained<T> Average<T>(this Sql.ISqlExtension ext, [ExprParameter] object expr) { throw new NotImplementedException(); } [Sql.Extension("AVG({modifier?}{_}{expr})", BuilderType = typeof(ApplyAggregateModifier), TokenName = FunctionToken, ChainPrecedence = 1, SqlFlags = SqlFlags.Aggregate)] public static IAggregateFunctionSelfContained<T> Average<T>(this Sql.ISqlExtension ext, [ExprParameter] object expr, Sql.AggregateModifier modifier) { throw new NotImplementedException(); } [Sql.Extension("CORR({expr1}, {expr2})", TokenName = FunctionToken, ChainPrecedence = 1, SqlFlags = SqlFlags.Aggregate)] public static IAggregateFunctionSelfContained<T> Corr<T>(this Sql.ISqlExtension ext, [ExprParameter] object expr1, [ExprParameter] object expr2) { throw new NotImplementedException(); } #region Count [Sql.Extension("COUNT(*)", TokenName = FunctionToken, ChainPrecedence = 1, SqlFlags = SqlFlags.Aggregate)] public static IAggregateFunctionSelfContained<long> Count(this Sql.ISqlExtension ext) { throw new NotImplementedException(); } [Sql.Extension("COUNT({expr})", TokenName = FunctionToken, ChainPrecedence = 1, SqlFlags = SqlFlags.Aggregate)] public static IAggregateFunctionSelfContained<T> Count<T>(this Sql.ISqlExtension ext, [ExprParameter] T expr) { throw new NotImplementedException(); } [Sql.Extension("COUNT({modifier?}{_}{expr})", BuilderType = typeof(ApplyAggregateModifier), TokenName = FunctionToken, ChainPrecedence = 1, SqlFlags = SqlFlags.Aggregate)] public static IAggregateFunctionSelfContained<long> Count(this Sql.ISqlExtension ext, [ExprParameter] object expr, Sql.AggregateModifier modifier) { throw new NotImplementedException(); } #endregion [Sql.Extension("COVAR_POP({expr1}, {expr2})", TokenName = FunctionToken, ChainPrecedence = 1, SqlFlags = SqlFlags.Aggregate)] public static IAggregateFunctionSelfContained<T> CovarPop<T>(this Sql.ISqlExtension ext, [ExprParameter] T expr1, [ExprParameter]T expr2) { throw new NotImplementedException(); } [Sql.Extension("COVAR_SAMP({expr1}, {expr2})", TokenName = FunctionToken, ChainPrecedence = 1, SqlFlags = SqlFlags.Aggregate)] public static IAggregateFunctionSelfContained<T> CovarSamp<T>(this Sql.ISqlExtension ext, [ExprParameter] T expr1, [ExprParameter]T expr2) { throw new NotImplementedException(); } [Sql.Extension("CUME_DIST({expr, ', '}) {within_group}", TokenName = FunctionToken, ChainPrecedence = 1, SqlFlags = SqlFlags.Aggregate)] public static INeedsWithinGroupWithOrderOnly<TR> CumeDist<TR>(this Sql.ISqlExtension ext, [ExprParameter] params object[] expr) { throw new NotImplementedException(); } [Sql.Extension("CUME_DIST()", TokenName = FunctionToken, ChainPrecedence = 1, SqlFlags = SqlFlags.Aggregate)] public static IAnalyticFunctionWithoutWindow<TR> CumeDist<TR>(this Sql.ISqlExtension ext) { throw new NotImplementedException(); } [Sql.Extension("DENSE_RANK({expr1}, {expr2}) {within_group}", TokenName = FunctionToken, ChainPrecedence = 1, SqlFlags = SqlFlags.Aggregate)] public static INeedsWithinGroupWithOrderOnly<long> DenseRank(this Sql.ISqlExtension ext, [ExprParameter] object expr1, [ExprParameter] object expr2) { throw new NotImplementedException(); } [Sql.Extension("DENSE_RANK()", TokenName = FunctionToken, ChainPrecedence = 1, SqlFlags = SqlFlags.Aggregate)] public static IAnalyticFunctionWithoutWindow<long> DenseRank(this Sql.ISqlExtension ext) { throw new NotImplementedException(); } [Sql.Extension("FIRST_VALUE({expr}{_}{modifier?})", TokenName = FunctionToken, BuilderType = typeof(ApplyNullsModifier), ChainPrecedence = 1, SqlFlags = SqlFlags.Aggregate)] public static IAggregateFunctionSelfContained<T> FirstValue<T>(this Sql.ISqlExtension ext, [ExprParameter] T expr, Sql.Nulls nulls) { throw new NotImplementedException(); } [Sql.Extension("LAG({expr}{_}{modifier?})", TokenName = FunctionToken, BuilderType = typeof(ApplyNullsModifier), ChainPrecedence = 1, SqlFlags = SqlFlags.Aggregate)] public static IAnalyticFunctionWithoutWindow<T> Lag<T>(this Sql.ISqlExtension ext, [ExprParameter] T expr, Sql.Nulls nulls) { throw new NotImplementedException(); } [Sql.Extension("LAG({expr}{_}{modifier?}, {offset}, {default})", TokenName = FunctionToken, BuilderType = typeof(ApplyNullsModifier), ChainPrecedence = 1, SqlFlags = SqlFlags.Aggregate)] public static IAnalyticFunctionWithoutWindow<T> Lag<T>(this Sql.ISqlExtension ext, [ExprParameter] T expr, Sql.Nulls nulls, [ExprParameter] int offset, [ExprParameter] int? @default) { throw new NotImplementedException(); } [Sql.Extension("LAST_VALUE({expr}{_}{modifier?})", TokenName = FunctionToken, BuilderType = typeof(ApplyNullsModifier), ChainPrecedence = 1, SqlFlags = SqlFlags.Aggregate)] public static IAggregateFunctionSelfContained<T> LastValue<T>(this Sql.ISqlExtension ext, [ExprParameter] T expr, Sql.Nulls nulls) { throw new NotImplementedException(); } [Sql.Extension("LEAD({expr}{_}{modifier?})", TokenName = FunctionToken, ChainPrecedence = 1, SqlFlags = SqlFlags.Aggregate)] public static IAnalyticFunctionWithoutWindow<T> Lead<T>(this Sql.ISqlExtension ext, [ExprParameter] T expr, Sql.Nulls nulls) { throw new NotImplementedException(); } [Sql.Extension("LEAD({expr}{_}{modifier?}, {offset}, {default})", TokenName = FunctionToken, BuilderType = typeof(ApplyNullsModifier), ChainPrecedence = 1, SqlFlags = SqlFlags.Aggregate)] public static IAnalyticFunctionWithoutWindow<T> Lead<T>(this Sql.ISqlExtension ext, [ExprParameter] T expr, Sql.Nulls nulls, [ExprParameter] int offset, [ExprParameter] int? @default) { throw new NotImplementedException(); } [Sql.Extension("LISTAGG({expr}) {within_group}", TokenName = FunctionToken, ChainPrecedence = 1, SqlFlags = SqlFlags.Aggregate)] public static INeedsWithinGroupWithOrderAndMaybePartition<string> ListAgg<T>(this Sql.ISqlExtension ext, [ExprParameter] T expr) { throw new NotImplementedException(); } [Sql.Extension("LISTAGG({expr}, {delimiter}) {within_group}", TokenName = FunctionToken, ChainPrecedence = 1, SqlFlags = SqlFlags.Aggregate)] public static INeedsWithinGroupWithOrderAndMaybePartition<string> ListAgg<T>(this Sql.ISqlExtension ext, [ExprParameter] T expr, [ExprParameter] string delimiter) { throw new NotImplementedException(); } [Sql.Extension("MAX({expr})", TokenName = FunctionToken, ChainPrecedence = 1, SqlFlags = SqlFlags.Aggregate)] public static IAggregateFunctionSelfContained<T> Max<T>(this Sql.ISqlExtension ext, [ExprParameter] T expr) { throw new NotImplementedException(); } [Sql.Extension("MAX({modifier?}{_}{expr})", BuilderType = typeof(ApplyAggregateModifier), TokenName = FunctionToken, ChainPrecedence = 1, SqlFlags = SqlFlags.Aggregate)] public static IAggregateFunctionSelfContained<T> Max<T>(this Sql.ISqlExtension ext, [ExprParameter] T expr, Sql.AggregateModifier modifier) { throw new NotImplementedException(); } [Sql.Extension("MEDIAN({expr})", TokenName = FunctionToken, ChainPrecedence = 1, SqlFlags = SqlFlags.Aggregate)] public static IReadyToFunctionOrOverWithPartition<T> Median<T>(this Sql.ISqlExtension ext, [ExprParameter] T expr) { throw new NotImplementedException(); } [Sql.Extension("MIN({expr})", TokenName = FunctionToken, ChainPrecedence = 1, SqlFlags = SqlFlags.Aggregate)] public static IAggregateFunctionSelfContained<T> Min<T>(this Sql.ISqlExtension ext, [ExprParameter] T expr) { throw new NotImplementedException(); } [Sql.Extension("MIN({modifier?}{_}{expr})", BuilderType = typeof(ApplyAggregateModifier), TokenName = FunctionToken, ChainPrecedence = 1, SqlFlags = SqlFlags.Aggregate)] public static IAggregateFunctionSelfContained<T> Min<T>(this Sql.ISqlExtension ext, [ExprParameter] T expr, Sql.AggregateModifier modifier) { throw new NotImplementedException(); } [Sql.Extension("NTH_VALUE({expr}, {n})", TokenName = FunctionToken, ChainPrecedence = 1, SqlFlags = SqlFlags.Aggregate)] public static IAggregateFunctionSelfContained<T> NthValue<T>(this Sql.ISqlExtension ext, [ExprParameter] T expr, [ExprParameter] long n) { throw new NotImplementedException(); } [Sql.Extension("NTH_VALUE({expr}, {n}){_}{from?}{_}{nulls?}", TokenName = FunctionToken, BuilderType = typeof(ApplyFromAndNullsModifier), ChainPrecedence = 1, SqlFlags = SqlFlags.Aggregate)] public static IAggregateFunctionSelfContained<T> NthValue<T>(this Sql.ISqlExtension ext, [ExprParameter] T expr, [ExprParameter] long n, Sql.From from, Sql.Nulls nulls) { throw new NotImplementedException(); } [Sql.Extension("NTILE({expr})", TokenName = FunctionToken, ChainPrecedence = 1, SqlFlags = SqlFlags.Aggregate)] public static IAnalyticFunctionWithoutWindow<T> NTile<T>(this Sql.ISqlExtension ext, [ExprParameter] T expr) { throw new NotImplementedException(); } [Sql.Extension("PERCENT_RANK({expr, ', '}) {within_group}", TokenName = FunctionToken, ChainPrecedence = 1, SqlFlags = SqlFlags.Aggregate)] public static INeedsWithinGroupWithOrderOnly<T> PercentRank<T>(this Sql.ISqlExtension ext, [ExprParameter] params object[] expr) { throw new NotImplementedException(); } [Sql.Extension("PERCENT_RANK()", TokenName = FunctionToken, ChainPrecedence = 1, SqlFlags = SqlFlags.Aggregate)] public static IAnalyticFunctionWithoutWindow<T> PercentRank<T>(this Sql.ISqlExtension ext) { throw new NotImplementedException(); } [Sql.Extension("PERCENTILE_CONT({expr}) {within_group}", TokenName = FunctionToken, ChainPrecedence = 1, SqlFlags = SqlFlags.Aggregate)] public static INeedsWithinGroupWithSingleOrderAndMaybePartition<T> PercentileCont<T>(this Sql.ISqlExtension ext, [ExprParameter] object expr) { throw new NotImplementedException(); } //TODO: check nulls support when ordering [Sql.Extension("PERCENTILE_DISC({expr}) {within_group}", TokenName = FunctionToken, ChainPrecedence = 1, SqlFlags = SqlFlags.Aggregate)] public static INeedsWithinGroupWithSingleOrderAndMaybePartition<T> PercentileDisc<T>(this Sql.ISqlExtension ext, [ExprParameter] object expr) { throw new NotImplementedException(); } [Sql.Extension("RANK({expr, ', '}) {within_group}", TokenName = FunctionToken, ChainPrecedence = 1, SqlFlags = SqlFlags.Aggregate)] public static INeedsWithinGroupWithOrderOnly<long> Rank(this Sql.ISqlExtension ext, [ExprParameter] params object[] expr) { throw new NotImplementedException(); } [Sql.Extension("RANK()", TokenName = FunctionToken, ChainPrecedence = 1, SqlFlags = SqlFlags.Aggregate)] public static IAnalyticFunctionWithoutWindow<long> Rank(this Sql.ISqlExtension ext) { throw new NotImplementedException(); } [Sql.Extension("RATIO_TO_REPORT({expr}) {over}", TokenName = FunctionToken, ChainPrecedence = 1, SqlFlags = SqlFlags.Aggregate)] public static IOverWithPartitionNeeded<TR> RatioToReport<TR>(this Sql.ISqlExtension ext, [ExprParameter] object expr) { throw new NotImplementedException(); } #region REGR_ function [Sql.Extension("REGR_SLOPE({expr1}, {expr2})", TokenName = FunctionToken, ChainPrecedence = 1, SqlFlags = SqlFlags.Aggregate)] public static IAggregateFunctionSelfContained<T> RegrSlope<T>(this Sql.ISqlExtension ext, [ExprParameter] object expr1, [ExprParameter] object expr2) { throw new NotImplementedException(); } [Sql.Extension("REGR_INTERCEPT({expr1}, {expr2})", TokenName = FunctionToken, ChainPrecedence = 1, SqlFlags = SqlFlags.Aggregate)] public static IAggregateFunctionSelfContained<T> RegrIntercept<T>(this Sql.ISqlExtension ext, [ExprParameter] object expr1, [ExprParameter] object expr2) { throw new NotImplementedException(); } [Sql.Extension("REGR_COUNT({expr1}, {expr2})", TokenName = FunctionToken, ChainPrecedence = 1, SqlFlags = SqlFlags.Aggregate)] public static IAggregateFunctionSelfContained<long> RegrCount(this Sql.ISqlExtension ext, [ExprParameter] object expr1, [ExprParameter] object expr2) { throw new NotImplementedException(); } [Sql.Extension("REGR_R2({expr1}, {expr2})", TokenName = FunctionToken, ChainPrecedence = 1, SqlFlags = SqlFlags.Aggregate)] public static IAggregateFunctionSelfContained<T> RegrR2<T>(this Sql.ISqlExtension ext, [ExprParameter] object expr1, [ExprParameter] object expr2) { throw new NotImplementedException(); } [Sql.Extension("REGR_AVGX({expr1}, {expr2})", TokenName = FunctionToken, ChainPrecedence = 1, SqlFlags = SqlFlags.Aggregate)] public static IAggregateFunctionSelfContained<T> RegrAvgX<T>(this Sql.ISqlExtension ext, [ExprParameter] object expr1, [ExprParameter] object expr2) { throw new NotImplementedException(); } [Sql.Extension("REGR_AVGY({expr1}, {expr2})", TokenName = FunctionToken, ChainPrecedence = 1, SqlFlags = SqlFlags.Aggregate)] public static IAggregateFunctionSelfContained<T> RegrAvgY<T>(this Sql.ISqlExtension ext, [ExprParameter] object expr1, [ExprParameter] object expr2) { throw new NotImplementedException(); } // ReSharper disable once InconsistentNaming [Sql.Extension("REGR_SXX({expr1}, {expr2})", TokenName = FunctionToken, ChainPrecedence = 1, SqlFlags = SqlFlags.Aggregate)] public static IAggregateFunctionSelfContained<T> RegrSXX<T>(this Sql.ISqlExtension ext, [ExprParameter] object expr1, [ExprParameter] object expr2) { throw new NotImplementedException(); } // ReSharper disable once InconsistentNaming [Sql.Extension("REGR_SYY({expr1}, {expr2})", TokenName = FunctionToken, ChainPrecedence = 1, SqlFlags = SqlFlags.Aggregate)] public static IAggregateFunctionSelfContained<T> RegrSYY<T>(this Sql.ISqlExtension ext, [ExprParameter] object expr1, [ExprParameter] object expr2) { throw new NotImplementedException(); } // ReSharper disable once InconsistentNaming [Sql.Extension("REGR_SXY({expr1}, {expr2})", TokenName = FunctionToken, ChainPrecedence = 1, SqlFlags = SqlFlags.Aggregate)] public static IAggregateFunctionSelfContained<T> RegrSXY<T>(this Sql.ISqlExtension ext, [ExprParameter] object expr1, [ExprParameter] object expr2) { throw new NotImplementedException(); } #endregion [Sql.Extension("ROW_NUMBER()", TokenName = FunctionToken, ChainPrecedence = 1, SqlFlags = SqlFlags.Aggregate)] public static IAnalyticFunctionWithoutWindow<long> RowNumber(this Sql.ISqlExtension ext) { throw new NotImplementedException(); } //TODO: support of aggreagate functions // [Sql.Extension("STDDEV({expr})", Names = AggregateFunctionName + "," + AnalyticFunctionName, ChainPrecedence = 1, AllowedScope = SqlScope.Select | SqlScope.OrderBy)] // public static IAggregateFunctionSelfContained<double> StdDev<TEntity, TV>(this IEnumerable<TEntity> source, [ExprParameter] Func<TEntity, TV> expr) // { // throw new NotImplementedException(); // } [Sql.Extension("STDDEV({expr})", TokenName = FunctionToken, ChainPrecedence = 1, SqlFlags = SqlFlags.Aggregate)] public static IAggregateFunctionSelfContained<T> StdDev<T>(this Sql.ISqlExtension ext, [ExprParameter] object expr) { throw new NotImplementedException(); } [Sql.Extension("STDDEV({modifier?}{_}{expr})", TokenName = FunctionToken, BuilderType = typeof(ApplyAggregateModifier), ChainPrecedence = 1, SqlFlags = SqlFlags.Aggregate)] public static IAggregateFunctionSelfContained<T> StdDev<T>(this Sql.ISqlExtension ext, [ExprParameter] object expr, Sql.AggregateModifier modifier) { throw new NotImplementedException(); } [Sql.Extension("STDDEV_POP({expr})", TokenName = FunctionToken, ChainPrecedence = 1, SqlFlags = SqlFlags.Aggregate)] public static IAggregateFunctionSelfContained<T> StdDevPop<T>(this Sql.ISqlExtension ext, [ExprParameter] object expr) { throw new NotImplementedException(); } [Sql.Extension("STDDEV_SAMP({expr})", TokenName = FunctionToken, ChainPrecedence = 1, SqlFlags = SqlFlags.Aggregate)] public static IAggregateFunctionSelfContained<T> StdDevSamp<T>(this Sql.ISqlExtension ext, [ExprParameter] object expr) { throw new NotImplementedException(); } [Sql.Extension("SUM({expr})", TokenName = FunctionToken, ChainPrecedence = 1, SqlFlags = SqlFlags.Aggregate)] public static IAggregateFunctionSelfContained<T> Sum<T>(this Sql.ISqlExtension ext, [ExprParameter] T expr) { throw new NotImplementedException(); } [Sql.Extension("SUM({modifier?}{_}{expr})" , BuilderType = typeof(ApplyAggregateModifier), TokenName = FunctionToken, ChainPrecedence = 1, SqlFlags = SqlFlags.Aggregate)] public static IAggregateFunctionSelfContained<T> Sum<T>(this Sql.ISqlExtension ext, [ExprParameter] T expr, Sql.AggregateModifier modifier) { throw new NotImplementedException(); } [Sql.Extension("VAR_POP({expr})", TokenName = FunctionToken, ChainPrecedence = 1, SqlFlags = SqlFlags.Aggregate)] public static IAggregateFunctionSelfContained<T> VarPop<T>(this Sql.ISqlExtension ext, [ExprParameter] object expr) { throw new NotImplementedException(); } [Sql.Extension("VAR_SAMP({expr})", TokenName = FunctionToken, ChainPrecedence = 1, SqlFlags = SqlFlags.Aggregate)] public static IAggregateFunctionSelfContained<T> VarSamp<T>(this Sql.ISqlExtension ext, [ExprParameter] object expr) { throw new NotImplementedException(); } [Sql.Extension("VARIANCE({expr})", TokenName = FunctionToken, ChainPrecedence = 1, SqlFlags = SqlFlags.Aggregate)] public static IAggregateFunctionSelfContained<T> Variance<T>(this Sql.ISqlExtension ext, [ExprParameter] object expr) { throw new NotImplementedException(); } [Sql.Extension("VARIANCE({modifier?}{_}{expr})", BuilderType = typeof(ApplyAggregateModifier), TokenName = FunctionToken, ChainPrecedence = 1, SqlFlags = SqlFlags.Aggregate)] public static IAggregateFunctionSelfContained<T> Variance<T>(this Sql.ISqlExtension ext, [ExprParameter] object expr, Sql.AggregateModifier modifier) { throw new NotImplementedException(); } [Sql.Extension("{function} KEEP (DENSE_RANK FIRST {order_by_clause}){_}{over?}", ChainPrecedence = 10, SqlFlags = SqlFlags.Aggregate)] public static INeedOrderByAndMaybeOverWithPartition<TR> KeepFirst<TR>(this IAggregateFunction<TR> ext) { throw new NotImplementedException(); } [Sql.Extension("{function} KEEP (DENSE_RANK LAST {order_by_clause}){_}{over?}", ChainPrecedence = 10, SqlFlags = SqlFlags.Aggregate)] public static INeedOrderByAndMaybeOverWithPartition<TR> KeepLast<TR>(this IAggregateFunction<TR> ext) { throw new NotImplementedException(); } #endregion Analytic functions } }
43.164706
192
0.740044
[ "MIT" ]
jogibear9988/linq2db
Source/Sql/Sql.Analytic.cs
33,023
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.Inputs { public sealed class WebAclRuleStatementAndStatementStatementAndStatementStatementOrStatementStatementByteMatchStatementTextTransformationArgs : Pulumi.ResourceArgs { /// <summary> /// The relative processing order for multiple transformations that are defined for a rule statement. AWS WAF processes all transformations, from lowest priority to highest, before inspecting the transformed content. /// </summary> [Input("priority", required: true)] public Input<int> Priority { get; set; } = null!; /// <summary> /// The transformation to apply, please refer to the Text Transformation [documentation](https://docs.aws.amazon.com/waf/latest/APIReference/API_TextTransformation.html) for more details. /// </summary> [Input("type", required: true)] public Input<string> Type { get; set; } = null!; public WebAclRuleStatementAndStatementStatementAndStatementStatementOrStatementStatementByteMatchStatementTextTransformationArgs() { } } }
43.90625
224
0.725267
[ "ECL-2.0", "Apache-2.0" ]
RafalSumislawski/pulumi-aws
sdk/dotnet/WafV2/Inputs/WebAclRuleStatementAndStatementStatementAndStatementStatementOrStatementStatementByteMatchStatementTextTransformationArgs.cs
1,405
C#
using Caliburn.Micro; using Microsoft.Win32; using SharpVectors.Converters; using SharpVectors.Renderers.Wpf; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Media; namespace Vectorize.Editor.Features.Workbench { public class PreviewViewModel : Screen { private string text; private ImageSource image; public string Text { get => text; private set => Set(ref text, value); } public ImageSource Image { get => image; private set => Set(ref image, value); } public void Update(string svg) { Text = svg; var drawSettings = new WpfDrawingSettings(); using (var svgStream = new MemoryStream(Encoding.Default.GetBytes(svg))) using (var stream = new FileSvgReader(drawSettings)) { Image = new DrawingImage(stream.Read(svgStream)); } } public async Task SaveSvgToFile() { if (string.IsNullOrWhiteSpace(Text)) return; var dialog = new SaveFileDialog(); dialog.Filter = "SVG files (*.svg)|*.svg"; dialog.InitialDirectory = Environment.CurrentDirectory; if (dialog.ShowDialog() == true) { var file = new FileInfo(dialog.FileName); using (var stream = file.OpenWrite()) using (var writer = new StreamWriter(stream)) { await writer.WriteLineAsync(Text); } } } } }
27.564516
84
0.561147
[ "MIT" ]
vectorize-dsl/antlr
Vectorize.Editor/Features/Workbench/PreviewViewModel.cs
1,711
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Net; using System.Threading; using System.Threading.Tasks; using LibUsbDotNet.Main; using Meadow.CLI.Core.DeviceManagement; using Meadow.CLI.Core.Exceptions; using Meadow.CLI.Core.Internals.Dfu; using Meadow.CLI.Core.Internals.MeadowCommunication.ReceiveClasses; namespace Meadow.CLI.Core.Devices { //a simple model object that represents a meadow device including connection public sealed class MeadowDeviceHelper : IDisposable { private IMeadowDevice _meadowDevice; public TimeSpan DefaultTimeout = TimeSpan.FromSeconds(60); public readonly ILogger Logger; public IMeadowDevice MeadowDevice => _meadowDevice; public MeadowDeviceHelper(IMeadowDevice meadow, ILogger logger) { _meadowDevice = meadow; DeviceInfo = meadow.DeviceInfo ?? throw new ArgumentException( "Device is not initialized, missing DeviceInfo", nameof(meadow)); Logger = logger; } public MeadowDeviceInfo DeviceInfo { get; private set; } public Task<IDictionary<string, uint>> GetFilesAndCrcsAsync(TimeSpan timeout, int partition = 0, CancellationToken cancellationToken = default) { return _meadowDevice.GetFilesAndCrcsAsync(timeout, partition, cancellationToken); } public Task<IList<string>> GetFilesAndFoldersAsync(TimeSpan timeout, CancellationToken cancellationToken = default) { return _meadowDevice.GetFilesAndFoldersAsync(timeout, cancellationToken); } public Task<FileTransferResult> WriteFileAsync(string sourceFileName, string destinationFileName, TimeSpan timeout, CancellationToken cancellationToken = default) { return _meadowDevice.WriteFileAsync(sourceFileName, destinationFileName, timeout, cancellationToken); } public Task DeleteFileAsync(string fileName, uint partition = 0, CancellationToken cancellationToken = default) { return _meadowDevice.DeleteFileAsync(fileName, partition, cancellationToken); } public Task EraseFlashAsync(CancellationToken cancellationToken = default) { return _meadowDevice.EraseFlashAsync(cancellationToken); } public Task VerifyErasedFlashAsync(CancellationToken cancellationToken = default) { return _meadowDevice.VerifyErasedFlashAsync(cancellationToken); } public Task FormatFileSystemAsync(uint partition = 0, CancellationToken cancellationToken = default) { return _meadowDevice.FormatFileSystemAsync(partition, cancellationToken); } public Task RenewFileSystemAsync(CancellationToken cancellationToken = default) { return _meadowDevice.RenewFileSystemAsync(cancellationToken); } public async Task UpdateMonoRuntimeAsync(string fileName, uint partition = 0, CancellationToken cancellationToken = default) { Logger.LogInformation("Starting Mono Runtime Update"); Logger.LogDebug("Calling Mono Disable"); await MonoDisableAsync(cancellationToken: cancellationToken) .ConfigureAwait(false); await ReInitializeMeadowAsync(cancellationToken); Trace.Assert(await GetMonoRunStateAsync(cancellationToken).ConfigureAwait(false) == false, "Meadow was expected to have Mono Disabled"); Logger.LogInformation("Updating Mono Runtime"); await _meadowDevice.UpdateMonoRuntimeAsync(fileName, partition, cancellationToken).ConfigureAwait(false); } public Task WriteFileToEspFlashAsync(string fileName, uint partition = 0, string? mcuDestAddress = null, CancellationToken cancellationToken = default) { return _meadowDevice.WriteFileToEspFlashAsync( fileName, partition, mcuDestAddress, cancellationToken); } public Task FlashEspAsync(string? sourcePath = null, CancellationToken cancellationToken = default) { return _meadowDevice.FlashEspAsync(sourcePath, cancellationToken); } //Get's the OS version as a string, used by the download manager public async Task<string> GetOSVersion(TimeSpan timeout, CancellationToken cancellationToken = default) { var deviceInfo = await GetDeviceInfoAsync(timeout, cancellationToken); return deviceInfo.MeadowOsVersion.Split(' ')[0]; // we want the first part of e.g. '0.5.3.0 (Oct 13 2021 13:39:12)' } public Task<MeadowDeviceInfo> GetDeviceInfoAsync(TimeSpan timeout, CancellationToken cancellationToken = default) { return _meadowDevice.GetDeviceInfoAsync(timeout, cancellationToken); } public Task<string?> GetDeviceNameAsync(TimeSpan timeout, CancellationToken cancellationToken = default) { return _meadowDevice.GetDeviceNameAsync(timeout, cancellationToken); } public Task<bool> GetMonoRunStateAsync(CancellationToken cancellationToken = default) { return _meadowDevice.GetMonoRunStateAsync(cancellationToken); } public async Task MonoDisableAsync(bool force = false, CancellationToken cancellationToken = default) { var endTime = DateTime.UtcNow.Add(TimeSpan.FromSeconds(60)); bool monoRunState; while ((monoRunState = await GetMonoRunStateAsync(cancellationToken).ConfigureAwait(false)) || force && endTime > DateTime.UtcNow) { Logger.LogDebug("Sending Mono Disable Request (Forced? {forced})", force); await _meadowDevice.MonoDisableAsync(cancellationToken); Logger.LogDebug("Waiting for Meadow to cycle"); await Task.Delay(3000, cancellationToken) .ConfigureAwait(false); Logger.LogDebug("Re-initialize the device"); await ReInitializeMeadowAsync(cancellationToken).ConfigureAwait(false); force = false; } if (monoRunState) throw new Exception("Failed to stop mono."); } public async Task MonoEnableAsync(bool force = false, CancellationToken cancellationToken = default) { var endTime = DateTime.UtcNow.Add(TimeSpan.FromSeconds(60)); bool monoRunState; while ((monoRunState = await GetMonoRunStateAsync(cancellationToken).ConfigureAwait(false)) == false || force && endTime > DateTime.UtcNow) { Logger.LogDebug("Sending Mono Enable Request (Forced? {forced})", force); await _meadowDevice.MonoEnableAsync(cancellationToken) .ConfigureAwait(false); Logger.LogDebug("Waiting for Meadow to cycle"); await Task.Delay(1000, cancellationToken) .ConfigureAwait(false); Logger.LogDebug("Re-initialize the device"); await ReInitializeMeadowAsync(cancellationToken).ConfigureAwait(false); force = false; } if (!monoRunState) throw new Exception("Failed to enable mono."); } public async Task ResetMeadowAsync(CancellationToken cancellationToken = default) { await _meadowDevice.ResetMeadowAsync(cancellationToken).ConfigureAwait(false); await Task.Delay(1000, cancellationToken) .ConfigureAwait(false); await ReInitializeMeadowAsync(cancellationToken) .ConfigureAwait(false); } public Task MonoFlashAsync(CancellationToken cancellationToken = default) { return _meadowDevice.MonoFlashAsync(cancellationToken); } public Task EnterDfuModeAsync(CancellationToken cancellationToken = default) { return _meadowDevice.EnterDfuModeAsync(cancellationToken); } public Task NshEnableAsync(CancellationToken cancellationToken = default) { return _meadowDevice.NshEnableAsync(cancellationToken); } public Task NshDisableAsync(CancellationToken cancellationToken = default) { return _meadowDevice.NshDisableAsync(cancellationToken); } public Task TraceEnableAsync(CancellationToken cancellationToken = default) { return _meadowDevice.TraceEnableAsync(cancellationToken); } public Task SetTraceLevelAsync(uint traceLevel, CancellationToken cancellationToken = default) { return _meadowDevice.SetTraceLevelAsync(traceLevel, cancellationToken); } public Task TraceDisableAsync(CancellationToken cancellationToken = default) { return _meadowDevice.TraceDisableAsync(cancellationToken); } public Task SetDeveloper1(uint userData, CancellationToken cancellationToken = default) { return _meadowDevice.SetDeveloper1(userData, cancellationToken); } public Task SetDeveloper2(uint userData, CancellationToken cancellationToken = default) { return _meadowDevice.SetDeveloper2(userData, cancellationToken); } public Task SetDeveloper3(uint userData, CancellationToken cancellationToken = default) { return _meadowDevice.SetDeveloper3(userData, cancellationToken); } public Task SetDeveloper4(uint userData, CancellationToken cancellationToken = default) { return _meadowDevice.SetDeveloper4(userData, cancellationToken); } public Task Uart1Apps(CancellationToken cancellationToken = default) { return _meadowDevice.Uart1Apps(cancellationToken); } public Task Uart1Trace(CancellationToken cancellationToken = default) { return _meadowDevice.Uart1Trace(cancellationToken); } public Task QspiWriteAsync(int value, CancellationToken cancellationToken = default) { return _meadowDevice.QspiWriteAsync(value, cancellationToken); } public Task QspiReadAsync(int value, CancellationToken cancellationToken = default) { return _meadowDevice.QspiReadAsync(value, cancellationToken); } public Task QspiInitAsync(int value, CancellationToken cancellationToken = default) { return _meadowDevice.QspiInitAsync(value, cancellationToken); } public async Task DeployAppAsync(string fileName, bool includePdbs = true, CancellationToken cancellationToken = default) { await MonoDisableAsync(cancellationToken: cancellationToken) .ConfigureAwait(false); string osVersion = await GetOSVersion(TimeSpan.FromSeconds(30), cancellationToken) .ConfigureAwait(false); await _meadowDevice.DeployAppAsync(fileName, osVersion, includePdbs, cancellationToken) .ConfigureAwait(false); await MonoEnableAsync(cancellationToken: cancellationToken) .ConfigureAwait(false); } public Task ForwardVisualStudioDataToMonoAsync(byte[] debuggerData, uint userData, CancellationToken cancellationToken = default) { return _meadowDevice.ForwardVisualStudioDataToMonoAsync( debuggerData, userData, cancellationToken); } /// <summary> /// Start a session to debug an application on the Meadow /// </summary> /// <param name="port">The port to use for the debugging proxy</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> for cancelling the operation</param> /// <returns>A running <see cref="DebuggingServer"/> that is available for connections</returns> public async Task<DebuggingServer> StartDebuggingSessionAsync(int port, CancellationToken cancellationToken) { await MonoEnableAsync(cancellationToken: cancellationToken); await _meadowDevice.StartDebuggingAsync(port, cancellationToken) .ConfigureAwait(false); await Task.Delay(1000, cancellationToken) .ConfigureAwait(false); await ReInitializeMeadowAsync(cancellationToken).ConfigureAwait(false); if (_meadowDevice == null) throw new DeviceNotFoundException(); var endpoint = new IPEndPoint(IPAddress.Loopback, port); var debuggingServer = new DebuggingServer(_meadowDevice, endpoint, Logger); await debuggingServer.StartListeningAsync(cancellationToken).ConfigureAwait(false); return debuggingServer; } public Task<string?> GetInitialBytesFromFile(string fileName, uint partition = 0, CancellationToken cancellationToken = default) { return _meadowDevice.GetInitialBytesFromFile(fileName, partition, cancellationToken); } public Task RestartEsp32Async(CancellationToken cancellationToken = default) { return _meadowDevice.RestartEsp32Async(cancellationToken); } public Task<string?> GetDeviceMacAddressAsync(CancellationToken cancellationToken = default) { return _meadowDevice.GetDeviceMacAddressAsync(cancellationToken); } public bool IsDeviceInitialized() { return _meadowDevice.IsDeviceInitialized(); } public async Task ReInitializeMeadowAsync(CancellationToken cancellationToken = default) { var serialNumber = DeviceInfo.SerialNumber; string? serialPort = null; IMeadowDevice? meadow = null; if(_meadowDevice is MeadowSerialDevice device) { serialPort = device.SerialPort?.PortName; } _meadowDevice?.Dispose(); await Task.Delay(1000, cancellationToken) .ConfigureAwait(false); //try the old port first, if we still have it if (string.IsNullOrWhiteSpace(serialPort) == false) { meadow = await MeadowDeviceManager.GetMeadowForSerialPort(serialPort!, false, Logger); } meadow ??= await MeadowDeviceManager.FindMeadowBySerialNumber( serialNumber, Logger, cancellationToken: cancellationToken) .ConfigureAwait(false); await Task.Delay(1000, cancellationToken) .ConfigureAwait(false); _meadowDevice = meadow ?? throw new Exception($"Meadow not found. Serial Number {serialNumber}"); } public async Task FlashOsAsync(string? runtimePath = null, bool skipRuntime = false, bool skipEsp = false, CancellationToken cancellationToken = default) { try { if (skipRuntime == false) { await MonoDisableAsync(cancellationToken: cancellationToken) .ConfigureAwait(false); await Task.Delay(2000); // Again, verify that Mono is disabled Trace.Assert(await _meadowDevice.GetMonoRunStateAsync(cancellationToken).ConfigureAwait(false) == false, "Meadow was expected to have Mono Disabled"); await _meadowDevice.UpdateMonoRuntimeAsync( runtimePath, cancellationToken: cancellationToken); await Task.Delay(2000); await ReInitializeMeadowAsync(cancellationToken) .ConfigureAwait(false); await Task.Delay(2000); } else { Logger.LogInformation("Skipping update of runtime."); } if (skipEsp == false) { await MonoDisableAsync(cancellationToken: cancellationToken).ConfigureAwait(false); Trace.Assert(await GetMonoRunStateAsync(cancellationToken).ConfigureAwait(false) == false, "Meadow was expected to have Mono Disabled"); Logger.LogInformation("Updating ESP"); await _meadowDevice.FlashEspAsync(cancellationToken) .ConfigureAwait(false); // Reset the meadow again to ensure flash worked. await _meadowDevice.ResetMeadowAsync(cancellationToken) .ConfigureAwait(false); await Task.Delay(3000); await ReInitializeMeadowAsync(cancellationToken) .ConfigureAwait(false); } else { Logger.LogInformation("Skipping ESP flash"); } //Logger.LogInformation("Enabling Mono and Resetting"); //await MonoEnableAsync(cancellationToken); // This is to ensure the ESP info has updated in HCOM on the Meadow await Task.Delay(3000, cancellationToken) .ConfigureAwait(false); // TODO: Verify that the device info returns the expected version var deviceInfo = await _meadowDevice .GetDeviceInfoAsync(TimeSpan.FromSeconds(60), cancellationToken) .ConfigureAwait(false); Logger.LogInformation( $"Updated Meadow to OS: {deviceInfo.MeadowOsVersion} ESP: {deviceInfo.CoProcessorOsVersion}"); } catch (Exception ex) { Logger.LogError(ex, "Error flashing OS to Meadow"); } } public static async Task<string> DfuFlashAsync(string serialPortName, string osPath, ILogger logger, CancellationToken cancellationToken = default) { var dfuAttempts = 0; UsbRegistry dfuDevice; while (true) { try { try { dfuDevice = DfuUtils.GetDevice(); break; } catch (MultipleDfuDevicesException) { // This is bad, we can't just blindly flash with multiple devices, let the user know throw; } catch (DeviceNotFoundException) { // eat it. } // No DFU device found, lets try to set the meadow to DFU mode. using var device = await MeadowDeviceManager.GetMeadowForSerialPort(serialPortName, false).ConfigureAwait(false); if (device != null) { logger.LogInformation("Entering DFU Mode"); await device.EnterDfuModeAsync(cancellationToken) .ConfigureAwait(false); } } catch (Exception ex) { logger.LogDebug( "An exception occurred while switching device to DFU Mode. Exception: {0}", ex); } switch (dfuAttempts) { case 5: logger.LogInformation( "Having trouble putting Meadow in DFU Mode, please press RST button on Meadow and press enter to try again"); Console.ReadKey(); break; case 10: logger.LogInformation( "Having trouble putting Meadow in DFU Mode, please hold BOOT button, press RST button and release BOOT button on Meadow and press enter to try again"); Console.ReadKey(); break; case > 15: throw new Exception( "Unable to place device in DFU mode, please disconnect the Meadow, hold the BOOT button, reconnect the Meadow, release the BOOT button and try again."); } // Lets give the device a little time to settle in and get picked up await Task.Delay(1000, cancellationToken) .ConfigureAwait(false); dfuAttempts++; } // Get the serial number so that later we can pick the right device if the system has multiple meadow plugged in string serialNumber = DfuUtils.GetDeviceSerial(dfuDevice); logger.LogInformation("Device in DFU Mode, flashing OS"); var res = await DfuUtils.DfuFlashAsync(osPath, dfuDevice, logger).ConfigureAwait(false); if (res) { logger.LogInformation("Device Flashed."); return serialNumber; } else { throw new MeadowDeviceException("Failed to flash meadow"); } } private void Dispose(bool disposing) { lock (Logger) { if (disposing) { _meadowDevice?.Dispose(); } } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } ~MeadowDeviceHelper() { Dispose(false); } } }
40.634058
180
0.594918
[ "Apache-2.0" ]
0xStuart/Meadow.CLI
Meadow.CLI.Core/Devices/MeadowDeviceHelper.cs
22,432
C#
namespace Mailjet.Client.TransactionalEmails { /// <summary> /// Enable or disable open tracking on this message. /// This property will overwrite the preferences selected in the Mailjet account. /// Equivalent of using X-Mailjet-TrackOpen header through SMTP. /// </summary> public enum TrackOpens { /// <summary> /// Use the values specified in the Mailjet account /// </summary> account_default, /// <summary> /// disable tracking for this message /// </summary> disabled, /// <summary> /// enable tracking for this message /// </summary> enabled } }
27.36
85
0.586257
[ "MIT" ]
Samy-Farnaud/mailjet-apiv3-dotnet
Mailjet.Client/TransactionalEmails/Models/TrackOpens.cs
686
C#
using log4net; namespace Mvc.Common.Service { public class AppService : IAppService { public AppService(IConfig config, ILog log) { Configuration = config; Log = log; } public IConfig Configuration { get; } public ILog Log { get; } } }
17.555556
51
0.553797
[ "MIT" ]
rob-walk/mvc-template
Mvc.Common/Service/AppService.cs
318
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated from a template. // // Manual changes to this file may cause unexpected behavior in your application. // Manual changes to this file will be overwritten if the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Bookstore.Data { using System; using System.Data.Entity; using System.Data.Entity.Infrastructure; public partial class BookstoreDBEntities : DbContext { public BookstoreDBEntities() : base("name=BookstoreDBEntities") { } protected override void OnModelCreating(DbModelBuilder modelBuilder) { throw new UnintentionalCodeFirstException(); } public virtual DbSet<Author> Authors { get; set; } public virtual DbSet<Book> Books { get; set; } public virtual DbSet<Review> Reviews { get; set; } } }
32.181818
85
0.548023
[ "MIT" ]
Ico093/TelerikAcademy
DataBases/Exams/DataBases-July-2013/DatabaseExam/Bookstore.Data/BookstoreDB.Context.cs
1,064
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; namespace Cats.UWP { public sealed partial class MainPage { public MainPage() { this.InitializeComponent(); LoadApplication(new Cats.App()); } } }
22.464286
52
0.72496
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
cleitonferreira/MaratonaXamarin
Cats/Cats/Cats.UWP/MainPage.xaml.cs
631
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. //----------------------------------------------------------------------------- // // Description: // ContentType class parses and validates the content-type string. // It provides functionality to compare the type/subtype values. // // Details: // Grammar which this class follows - // // Content-type grammar MUST conform to media-type grammar as per // RFC 2616 (ABNF notation): // // media-type = type "/" subtype *( ";" parameter ) // type = token // subtype = token // parameter = attribute "=" value // attribute = token // value = token | quoted-string // quoted-string = ( <"> *(qdtext | quoted-pair ) <"> ) // qdtext = <any TEXT except <">> // quoted-pair = "\" CHAR // token = 1*<any CHAR except CTLs or separators> // separators = "(" | ")" | "<" | ">" | "@" // | "," | ";" | ":" | "\" | <"> // | "/" | "[" | "]" | "?" | "=" // | "{" | "}" | SP | HT // TEXT = <any OCTET except CTLs, but including LWS> // OCTET = <any 8-bit sequence of data> // CHAR = <any US-ASCII character (octets 0 - 127)> // CTL = <any US-ASCII control character(octets 0 - 31)and DEL(127)> // CR = <US-ASCII CR, carriage return (13)> // LF = <US-ASCII LF, linefeed (10)> // SP = <US-ASCII SP, space (32)> // HT = <US-ASCII HT, horizontal-tab (9)> // <"> = <US-ASCII double-quote mark (34)> // LWS = [CRLF] 1*( SP | HT ) // CRLF = CR LF // Linear white space (LWS) MUST NOT be used between the type and subtype, nor // between an attribute and its value. Leading and trailing LWS are prohibited. // //----------------------------------------------------------------------------- using System; using System.Collections.Generic; // For Dictionary<string, string> using System.Text; // For StringBuilder using System.Diagnostics; // For Debug.Assert namespace System.IO.Packaging { /// <summary> /// Content Type class /// </summary> internal sealed class ContentType { //------------------------------------------------------ // // Internal Constructors // //------------------------------------------------------ #region Internal Constructors /// <summary> /// This constructor creates a ContentType object that represents /// the content-type string. At construction time we validate the /// string as per the grammar specified in RFC 2616. /// Note: We allow empty strings as valid input. Empty string should /// we used more as an indication of an absent/unknown ContentType. /// </summary> /// <param name="contentType">content-type</param> /// <exception cref="ArgumentNullException">If the contentType parameter is null</exception> /// <exception cref="ArgumentException">If the contentType string has leading or /// trailing Linear White Spaces(LWS) characters</exception> /// <exception cref="ArgumentException">If the contentType string invalid CR-LF characters</exception> internal ContentType(string contentType) { if (contentType == null) throw new ArgumentNullException("contentType"); if (contentType.Length == 0) { _contentType = String.Empty; } else { if (IsLinearWhiteSpaceChar(contentType[0]) || IsLinearWhiteSpaceChar(contentType[contentType.Length - 1])) throw new ArgumentException(SR.ContentTypeCannotHaveLeadingTrailingLWS); //Carriage return can be expressed as '\r\n' or '\n\r' //We need to make sure that a \r is accompanied by \n ValidateCarriageReturns(contentType); //Begin Parsing int semiColonIndex = contentType.IndexOf(SemicolonSeparator); if (semiColonIndex == -1) { // Parse content type similar to - type/subtype ParseTypeAndSubType(contentType); } else { // Parse content type similar to - type/subtype ; param1=value1 ; param2=value2 ; param3="value3" ParseTypeAndSubType(contentType.Substring(0, semiColonIndex)); ParseParameterAndValue(contentType.Substring(semiColonIndex)); } } // keep this untouched for return from OriginalString property _originalString = contentType; //This variable is used to print out the correct content type string representation //using the ToString method. This is mainly important while debugging and seeing the //value of the content type object in the debugger. _isInitialized = true; } #endregion Internal Constructors //------------------------------------------------------ // // Internal Methods // //------------------------------------------------------ #region Internal Properties /// <summary> /// TypeComponent of the Content Type /// If the content type is "text/xml". This property will return "text" /// </summary> internal string TypeComponent { get { return _type; } } /// <summary> /// SubType component /// If the content type is "text/xml". This property will return "xml" /// </summary> internal string SubTypeComponent { get { return _subType; } } /// <summary> /// Enumerator which iterates over the Parameter and Value pairs which are stored /// in a dictionary. We hand out just the enumerator in order to make this property /// ReadOnly /// Consider following Content type - /// type/subtype ; param1=value1 ; param2=value2 ; param3="value3" /// This will return a enumerator over a dictionary of the parameter/value pairs. /// </summary> internal Dictionary<string, string>.Enumerator ParameterValuePairs { get { EnsureParameterDictionary(); return _parameterDictionary.GetEnumerator(); } } #endregion Internal Properties //------------------------------------------------------ // // Internal Methods // //------------------------------------------------------ #region Internal Methods /// <summary> /// This method does a strong comparison of the content types, as parameters are not allowed. /// We only compare the type and subType values in an ASCII case-insensitive manner. /// Parameters are not allowed to be present on any of the content type operands. /// </summary> /// <param name="contentType">Content type to be compared with</param> /// <returns></returns> internal bool AreTypeAndSubTypeEqual(ContentType contentType) { return AreTypeAndSubTypeEqual(contentType, false); } /// <summary> /// This method does a weak comparison of the content types. We only compare the /// type and subType values in an ASCII case-insensitive manner. /// Parameter and value pairs are not used for the comparison. /// If you wish to compare the paramters too, then you must get the ParameterValuePairs from /// both the ContentType objects and compare each parameter entry. /// The allowParameterValuePairs parameter is used to indicate whether the /// comparison is tolerant to parameters being present or no. /// </summary> /// <param name="contentType">Content type to be compared with</param> /// <param name="allowParameterValuePairs">If true, allows the presence of parameter value pairs. /// If false, parameter/value pairs cannot be present in the content type string. /// In either case, the parameter value pair is not used for the comparison.</param> /// <returns></returns> internal bool AreTypeAndSubTypeEqual(ContentType contentType, bool allowParameterValuePairs) { bool result = false; if (contentType != null) { if (!allowParameterValuePairs) { //Return false if this content type object has parameters if (_parameterDictionary != null) { if (_parameterDictionary.Count > 0) return false; } //Return false if the content type object passed in has parameters Dictionary<string, string>.Enumerator contentTypeEnumerator; contentTypeEnumerator = contentType.ParameterValuePairs; contentTypeEnumerator.MoveNext(); if (contentTypeEnumerator.Current.Key != null) return false; } // Perform a case-insensitive comparison on the type/subtype strings. This is a // safe comparison because the _type and _subType strings have been restricted to // ASCII characters, digits, and a small set of symbols. This is not a safe comparison // for the broader set of strings that have not been restricted in the same way. result = (String.Equals(_type, contentType.TypeComponent, StringComparison.OrdinalIgnoreCase) && String.Equals(_subType, contentType.SubTypeComponent, StringComparison.OrdinalIgnoreCase)); } return result; } /// <summary> /// ToString - outputs a normalized form of the content type string /// </summary> /// <returns></returns> public override string ToString() { if (_contentType == null) { //This is needed so that while debugging we get the correct //string if (!_isInitialized) return String.Empty; Debug.Assert(String.CompareOrdinal(_type, String.Empty) != 0 || String.CompareOrdinal(_subType, String.Empty) != 0); StringBuilder stringBuilder = new StringBuilder(_type); stringBuilder.Append(PackUriHelper.ForwardSlashChar); stringBuilder.Append(_subType); if (_parameterDictionary != null && _parameterDictionary.Count > 0) { foreach (string parameterKey in _parameterDictionary.Keys) { stringBuilder.Append(s_linearWhiteSpaceChars[0]); stringBuilder.Append(SemicolonSeparator); stringBuilder.Append(s_linearWhiteSpaceChars[0]); stringBuilder.Append(parameterKey); stringBuilder.Append(EqualSeparator); stringBuilder.Append(_parameterDictionary[parameterKey]); } } _contentType = stringBuilder.ToString(); } return _contentType; } #endregion Internal Methods //------------------------------------------------------ // // Private Methods // //------------------------------------------------------ #region Private Methods /// <summary> /// This method validates if the content type string has /// valid CR-LF characters. Specifically we test if '\r' is /// accompanied by a '\n' in the string, else its an error. /// </summary> /// <param name="contentType"></param> private static void ValidateCarriageReturns(string contentType) { Debug.Assert(!IsLinearWhiteSpaceChar(contentType[0]) && !IsLinearWhiteSpaceChar(contentType[contentType.Length - 1])); //Prior to calling this method we have already checked that first and last //character of the content type are not Linear White Spaces. So its safe to //assume that the index will be greater than 0 and less that length-2. int index = contentType.IndexOf(s_linearWhiteSpaceChars[2]); while (index != -1) { if (contentType[index - 1] == s_linearWhiteSpaceChars[1] || contentType[index + 1] == s_linearWhiteSpaceChars[1]) { index = contentType.IndexOf(s_linearWhiteSpaceChars[2], ++index); } else throw new ArgumentException(SR.InvalidLinearWhiteSpaceCharacter); } } /// <summary> /// Parses the type and subType tokens from the string. /// Also verifies if the Tokens are valid as per the grammar. /// </summary> /// <param name="typeAndSubType">substring that has the type and subType of the content type</param> /// <exception cref="ArgumentException">If the typeAndSubType parameter does not have the "/" character</exception> private void ParseTypeAndSubType(string typeAndSubType) { //okay to trim at this point the end of the string as Linear White Spaces(LWS) chars are allowed here. typeAndSubType = typeAndSubType.TrimEnd(s_linearWhiteSpaceChars); string[] splitBasedOnForwardSlash = typeAndSubType.Split(PackUriHelper.s_forwardSlashCharArray); if (splitBasedOnForwardSlash.Length != 2) throw new ArgumentException(SR.InvalidTypeSubType); _type = ValidateToken(splitBasedOnForwardSlash[0]); _subType = ValidateToken(splitBasedOnForwardSlash[1]); } /// <summary> /// Parse the individual parameter=value strings /// </summary> /// <param name="parameterAndValue">This string has the parameter and value pair of the form /// parameter=value</param> /// <exception cref="ArgumentException">If the string does not have the required "="</exception> private void ParseParameterAndValue(string parameterAndValue) { while (parameterAndValue != string.Empty) { //At this point the first character MUST be a semi-colon //First time through this test is serving more as an assert. if (parameterAndValue[0] != SemicolonSeparator) throw new ArgumentException(SR.ExpectingSemicolon); //At this point if we have just one semicolon, then its an error. //Also, there can be no trailing LWS characters, as we already checked for that //in the constructor. if (parameterAndValue.Length == 1) throw new ArgumentException(SR.ExpectingParameterValuePairs); //Removing the leading ; from the string parameterAndValue = parameterAndValue.Substring(1); //okay to trim start as there can be spaces before the begining //of the parameter name. parameterAndValue = parameterAndValue.TrimStart(s_linearWhiteSpaceChars); int equalSignIndex = parameterAndValue.IndexOf(EqualSeparator); if (equalSignIndex <= 0 || equalSignIndex == (parameterAndValue.Length - 1)) throw new ArgumentException(SR.InvalidParameterValuePair); int parameterStartIndex = equalSignIndex + 1; //Get length of the parameter value int parameterValueLength = GetLengthOfParameterValue(parameterAndValue, parameterStartIndex); EnsureParameterDictionary(); _parameterDictionary.Add( ValidateToken(parameterAndValue.Substring(0, equalSignIndex)), ValidateQuotedStringOrToken(parameterAndValue.Substring(parameterStartIndex, parameterValueLength))); parameterAndValue = parameterAndValue.Substring(parameterStartIndex + parameterValueLength).TrimStart(s_linearWhiteSpaceChars); } } /// <summary> /// This method returns the length of the first parameter value in the input string. /// </summary> /// <param name="s"></param> /// <param name="startIndex">Starting index for parsing</param> /// <returns></returns> private static int GetLengthOfParameterValue(string s, int startIndex) { Debug.Assert(s != null); int length = 0; //if the parameter value does not start with a '"' then, //we expect a valid token. So we look for Linear White Spaces or //a ';' as the terminator for the token value. if (s[startIndex] != '"') { int semicolonIndex = s.IndexOf(SemicolonSeparator, startIndex); if (semicolonIndex != -1) { int lwsIndex = s.IndexOfAny(s_linearWhiteSpaceChars, startIndex); if (lwsIndex != -1 && lwsIndex < semicolonIndex) length = lwsIndex; else length = semicolonIndex; } else length = semicolonIndex; //If there is no linear white space found we treat the entire remaining string as //parameter value. if (length == -1) length = s.Length; } else { //if the parameter value starts with a '"' then, we need to look for the //pairing '"' that is not preceded by a "\" ["\" is used to escape the '"'] bool found = false; length = startIndex; while (!found) { length = s.IndexOf('"', ++length); if (length == -1) throw new ArgumentException(SR.InvalidParameterValue); if (s[length - 1] != '\\') { found = true; length++; } } } return length - startIndex; } /// <summary> /// Validating the given token /// The following checks are being made - /// 1. If all the characters in the token are either ASCII letter or digit. /// 2. If all the characters in the token are either from the remaining allowed cha----ter set. /// </summary> /// <param name="token">string token</param> /// <returns>validated string token</returns> /// <exception cref="ArgumentException">If the token is Empty</exception> private static string ValidateToken(string token) { if (String.IsNullOrEmpty(token)) throw new ArgumentException(SR.InvalidToken); for (int i = 0; i < token.Length; i++) { if (!IsAsciiLetterOrDigit(token[i]) && !IsAllowedCharacter(token[i])) { throw new ArgumentException(SR.InvalidToken); } } return token; } /// <summary> /// Validating if the value of a parameter is either a valid token or a /// valid quoted string /// </summary> /// <param name="parameterValue">paramter value string</param> /// <returns>validate parameter value string</returns> /// <exception cref="ArgumentException">If the paramter value is empty</exception> private static string ValidateQuotedStringOrToken(string parameterValue) { if (String.IsNullOrEmpty(parameterValue)) throw new ArgumentException(SR.InvalidParameterValue); if (parameterValue.Length >= 2 && parameterValue.StartsWith(Quote, StringComparison.Ordinal) && parameterValue.EndsWith(Quote, StringComparison.Ordinal)) ValidateQuotedText(parameterValue.Substring(1, parameterValue.Length - 2)); else ValidateToken(parameterValue); return parameterValue; } /// <summary> /// This method validates if the text in the quoted string /// </summary> /// <param name="quotedText"></param> private static void ValidateQuotedText(string quotedText) { //empty is okay for (int i = 0; i < quotedText.Length; i++) { if (IsLinearWhiteSpaceChar(quotedText[i])) continue; if (quotedText[i] <= ' ' || quotedText[i] >= 0xFF) throw new ArgumentException(SR.InvalidParameterValue); else if (quotedText[i] == '"' && (i == 0 || quotedText[i - 1] != '\\')) throw new ArgumentException(SR.InvalidParameterValue); } } /// <summary> /// Returns true if the input character is an allowed character /// Returns false if the input cha----ter is not an allowed character /// </summary> /// <param name="character">input character</param> /// <returns></returns> private static bool IsAllowedCharacter(char character) { return Array.IndexOf(s_allowedCharacters, character) >= 0; } /// <summary> /// Returns true if the input character is an ASCII digit or letter /// Returns false if the input character is not an ASCII digit or letter /// </summary> /// <param name="character">input character</param> /// <returns></returns> private static bool IsAsciiLetterOrDigit(char character) { return (IsAsciiLetter(character) || (character >= '0' && character <= '9')); } /// <summary> /// Returns true if the input character is an ASCII letter /// Returns false if the input character is not an ASCII letter /// </summary> /// <param name="character">input character</param> /// <returns></returns> private static bool IsAsciiLetter(char character) { return (character >= 'a' && character <= 'z') || (character >= 'A' && character <= 'Z'); } /// <summary> /// Returns true if the input character is one of the Linear White Space characters - /// ' ', '\t', '\n', '\r' /// Returns false if the input character is none of the above /// </summary> /// <param name="ch">input character</param> /// <returns></returns> private static bool IsLinearWhiteSpaceChar(char ch) { if (ch > ' ') { return false; } int whiteSpaceIndex = Array.IndexOf(s_linearWhiteSpaceChars, ch); return whiteSpaceIndex != -1; } /// <summary> /// Lazy initialization for the ParameterDictionary /// </summary> private void EnsureParameterDictionary() { if (_parameterDictionary == null) { _parameterDictionary = new Dictionary<string, string>(); //initial size 0 } } #endregion Private Methods //------------------------------------------------------ // // Private Members // //------------------------------------------------------ #region Private Members private string _contentType = null; private string _type = String.Empty; private string _subType = String.Empty; private string _originalString; private Dictionary<string, string> _parameterDictionary = null; private bool _isInitialized = false; private const string Quote = "\""; private const char SemicolonSeparator = ';'; private const char EqualSeparator = '='; //This array is sorted by the ascii value of these characters. private static readonly char[] s_allowedCharacters = { '!' /*33*/, '#' /*35*/ , '$' /*36*/, '%' /*37*/, '&' /*38*/ , '\'' /*39*/, '*' /*42*/, '+' /*43*/ , '-' /*45*/, '.' /*46*/, '^' /*94*/ , '_' /*95*/, '`' /*96*/, '|' /*124*/, '~' /*126*/, }; //Linear White Space characters private static readonly char[] s_linearWhiteSpaceChars = { ' ', // space - \x20 '\n', // new line - \x0A '\r', // carriage return - \x0D '\t' // horizontal tab - \x09 }; #endregion Private Members } }
41.400324
143
0.541145
[ "MIT" ]
690486439/corefx
src/System.IO.Packaging/src/System/IO/Packaging/ContentType.cs
25,544
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols.Metadata.PE { public class NoPiaLocalHideAndTypeSubstitutionTests : CSharpTestBase { [Fact] public void NoPiaTypeEquivalenceBetweenPIATypeInExternalAndLocalAssembly() { // Verify type equivalence between PIA type in external assembly and local assembly var localConsumer = CreateCompilation(assemblyName: "Dummy", source: (string[])null, references: new MetadataReference[] { TestReferences.SymbolsTests.NoPia.Pia1, TestReferences.SymbolsTests.NoPia.LocalTypes1 }); var localConsumerRefsAsm = localConsumer.Assembly.GetNoPiaResolutionAssemblies(); Assert.Equal(1, localConsumerRefsAsm.First(arg => arg.Name == "LocalTypes1").Modules.FirstOrDefault().GetReferencedAssemblies().Length); Assert.Equal(1, localConsumerRefsAsm.First(arg => arg.Name == "LocalTypes1").Modules.FirstOrDefault().GetReferencedAssemblySymbols().Length); Assert.Equal(localConsumerRefsAsm.First(arg => arg.Name == "mscorlib"), localConsumerRefsAsm.First(arg => arg.Name == "LocalTypes1").Modules.FirstOrDefault().GetReferencedAssemblySymbols().ElementAt(0)); var canonicalType1 = localConsumerRefsAsm.First(arg => arg.Name == "Pia1").GlobalNamespace.GetTypeMembers("I1").Single(); var canonicalType2 = localConsumerRefsAsm.First(arg => arg.Name == "Pia1").GlobalNamespace.GetMembers("NS1").OfType<NamespaceSymbol>().Single().GetTypeMembers("I2").Single(); NamedTypeSymbol classLocalType = localConsumerRefsAsm.First(arg => arg.Name == "LocalTypes1").GlobalNamespace.GetTypeMembers("LocalTypes1").Single(); MethodSymbol methodSymbol = classLocalType.GetMembers("Test1").OfType<MethodSymbol>().Single(); ImmutableArray<ParameterSymbol> param = methodSymbol.Parameters; Assert.Same(canonicalType1, param.Where(arg => arg.Type.Name == "I1").Select(arg => arg).Single().Type); Assert.Same(canonicalType2, param.Where(arg => arg.Type.Name == "I2").Select(arg => arg).Single().Type); } [Fact] public void NoPiaTypeSubstitutionReferToAnotherAssemblyLocalDefOfPIAInterface() { //Refer to another local assembly's local def of a PIA interface var localTypeSource1 = @"public class External1 { public const IDuplicates IDup =null; public static delegate IDuplicates MyFunc(); public event GeneralEventScenario.EventHandler Event1; public FooStruct Structure1; public FooEnum Property1; }"; var localTypeSource2 = @"public static class LocalType1 { public void Test1(External1.MyFunc arg) { } }"; var localType1 = CreateEmptyCompilation(assemblyName: "Dummy1", source: new string[] { localTypeSource1 }, references: new MetadataReference[] { TestReferences.SymbolsTests.NoPia.GeneralPia.WithEmbedInteropTypes(true) }); var localType2 = CreateEmptyCompilation(assemblyName: "Dummy2", source: new string[] { localTypeSource2 }, references: new MetadataReference[] { TestReferences.SymbolsTests.NoPia.GeneralPia, new CSharpCompilationReference(localType1) }); var localConsumer = CreateEmptyCompilation(assemblyName: "Dummy3", source: CSharpTestSource.None, references: new MetadataReference[] { TestReferences.SymbolsTests.NoPia.GeneralPiaCopy, new CSharpCompilationReference(localType2), new CSharpCompilationReference(localType1) }); var localConsumerRefsAsm = localConsumer.Assembly.GetNoPiaResolutionAssemblies(); Assert.Equal(2, localConsumerRefsAsm.First(arg => arg.Name == "Dummy2").Modules.FirstOrDefault().GetReferencedAssemblies().Length); Assert.Equal(2, localConsumerRefsAsm.First(arg => arg.Name == "Dummy2").Modules.FirstOrDefault().GetReferencedAssemblySymbols().Length); NamedTypeSymbol classLocalType = localConsumer.GlobalNamespace.GetTypeMembers("LocalType1").Single(); MethodSymbol methodSymbol = classLocalType.GetMembers("Test1").OfType<MethodSymbol>().Single(); Assert.Equal(SymbolKind.NamedType, methodSymbol.Parameters.Single(arg => arg.Name == "arg").Type.Kind); } [Fact] public void NoPIALocalTypesEquivalentToEachOtherStructAsMethodParameterType() { //Structure - As method parameter type in external assembly (test this by passing the parameter with a variable which was declared in the current assembly) var localTypeSource = @"static class TypeSubstitution { FooStruct myOwnVar = null; public static void Main() { myOwnVar = new FooStruct(); myOwnVar.Structure = -1; ExternalAsm1.Scen1(myOwnVar); } } "; var localConsumer = CreateEmptyCompilation(assemblyName: "Dummy", source: new string[] { localTypeSource }, references: new MetadataReference[] { TestReferences.SymbolsTests.NoPia.GeneralPia, TestReferences.SymbolsTests.NoPia.ExternalAsm1, }); var localConsumerRefsAsm = localConsumer.Assembly.GetNoPiaResolutionAssemblies(); Assert.Equal(3, localConsumerRefsAsm.First(arg => arg.Name == "GeneralPia").Modules.FirstOrDefault().GetReferencedAssemblies().Length); Assert.Equal(3, localConsumerRefsAsm.First(arg => arg.Name == "GeneralPia").Modules.FirstOrDefault().GetReferencedAssemblySymbols().Length); var canonicalType = localConsumerRefsAsm.First(arg => arg.Name == "GeneralPia").GlobalNamespace.GetTypeMembers("FooStruct").Single(); NamedTypeSymbol classLocalType = localConsumer.GlobalNamespace.GetTypeMembers("TypeSubstitution").Single(); FieldSymbol localFieldSymbol = classLocalType.GetMembers("myOwnVar").OfType<FieldSymbol>().Single(); NamedTypeSymbol classRefLocalType = localConsumerRefsAsm.First(arg => arg.Name == "ExternalAsm1").GlobalNamespace.GetTypeMembers("ExternalAsm1").Single(); MethodSymbol refMethodSymbol = classRefLocalType.GetMembers("Scen1").OfType<MethodSymbol>().Single(); ImmutableArray<ParameterSymbol> param = refMethodSymbol.Parameters; NoPiaMissingCanonicalTypeSymbol missing = (NoPiaMissingCanonicalTypeSymbol)param.First().Type; Assert.Same(localConsumerRefsAsm.First(arg => arg.Name == "ExternalAsm1"), missing.EmbeddingAssembly); Assert.Null(missing.Guid); Assert.Equal(canonicalType.ToTestDisplayString(), missing.FullTypeName); Assert.Equal("f9c2d51d-4f44-45f0-9eda-c9d599b58257", missing.Scope); Assert.Equal(canonicalType.ToTestDisplayString(), missing.Identifier); Assert.Same(canonicalType, localFieldSymbol.Type); Assert.IsType<NoPiaMissingCanonicalTypeSymbol>(param[0].Type); } [Fact] public void NoPIALocalTypesEquivalentToEachOtherInterfaceAsMethodParameterType() { //Same as previous scenario but with Interface var localTypeSource = @"class ICBase : InheritanceConflict.IBase { public int Bar() { return -2; } public void ConflictMethod(int x) { } public void Foo() { } public string this[object x] { get { return null; } set { } } } static class TypeSubstitution { InheritanceConflict.IBase myOwnRef =null; public static void Main() { myOwnRef = new ICBase(); ExternalAsm1.Scen2(myOwnRef); } }"; var localConsumer = CreateEmptyCompilation(assemblyName: "Dummy", source: new string[] { localTypeSource }, references: new List<MetadataReference>() { TestReferences.SymbolsTests.NoPia.GeneralPia, TestReferences.SymbolsTests.NoPia.ExternalAsm1 }); var localConsumerRefsAsm = localConsumer.Assembly.GetNoPiaResolutionAssemblies(); var canonicalType = localConsumerRefsAsm.First(arg => arg.Name == "GeneralPia").GlobalNamespace.ChildNamespace("InheritanceConflict"); var canonicalTypeInter = canonicalType.GetTypeMembers("IBase").Single(); NamedTypeSymbol classLocalType = localConsumer.GlobalNamespace.GetTypeMembers("TypeSubstitution").Single(); FieldSymbol localFieldSymbol = classLocalType.GetMembers("myOwnRef").OfType<FieldSymbol>().Single(); NamedTypeSymbol classRefLocalType = localConsumerRefsAsm.First(arg => arg.Name == "ExternalAsm1").GlobalNamespace.GetTypeMembers("ExternalAsm1").Single(); MethodSymbol refMethodSymbol = classRefLocalType.GetMembers("Scen2").OfType<MethodSymbol>().Single(); ImmutableArray<ParameterSymbol> param = refMethodSymbol.Parameters; Assert.Same(canonicalTypeInter, localFieldSymbol.Type); Assert.Same(canonicalTypeInter, param.First().Type); Assert.IsAssignableFrom<PENamedTypeSymbol>(param.First().Type); } [Fact] public void NoPIALocalTypesEquivalentToEachOtherEnumAsReturnTypeInExternalAssembly() { //Enum - As return type in external assembly var localTypeSource = @"static class TypeSubstitution { FooEnum myLocalType = 0; public static void Main() { FooEnum myLocalType = 0; myLocalType = ExternalAsm1.Scen3(5); } }"; var localConsumer = CreateEmptyCompilation(assemblyName: "Dummy", source: new string[] { localTypeSource }, references: new List<MetadataReference>() { TestReferences.SymbolsTests.NoPia.GeneralPia, TestReferences.SymbolsTests.NoPia.ExternalAsm1 }); var localConsumerRefsAsm = localConsumer.Assembly.GetNoPiaResolutionAssemblies(); var canonicalType = localConsumerRefsAsm.First(arg => arg.Name == "GeneralPia").GlobalNamespace.GetTypeMembers("FooEnum").Single(); NamedTypeSymbol classLocalType = localConsumer.GlobalNamespace.GetTypeMembers("TypeSubstitution").Single(); FieldSymbol localFieldSymbol = classLocalType.GetMembers("myLocalType").OfType<FieldSymbol>().Single(); NamedTypeSymbol classRefLocalType = localConsumerRefsAsm.First(arg => arg.Name == "ExternalAsm1").GlobalNamespace.GetTypeMembers("ExternalAsm1").Single(); MethodSymbol methodSymbol = classRefLocalType.GetMembers("Scen3").OfType<MethodSymbol>().Single(); NoPiaMissingCanonicalTypeSymbol missing = (NoPiaMissingCanonicalTypeSymbol)methodSymbol.ReturnType; Assert.Same(localConsumerRefsAsm.First(arg => arg.Name == "ExternalAsm1"), missing.EmbeddingAssembly); Assert.Null(missing.Guid); Assert.Equal(canonicalType.ToTestDisplayString(), missing.FullTypeName); Assert.Equal("f9c2d51d-4f44-45f0-9eda-c9d599b58257", missing.Scope); Assert.Equal(canonicalType.ToTestDisplayString(), missing.Identifier); Assert.Same(canonicalType, localFieldSymbol.Type); Assert.IsType<NoPiaMissingCanonicalTypeSymbol>(methodSymbol.ReturnType); } [Fact] public void NoPIALocalTypesEquivalentToEachOtherInterfaceAsReturnTypeInExternalAssembly() { // Interface - As property in external assembly var localTypeSource = @"static class TypeSubstitution { ISubFuncProp myLocalType = ExternalAsm1.Scen4; }"; var localConsumer = CreateEmptyCompilation(assemblyName: "Dummy", source: new string[] { localTypeSource }, references: new List<MetadataReference>() { TestReferences.SymbolsTests.NoPia.GeneralPia, TestReferences.SymbolsTests.NoPia.ExternalAsm1 }); var localConsumerRefsAsm = localConsumer.Assembly.GetNoPiaResolutionAssemblies(); var canonicalType = localConsumerRefsAsm.First(arg => arg.Name == "GeneralPia").GlobalNamespace.GetTypeMembers("ISubFuncProp").Single(); NamedTypeSymbol classLocalType = localConsumer.GlobalNamespace.GetTypeMembers("TypeSubstitution").Single(); FieldSymbol localFieldSymbol = classLocalType.GetMembers("myLocalType").OfType<FieldSymbol>().Single(); NamedTypeSymbol classRefLocalType = localConsumerRefsAsm.First(arg => arg.Name == "ExternalAsm1").GlobalNamespace.GetTypeMembers("ExternalAsm1").Single(); var methodSymbol = classRefLocalType.GetMembers("Scen4").OfType<PropertySymbol>().Single(); var missing = methodSymbol.TypeWithAnnotations; Assert.Equal(canonicalType.ToTestDisplayString(), missing.Type.Name); Assert.Same(canonicalType, localFieldSymbol.Type); Assert.IsAssignableFrom<PENamedTypeSymbol>(methodSymbol.Type); } [Fact] public void NoPIALocalTypesEquivalentToEachOtherDelegateAsReturnTypeInExternalAssembly() { //Same as previous scenario but with Delegate var localTypeSource = @"static class TypeSubstitution { GeneralEventScenario.EventHandler myLocalType = ExternalAsm1.Scen5; }"; var localConsumer = CreateEmptyCompilation(assemblyName: "Dummy", source: new string[] { localTypeSource }, references: new List<MetadataReference>() { TestReferences.SymbolsTests.NoPia.GeneralPia, TestReferences.SymbolsTests.NoPia.ExternalAsm1 }); var localConsumerRefsAsm = localConsumer.Assembly.GetNoPiaResolutionAssemblies(); var canonicalType = localConsumerRefsAsm[0].GlobalNamespace.ChildNamespace("GeneralEventScenario"); var canonicalTypeInter = canonicalType.GetTypeMembers("EventHandler").Single(); NamedTypeSymbol classLocalType = localConsumer.GlobalNamespace.GetTypeMembers("TypeSubstitution").Single(); FieldSymbol localFieldSymbol = classLocalType.GetMembers("myLocalType").OfType<FieldSymbol>().Single(); NamedTypeSymbol classRefLocalType = localConsumerRefsAsm.First(arg => arg.Name == "ExternalAsm1").GlobalNamespace.GetTypeMembers("ExternalAsm1").Single(); var methodSymbol = classRefLocalType.GetMembers("Scen5").OfType<PropertySymbol>().Single(); var missing = (NamedTypeSymbol)methodSymbol.Type; Assert.Equal(SymbolKind.ErrorType, missing.Kind); Assert.Same(canonicalTypeInter, localFieldSymbol.Type); Assert.IsType<NoPiaMissingCanonicalTypeSymbol>(missing); } [Fact] public void NoPIATypeSubstitutionForClassThatImplementNoPiaInterface() { //Check type substitution when a class implement a PIA interface var localConsumer = CreateEmptyCompilation(assemblyName: "Dummy", source: CSharpTestSource.None, references: new List<MetadataReference>() { TestReferences.SymbolsTests.NoPia.GeneralPia, TestReferences.SymbolsTests.NoPia.ExternalAsm1 }); var localConsumerRefsAsm = localConsumer.Assembly.GetNoPiaResolutionAssemblies(); var canonicalType = localConsumerRefsAsm.First(arg => arg.Name == "GeneralPia").GlobalNamespace.GetTypeMembers("ISubFuncProp").Single(); NamedTypeSymbol classRefLocalType = localConsumerRefsAsm.First(arg => arg.Name == "ExternalAsm1").GlobalNamespace.GetTypeMembers("SubFuncProp").Single(); MethodSymbol methodSymbol = classRefLocalType.GetMembers("Foo").OfType<MethodSymbol>().Single(); var interfaceType = classRefLocalType.GetDeclaredInterfaces(null).First(); Assert.Same(canonicalType, interfaceType); Assert.IsAssignableFrom<PENamedTypeSymbol>(interfaceType); } [Fact] public void NoPIATypeSubstitutionForMethodExplicitlyImplementNoPiaInterface() { //Check type substitution for a method of a class that implement PIA interface var localConsumer = CreateEmptyCompilation(assemblyName: "Dummy", source: CSharpTestSource.None, references: new List<MetadataReference>() { TestReferences.SymbolsTests.NoPia.GeneralPia, TestReferences.SymbolsTests.NoPia.ExternalAsm1 }); var localConsumerRefsAsm = localConsumer.Assembly.GetNoPiaResolutionAssemblies(); var canonicalType = localConsumerRefsAsm.First(arg => arg.Name == "GeneralPia").GlobalNamespace.GetTypeMembers("ISubFuncProp").Single(); NamedTypeSymbol classRefLocalType = localConsumerRefsAsm.First(arg => arg.Name == "ExternalAsm1").GlobalNamespace.GetTypeMembers("SubFuncProp").Single(); MethodSymbol methodSymbol = classRefLocalType.GetMembers("Foo").OfType<MethodSymbol>().Single(); Assert.Equal(0, methodSymbol.ExplicitInterfaceImplementations.Length); } [Fact] public void NoPiaAmbiguousCanonicalTypeSymbolForStruct() { //NoPiaAmbiguousCanonicalTypeSymbol for the corresponding interface type. var localConsumer = CreateEmptyCompilation(assemblyName: "Dummy", source: CSharpTestSource.None, references: new List<MetadataReference>() { TestReferences.SymbolsTests.NoPia.GeneralPia, TestReferences.SymbolsTests.NoPia.GeneralPiaCopy, TestReferences.SymbolsTests.NoPia.ExternalAsm1 }); var localConsumerRefsAsm = localConsumer.Assembly.GetNoPiaResolutionAssemblies(); NamedTypeSymbol classRefLocalType = localConsumerRefsAsm.First(arg => arg.Name == "ExternalAsm1").GlobalNamespace.GetTypeMembers("ExternalAsm1").Single(); MethodSymbol refMethodSymbol = classRefLocalType.GetMembers("Scen2").OfType<MethodSymbol>().Single(); ImmutableArray<ParameterSymbol> param = refMethodSymbol.Parameters; NoPiaAmbiguousCanonicalTypeSymbol ambiguous = (NoPiaAmbiguousCanonicalTypeSymbol)param.First().Type; Assert.Equal(SymbolKind.ErrorType, param.First().Type.Kind); Assert.IsType<NoPiaAmbiguousCanonicalTypeSymbol>(param.First().Type); Assert.Same(localConsumerRefsAsm.First(arg => arg.Name == "ExternalAsm1"), ambiguous.EmbeddingAssembly); Assert.Same(localConsumerRefsAsm.First(arg => arg.Name == "GeneralPia").GlobalNamespace.ChildNamespace("InheritanceConflict").GetTypeMembers("IBase").Single(), ambiguous.FirstCandidate); Assert.Same(localConsumerRefsAsm.First(arg => arg.Name == "GeneralPiaCopy").GlobalNamespace.ChildNamespace("InheritanceConflict").GetTypeMembers("IBase").Single(), ambiguous.SecondCandidate); } [Fact] public void NoPiaLeaveOutAllidentifyingAttributesOnAStructButUseItInAPIAInterface() { //Leave out all identifying attributes on a Struct, but use it in a PIA interface, and cause the PIA interface to be imported var localTypeSource1 = @" using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Collections.Generic; [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [assembly: ImportedFromTypeLib(""NoPIAMixPIANonPIATypesIInterface.dll"")] public struct Structure1 { public double Data; } public class Class1 { } [Guid(""27e3e649-994b-4f58-b3c6-f8089a5f2c6c""), ComImport(), CoClass(typeof(InterfaceImpl)), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IInterface { Structure1 Prop1 { get; set; } void Method1(ref Class1 c1); } [Guid(""c9dcf748-b634-4504-a7ce-348cf7c61891"")] public class InterfaceImpl { }"; var localTypeSource2 = @"public class IdentifyingAttributes { Structure1 s = new IInterface().Prop1[0.0]; public IInterface Foo() { return new IInterface(); } }"; var localType1 = CreateCompilation(assemblyName: "Dummy1", source: localTypeSource1, references: null); var localType2 = CreateCompilation(assemblyName: "Dummy2", source: localTypeSource2, references: new List<MetadataReference>() { new CSharpCompilationReference(localType1, embedInteropTypes: true) }); Assert.True(localType2.Assembly.GetNoPiaResolutionAssemblies().First(arg => arg.Name == "Dummy1").IsLinked); var localConsumer = CreateCompilation(source: "", assemblyName: "Dummy3", references: new List<MetadataReference>() { new CSharpCompilationReference(localType2), new CSharpCompilationReference(localType1) }); var localConsumerRefsAsm = localConsumer.Assembly.GetNoPiaResolutionAssemblies(); var importedType = localConsumerRefsAsm.First(arg => arg.Name == "Dummy2").GlobalNamespace.GetTypeMembers("IdentifyingAttributes").Single(); var methodSymbol = importedType.GetMembers("Foo").OfType<MethodSymbol>().Single(); Assert.Equal(SymbolKind.NamedType, methodSymbol.ReturnType.Kind); Assert.IsAssignableFrom<SourceNamedTypeSymbol>(methodSymbol.ReturnType); } [Fact] public void NoPiaTypeSubstitutionWithHandAuthoredLocalType() { //Try to apply attributes to the local type that indicates that the type is intended to be used for type equivalence. var localTypeSource = @" using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Collections.Generic; public class LocalTypes1 { public I1 Test1() { return null; } } [ComImport, Guid(""27e3e649-994b-4f58-b3c6-f8089a5f2c01""), TypeIdentifier, CompilerGenerated, InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface I1 { }"; var localType = CreateCompilation(assemblyName: "Dummy1", source: localTypeSource, references: null); var localConsumer = CreateCompilation(assemblyName: "Dummy2", source: "", references: new List<MetadataReference>() { TestReferences.SymbolsTests.NoPia.Pia1, new CSharpCompilationReference(localType) }); var localConsumerRefsAsm = localConsumer.Assembly.GetNoPiaResolutionAssemblies(); var importedTypeComp2 = localConsumerRefsAsm.First(arg => arg.Name == "Dummy1").GlobalNamespace.GetTypeMembers("LocalTypes1").Single(); var embeddedType = importedTypeComp2.GetMembers("Test1").OfType<MethodSymbol>().Single(); var importedTypeAsm = localConsumerRefsAsm.First(arg => arg.Name == "Pia1").GlobalNamespace.GetTypeMembers("I1").Single(); Assert.Same(embeddedType.ReturnType, importedTypeAsm); Assert.Equal(SymbolKind.NamedType, embeddedType.ReturnType.Kind); } } }
53.306418
215
0.63922
[ "Apache-2.0" ]
20chan/roslyn
src/Compilers/CSharp/Test/Symbol/Symbols/Metadata/PE/NoPiaLocalHideAndTypeSubstitutionTests.cs
25,749
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using TeleSharp.TL; namespace TeleSharp.TL.Phone { [TLObject(-326966976)] public class TLPhoneCall : TLObject { public override int Constructor { get { return -326966976; } } public TLAbsPhoneCall PhoneCall { get; set; } public TLVector<TLAbsUser> Users { get; set; } public void ComputeFlags() { } public override void DeserializeBody(BinaryReader br) { PhoneCall = (TLAbsPhoneCall)ObjectUtils.DeserializeObject(br); Users = (TLVector<TLAbsUser>)ObjectUtils.DeserializeVector<TLAbsUser>(br); } public override void SerializeBody(BinaryWriter bw) { bw.Write(Constructor); ObjectUtils.SerializeObject(PhoneCall, bw); ObjectUtils.SerializeObject(Users, bw); } } }
22.673913
86
0.601151
[ "MIT" ]
Vladimir-Novick/TLSharp.NetCore2
TeleSharp.NetCore2.TL/TL/Phone/TLPhoneCall.cs
1,043
C#
using System.Threading; using System.Threading.Tasks; using Binance.Net.Objects.Futures.MarketData; using CryptoExchange.Net.Objects; namespace Binance.Net.Interfaces.SubClients.Futures { /// <summary> /// Futures system interface /// </summary> public interface IBinanceClientFuturesCoinSystem { /// <summary> /// Get's information about the exchange including rate limits and symbol list /// </summary> /// <param name="ct">Cancellation token</param> /// <returns>Exchange info</returns> Task<WebCallResult<BinanceFuturesCoinExchangeInfo>> GetExchangeInfoAsync(CancellationToken ct = default); } }
32.095238
113
0.697329
[ "MIT" ]
GLipitch/Binance.Net
Binance.Net/Interfaces/SubClients/Futures/IBinanceClientFuturesCoinSystem.cs
676
C#
using DSharpPlus; using DSharpPlus.Entities; using DSharpPlus.SlashCommands; using HGV.Reaver.Models; using HGV.Reaver.Services; using Microsoft.Extensions.Options; using System.Threading.Tasks; namespace HGV.Reaver.Commands { [SlashCommandGroup("Account", "Account Commands")] public class AccountCommands : ApplicationCommandModule { private readonly string baseUrl; private readonly IAccountService accountService; private readonly IProfileService profileService; public AccountCommands(IOptions<ReaverSettings> settings, IAccountService accountService, IProfileService profileService) { this.baseUrl = settings.Value?.BaseURL ?? throw new ConfigurationValueMissingException(nameof(ReaverSettings.BaseURL)); this.accountService = accountService; this.profileService = profileService; } [SlashCommand("Link", "Links your Discord and Steam accounts")] public async Task Link(InteractionContext ctx) { await ctx.CreateResponseAsync(InteractionResponseType.DeferredChannelMessageWithSource, new DiscordInteractionResponseBuilder() { IsEphemeral = true }); var builder = new DiscordEmbedBuilder(); builder.WithColor(DiscordColor.Purple); builder.WithTitle("Click Here to Link Accounts"); builder.WithDescription("A number of the commands require linked accounts. Click the link above to sign into discord and steam to link the accounts."); builder.WithUrl($"{this.baseUrl}/account/link/{ctx.Guild.Id}"); builder.WithThumbnail("https://hyperstone.highgroundvision.com/images/hgv/bot-logo.png"); await ctx.EditResponseAsync(new DiscordWebhookBuilder().AddEmbed(builder.Build())); } [SlashCommand("Delink", "Everyone deserves the right to be forgotten")] public async Task Delink(InteractionContext ctx) { await ctx.CreateResponseAsync(InteractionResponseType.DeferredChannelMessageWithSource, new DiscordInteractionResponseBuilder() { IsEphemeral = true }); await this.accountService.Remove(ctx.Guild.Id, ctx.Member.Id); await ctx.EditResponseAsync(new DiscordWebhookBuilder().WithContent("Done!")); } [SlashCommand("Refresh","Overrides your discord nickname to match your steam persona and refreshes your cache profile images.")] public async Task Refresh(InteractionContext ctx) { await ctx.CreateResponseAsync(InteractionResponseType.DeferredChannelMessageWithSource, new DiscordInteractionResponseBuilder() { IsEphemeral = true }); var account = await this.accountService.Get(ctx.Member.Guild.Id, ctx.Member.Id); var dota = await this.profileService.GetDotaProfile(account.SteamId); var steam = await this.profileService.GetSteamProfile(account.SteamId); var nickname = steam?.Persona ?? dota?.Nickname; if (nickname is not null) { await ctx.Member.ModifyAsync(x => x.Nickname = nickname); } await ctx.EditResponseAsync(new DiscordWebhookBuilder().WithContent("Done!")); } } }
46.328571
164
0.699969
[ "MIT" ]
HighGroundVision/Reaver
src/HGV.Reaver/Commands/AccountCommands.cs
3,245
C#
using System; using System.Collections.Generic; using BenchmarkDotNet.Attributes; using JustEvaluate.UtilityFunctions; namespace JustEvaluate.Benchmark { [SimpleJob] public class BasicBenchmark { private Evaluator _evaluator; private Func<Input, decimal> _function; private readonly string formula = "Amount * 10 / 100 + Sqrt(Amount)"; [GlobalSetup] public void Setup() { var expressionCache = new CompiledExpressionsCache(); _evaluator = new Evaluator(new Parser(), new Builder(new FunctionsRegistry().AddMath()), expressionCache); // force caching _evaluator.Evaluate(formula, new Input { Amount = 0 }); _function = expressionCache.Get<Input>(formula); } [Params(40, 1098887)] public decimal Amount { get; set; } [Benchmark] public decimal UsingEvaluatorWithObjectArgument() => _evaluator.Evaluate(formula, new Input {Amount = Amount }); [Benchmark] public decimal UsingEvaluatorWithDictionaryArgument() => _evaluator.Evaluate(formula, new Dictionary<string, decimal> { { "Amount", Amount } }); [Benchmark] public decimal UsingCompiledExpression() => _function(new Input { Amount = Amount }); [Benchmark(Baseline = true)] public decimal Coded() { return Amount * 10 / 100 + (decimal)Math.Sqrt((double)Amount); } } public class Input { public decimal Amount { get; set; } } }
30.352941
152
0.631137
[ "MIT" ]
petar-m/JustEvaluate
test/JustEvaluate.Benchmark/BasicBenchmark.cs
1,550
C#
namespace MakeUpBakery.Web.Areas.Administration.Controllers { using MakeUpBakery.Services.Data; using MakeUpBakery.Web.ViewModels.Administration.Dashboard; using Microsoft.AspNetCore.Mvc; public class DashboardController : AdministrationController { private readonly ISettingsService settingsService; public DashboardController(ISettingsService settingsService) { this.settingsService = settingsService; } public IActionResult Index() { var viewModel = new IndexViewModel { SettingsCount = this.settingsService.GetCount(), }; return this.View(viewModel); } } }
28.416667
100
0.687683
[ "MIT" ]
MadlenaIvanov/MakeUpBakery
MakeUpBakery/Web/MakeUpBakery.Web/Areas/Administration/Controllers/DashboardController.cs
684
C#
// // Copyright 2020 Google LLC // // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. // using Google.Apis.Auth.OAuth2; using Google.Solutions.Common.Locator; using Google.Solutions.Common.Test; using Google.Solutions.Common.Test.Integration; using Google.Solutions.IapDesktop.Application.Services.Adapters; using NUnit.Framework; using System; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace Google.Solutions.IapDesktop.Application.Test.Services.Adapters { [TestFixture] [Category("IntegrationTest")] public class TestComputeEngineAdapter : ApplicationFixtureBase { //--------------------------------------------------------------------- // Projects. //--------------------------------------------------------------------- [Test] public async Task WhenUserInViewerRole_ThenGetProjectReturnsProject( [Credential(Role = PredefinedRole.ComputeViewer)] ResourceTask<ICredential> credential) { var adapter = new ComputeEngineAdapter(await credential); var project = await adapter.GetProjectAsync( TestProject.ProjectId, CancellationToken.None); Assert.IsNotNull(project); Assert.AreEqual(TestProject.ProjectId, project.Name); } [Test] public async Task WhenUserNotInRole_ThenGetProjectThrowsResourceAccessDeniedException( [Credential(Role = PredefinedRole.IapTunnelUser)] ResourceTask<ICredential> credential) { var adapter = new ComputeEngineAdapter(await credential); AssertEx.ThrowsAggregateException<ResourceAccessDeniedException>( () => adapter.GetProjectAsync( TestProject.ProjectId, CancellationToken.None).Wait()); } [Test] public async Task WhenProjectIdInvalid_ThenGetProjectThrowsGoogleApiException( [Credential(Role = PredefinedRole.IapTunnelUser)] ResourceTask<ICredential> credential) { var adapter = new ComputeEngineAdapter(await credential); AssertEx.ThrowsAggregateException<GoogleApiException>( () => adapter.GetProjectAsync( TestProject.InvalidProjectId, CancellationToken.None).Wait()); } //--------------------------------------------------------------------- // Instances. //--------------------------------------------------------------------- [Test] public async Task WhenUserInViewerRole_ThenListInstancesAsyncReturnsInstances( [LinuxInstance] ResourceTask<InstanceLocator> testInstance, [Credential(Role = PredefinedRole.ComputeViewer)] ResourceTask<ICredential> credential) { // Make sure there is at least one instance. await testInstance; var instanceRef = await testInstance; var adapter = new ComputeEngineAdapter(await credential); var instances = await adapter.ListInstancesAsync( TestProject.ProjectId, CancellationToken.None); Assert.Greater(instances.Count(), 1); Assert.IsNotNull(instances.FirstOrDefault(i => i.Name == instanceRef.Name)); } [Test] public async Task WhenUserInViewerRole_ThenListInstancesAsyncByZoneReturnsInstances( [LinuxInstance] ResourceTask<InstanceLocator> testInstance, [Credential(Role = PredefinedRole.ComputeViewer)] ResourceTask<ICredential> credential) { // Make sure there is at least one instance. await testInstance; var instanceRef = await testInstance; var adapter = new ComputeEngineAdapter(await credential); var instances = await adapter.ListInstancesAsync( new ZoneLocator(TestProject.ProjectId, instanceRef.Zone), CancellationToken.None); Assert.Greater(instances.Count(), 1); Assert.IsNotNull(instances.FirstOrDefault(i => i.Name == instanceRef.Name)); } [Test] public async Task WhenUserNotInRole_ThenListInstancesAsyncThrowsResourceAccessDeniedException( [Credential(Role = PredefinedRole.IapTunnelUser)] ResourceTask<ICredential> credential) { var adapter = new ComputeEngineAdapter(await credential); AssertEx.ThrowsAggregateException<ResourceAccessDeniedException>( () => adapter.ListInstancesAsync( TestProject.ProjectId, CancellationToken.None).Wait()); } [Test] public async Task WhenUserNotInRole_ThenListInstancesAsyncByZoneThrowsResourceAccessDeniedException( [Credential(Role = PredefinedRole.IapTunnelUser)] ResourceTask<ICredential> credential) { var adapter = new ComputeEngineAdapter(await credential); AssertEx.ThrowsAggregateException<ResourceAccessDeniedException>( () => adapter.ListInstancesAsync( new ZoneLocator(TestProject.ProjectId, "us-central1-a"), CancellationToken.None).Wait()); } [Test] public async Task WhenUserNotInRole_ThenGetInstanceAsyncThrowsResourceAccessDeniedException( [LinuxInstance] ResourceTask<InstanceLocator> testInstance, [Credential(Role = PredefinedRole.IapTunnelUser)] ResourceTask<ICredential> credential) { var locator = await testInstance; var adapter = new ComputeEngineAdapter(await credential); AssertEx.ThrowsAggregateException<ResourceAccessDeniedException>( () => adapter.GetInstanceAsync( locator, CancellationToken.None).Wait()); } //--------------------------------------------------------------------- // Guest attributes. //--------------------------------------------------------------------- [Test] public async Task WhenUserNotInRole_ThenGetGuestAttributesAsyncThrowsResourceAccessDeniedException( [LinuxInstance] ResourceTask<InstanceLocator> testInstance, [Credential(Role = PredefinedRole.IapTunnelUser)] ResourceTask<ICredential> credential) { var locator = await testInstance; var adapter = new ComputeEngineAdapter(await credential); AssertEx.ThrowsAggregateException<ResourceAccessDeniedException>( () => adapter.GetGuestAttributesAsync( locator, "somepath/", CancellationToken.None).Wait()); } //--------------------------------------------------------------------- // Nodes. //--------------------------------------------------------------------- [Test] public async Task WhenUserNotInRole_ThenListNodeGroupsAsyncThrowsResourceAccessDeniedException( [Credential(Role = PredefinedRole.IapTunnelUser)] ResourceTask<ICredential> credential) { var adapter = new ComputeEngineAdapter(await credential); AssertEx.ThrowsAggregateException<ResourceAccessDeniedException>( () => adapter.ListNodeGroupsAsync( TestProject.ProjectId, CancellationToken.None).Wait()); } [Test] public async Task WhenUserNotInRole_ThenListNodesAsyncThrowsResourceAccessDeniedException( [Credential(Role = PredefinedRole.IapTunnelUser)] ResourceTask<ICredential> credential) { var adapter = new ComputeEngineAdapter(await credential); AssertEx.ThrowsAggregateException<ResourceAccessDeniedException>( () => adapter.ListNodesAsync( TestProject.ProjectId, CancellationToken.None).Wait()); AssertEx.ThrowsAggregateException<ResourceAccessDeniedException>( () => adapter.ListNodesAsync( new ZoneLocator(TestProject.ProjectId, "us-central1-a"), "group-1", CancellationToken.None).Wait()); } //--------------------------------------------------------------------- // Disks/Images. //--------------------------------------------------------------------- [Test] public async Task WhenUserNotInRole_ThenListDisksAsyncThrowsResourceAccessDeniedException( [Credential(Role = PredefinedRole.IapTunnelUser)] ResourceTask<ICredential> credential) { var adapter = new ComputeEngineAdapter(await credential); AssertEx.ThrowsAggregateException<ResourceAccessDeniedException>( () => adapter.ListDisksAsync( TestProject.ProjectId, CancellationToken.None).Wait()); } [Test] public async Task WhenUserNotInRole_ThenGetImageThrowsResourceAccessDeniedException( [Credential(Role = PredefinedRole.IapTunnelUser)] ResourceTask<ICredential> credential) { var adapter = new ComputeEngineAdapter(await credential); AssertEx.ThrowsAggregateException<ResourceAccessDeniedException>( () => adapter.GetImageAsync( new ImageLocator(TestProject.ProjectId, "someimage"), CancellationToken.None).Wait()); } //--------------------------------------------------------------------- // Serial port. //--------------------------------------------------------------------- [Test] public async Task WhenLaunchingInstance_ThenInstanceSetupFinishedTextAppearsInStream( [WindowsInstance] ResourceTask<InstanceLocator> testInstance, [Credential(Role = PredefinedRole.ComputeViewer)] ResourceTask<ICredential> credential) { var adapter = new ComputeEngineAdapter(await credential); var stream = adapter.GetSerialPortOutput( await testInstance, 1); var startTime = DateTime.Now; while (DateTime.Now < startTime.AddMinutes(3)) { var log = await stream.ReadAsync(CancellationToken.None); if (log.Contains("Finished running startup scripts")) { return; } } Assert.Fail("Timeout waiting for serial console output to appear"); } //--------------------------------------------------------------------- // Permission check. //--------------------------------------------------------------------- [Test] public async Task WhenUserInRole_ThenIsGrantedPermissionReturnsTrue( [LinuxInstance] ResourceTask<InstanceLocator> testInstance, [Credential(Role = PredefinedRole.ComputeViewer)] ResourceTask<ICredential> credential) { var locator = await testInstance; var adapter = new ComputeEngineAdapter(await credential); var result = await adapter.IsGrantedPermission( locator, Permissions.ComputeInstancesGet); Assert.IsTrue(result); } [Test] public async Task WhenUserNotInRole_ThenIsGrantedPermissionReturnsFalse( [LinuxInstance] ResourceTask<InstanceLocator> testInstance, [Credential(Role = PredefinedRole.ComputeViewer)] ResourceTask<ICredential> credential) { var locator = await testInstance; var adapter = new ComputeEngineAdapter(await credential); var result = await adapter.IsGrantedPermission( locator, Permissions.ComputeInstancesSetMetadata); Assert.IsFalse(result); } [Test] public async Task WhenUserLacksInstanceListPermission_ThenIsGrantedPermissionFailsOpenAndReturnsTrue( [LinuxInstance] ResourceTask<InstanceLocator> testInstance, [Credential(Role = PredefinedRole.IapTunnelUser)] ResourceTask<ICredential> credential) { var locator = await testInstance; var adapter = new ComputeEngineAdapter(await credential); var result = await adapter.IsGrantedPermission( locator, Permissions.ComputeInstancesSetMetadata); Assert.IsTrue(result); } } }
41.750779
109
0.592747
[ "Apache-2.0" ]
Theschme96/iap-desktop
sources/Google.Solutions.IapDesktop.Application.Test/Services/Adapters/TestComputeEngineAdapter.cs
13,404
C#
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; namespace timw255.Sitefinity.RestClient.Model { public class CartDiscount : IDynamicFieldsContainer { public string ApplicationName { get; set; } public decimal DiscountAmount { get; set; } public string DiscountAmountDisplay { get; set; } public DiscountAmountType DiscountAmountType { get; set; } public DiscountType DiscountType { get; set; } public Guid Id { get; set; } public DateTime LastModified { get; set; } public decimal SavingsAmount { get; set; } public string SavingsAmountFormatted { get; set; } public Lstring Title { get; set; } public CartDiscount() { } } }
32
66
0.680288
[ "MIT" ]
timw255/timw255.Sitefinity.RestClient
timw255.Sitefinity.RestClient/Model/CartDiscount.cs
834
C#
using UniRx; using UnityEngine; using UnityEngine.UI; namespace Samples.Section5.ModelViewReactivePresenter { /// <summary> /// Presenter /// </summary> public class CountPresenter : MonoBehaviour { // Modelへの参照 [SerializeField] private CountModel _countModel; // View(uGUIコンポーネント)への参照 [SerializeField] private InputField _inputField; [SerializeField] private Button _upButton; [SerializeField] private Button _downButton; [SerializeField] private Slider _slider; private void Start() { // UniRxの機能を活用して、ModelとViewを相互接続する // Model -> View _countModel.Current .Subscribe(x => { // Modelの値が変動したら // InputFieldとSliderの状態を更新 _inputField.text = x.ToString(); _slider.value = x; }) .AddTo(this); // ----- // View -> Model // InputFieldが更新されたらModelに反映 _inputField .OnValueChangedAsObservable() .Select(x => { var isSucceed = int.TryParse(x, out var value); return (isSucceed, value); }) .Where(x => x.isSucceed) .Subscribe(x => _countModel.UpdateCount(x.value)) .AddTo(this); // Sliderが更新されたらModelに反映 _slider .OnValueChangedAsObservable() .Subscribe(x => _countModel.UpdateCount((int) x)) .AddTo(this); // Buttonが押されたらModelに反映 Observable.Merge( _upButton.OnClickAsObservable().Select(_ => +1), _downButton.OnClickAsObservable().Select(_ => -1) ).Subscribe(value => { _countModel.UpdateCount(_countModel.Current.Value + value); }) .AddTo(this); } } }
29.385714
79
0.494409
[ "Unlicense", "CC0-1.0", "MIT" ]
TORISOUP/UniRx-UniTask_Samples
Assets/Samples/Section5/ModelViewReactivePresenter/CountPresenter.cs
2,211
C#
using Microsoft.Extensions.Configuration; using NeoSharp.Core.Network.Security; namespace NeoSharp.Core.Network { public class NetworkConfig { /// <summary> /// Magic number /// </summary> public uint Magic { get; internal set; } /// <summary> /// Portt /// </summary> public ushort Port { get; internal set; } /// <summary> /// Force Ipv6 /// </summary> public bool ForceIPv6 { get; internal set; } /// <summary> /// Peers /// </summary> public EndPoint[] PeerEndPoints { get; internal set; } /// <summary> /// Acl Config /// </summary> public NetworkAclConfig AclConfig { get; internal set; } /// <summary> /// StandByValidator config /// </summary> public string[] StandByValidator { get; internal set; } /// <summary> /// Max number of connected peers /// </summary> public ushort MaxConnectedPeers { get; internal set; } = 10; /// <summary> /// Constructor /// </summary> /// <param name="configuration">Configuration</param> public NetworkConfig(IConfiguration configuration) { PeerEndPoints = new EndPoint[0]; configuration?.GetSection("network")?.Bind(this); } } }
29.702128
68
0.532951
[ "MIT" ]
BSathvik/neo-sharp
src/NeoSharp.Core/Network/NetworkConfig.cs
1,398
C#
using System; using NetRuntimeSystem = System; using System.ComponentModel; using NetOffice.Attributes; namespace NetOffice.MSHTMLApi { /// <summary> /// DispatchInterface IHTMLFontNamesCollection /// SupportByVersion MSHTML, 4 /// </summary> [SupportByVersion("MSHTML", 4)] [EntityType(EntityType.IsDispatchInterface)] public class IHTMLFontNamesCollection : COMObject { #pragma warning disable #region Type Information /// <summary> /// Instance Type /// </summary> [EditorBrowsable(EditorBrowsableState.Advanced), Browsable(false), Category("NetOffice"), CoreOverridden] public override Type InstanceType { get { return LateBindingApiWrapperType; } } private static Type _type; [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public static Type LateBindingApiWrapperType { get { if (null == _type) _type = typeof(IHTMLFontNamesCollection); return _type; } } #endregion #region Ctor /// <param name="factory">current used factory core</param> /// <param name="parentObject">object there has created the proxy</param> /// <param name="proxyShare">proxy share instead if com proxy</param> public IHTMLFontNamesCollection(Core factory, ICOMObject parentObject, COMProxyShare proxyShare) : base(factory, parentObject, proxyShare) { } ///<param name="factory">current used factory core</param> ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> public IHTMLFontNamesCollection(Core factory, ICOMObject parentObject, object comProxy) : base(factory, parentObject, comProxy) { } ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public IHTMLFontNamesCollection(ICOMObject parentObject, object comProxy) : base(parentObject, comProxy) { } ///<param name="factory">current used factory core</param> ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> ///<param name="comProxyType">Type of inner wrapped COM proxy"</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public IHTMLFontNamesCollection(Core factory, ICOMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(factory, parentObject, comProxy, comProxyType) { } ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> ///<param name="comProxyType">Type of inner wrapped COM proxy"</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public IHTMLFontNamesCollection(ICOMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(parentObject, comProxy, comProxyType) { } ///<param name="replacedObject">object to replaced. replacedObject are not usable after this action</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public IHTMLFontNamesCollection(ICOMObject replacedObject) : base(replacedObject) { } [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public IHTMLFontNamesCollection() : base() { } /// <param name="progId">registered progID</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public IHTMLFontNamesCollection(string progId) : base(progId) { } #endregion #region Properties /// <summary> /// SupportByVersion MSHTML 4 /// Get /// </summary> [SupportByVersion("MSHTML", 4)] [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public Int32 length { get { return Factory.ExecuteInt32PropertyGet(this, "length"); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get /// Unknown COM Proxy /// </summary> [SupportByVersion("MSHTML", 4), ProxyResult] [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public object _newEnum { get { return Factory.ExecuteReferencePropertyGet(this, "_newEnum"); } } #endregion #region Methods /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <param name="index">Int32 index</param> [SupportByVersion("MSHTML", 4)] public string item(Int32 index) { return Factory.ExecuteStringMethodGet(this, "item", index); } #endregion #pragma warning restore } }
29.772152
179
0.698554
[ "MIT" ]
DominikPalo/NetOffice
Source/MSHTML/DispatchInterfaces/IHTMLFontNamesCollection.cs
4,706
C#
using ManagePlan.Core.Models; using ManagePlan.Service.IServices; using Microsoft.AspNetCore.Cors; using Microsoft.AspNetCore.Mvc; using System.Threading.Tasks; namespace ManagePlan.Controllers { [EnableCors("AllowAll")] [Route("api/[controller]")] [ApiController] public class TransactionController : Controller { private readonly ITransactionService transactionService; public TransactionController(ITransactionService transactionService) { this.transactionService = transactionService; } [HttpGet] public async Task<IActionResult> GetAll() { var data = await transactionService.GetAllTransactions(); return Ok(data); } [HttpGet("{id}")] public async Task<IActionResult> GetById(int id) { var data = await transactionService.GetTransactionById(id); if (data == null) return Ok(); return Ok(data); } [HttpPost] public async Task<IActionResult> Add(Transaction transaction) { await transactionService.AddTransaction(transaction); return Ok(); } [HttpDelete("{id}")] public async Task<IActionResult> Delete(int id) { await transactionService.DeleteTransaction(id); return Ok(); } [HttpPut] public async Task<IActionResult> Update(Transaction transaction) { await transactionService.UpdateTransaction(transaction); return Ok(); } [HttpGet("account/{accountId}")] public async Task<IActionResult> GetAllByAccountId(int accountId) { var data = await transactionService.GetTransactionsByAccountId(accountId); return Ok(data); } } }
28.921875
86
0.615883
[ "MIT" ]
Baintastic/ManagePlan
ManagePlan/Controllers/TransactionController.cs
1,853
C#
using Avalonia.Input; using Avalonia.Input.Raw; using Avalonia.Platform; using Avalonia.Rendering; using Avalonia.Threading; using System; using System.Collections.Generic; namespace Avalonia.DfrFrameBuffer { class FramebufferToplevelImpl : IEmbeddableWindowImpl { private readonly BridgeFrameBuffer _fb; private bool _renderQueued; public IInputRoot InputRoot { get; private set; } public FramebufferToplevelImpl(BridgeFrameBuffer fb) { _fb = fb; Invalidate(default); var digiziter = new Digitizer(ClientSize.Width, ClientSize.Height, fb.Dpi); digiziter.Start(); digiziter.Event += e => Input?.Invoke(e); } public IRenderer CreateRenderer(IRenderRoot root) { return new ImmediateRenderer(root); } public void Dispose() { throw new NotSupportedException(); } public void Invalidate(Rect rect) { if(_renderQueued) return; _renderQueued = true; Dispatcher.UIThread.Post(() => { Paint?.Invoke(new Rect(default, ClientSize)); _renderQueued = false; }); } public void SetInputRoot(IInputRoot inputRoot) { InputRoot = inputRoot; } public Point PointToClient(PixelPoint p) => p.ToPoint(1); public PixelPoint PointToScreen(Point p) => PixelPoint.FromPoint(p, 1); public void SetCursor(IPlatformHandle cursor) { } public Size ClientSize => new Size(2170, 60); public IMouseDevice MouseDevice => BridgeFrameBufferPlatform.MouseDevice; public double Scaling => 1; public IEnumerable<object> Surfaces => new object[] {_fb}; public Action<RawInputEventArgs> Input { get; set; } public Action<Rect> Paint { get; set; } public Action<Size> Resized { get; set; } public Action<double> ScalingChanged { get; set; } public Action Closed { get; set; } public event Action LostFocus { add {} remove {} } } }
28.986842
87
0.592828
[ "MIT" ]
imbushuo/DFRContentHost
Avalonia.DfrFrameBuffer/FramebufferToplevelImpl.cs
2,205
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web.Http; namespace DocDbRestAPI { public static class WebApiConfig { public static void Register(HttpConfiguration config) { // Web API configuration and services // Web API routes config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); } } }
23.48
62
0.58092
[ "MIT" ]
HEDIDIN/DocumentDB-REST
DocumentDBRestApi/DocDbRestAPI/App_Start/WebApiConfig.cs
589
C#
// <auto-generated> // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Gov.Lclb.Cllb.Interfaces.Models { using Newtonsoft.Json; using System.Linq; /// <summary> /// SearchResponse /// </summary> public partial class MicrosoftDynamicsCRMSearchResponse { /// <summary> /// Initializes a new instance of the /// MicrosoftDynamicsCRMSearchResponse class. /// </summary> public MicrosoftDynamicsCRMSearchResponse() { CustomInit(); } /// <summary> /// Initializes a new instance of the /// MicrosoftDynamicsCRMSearchResponse class. /// </summary> public MicrosoftDynamicsCRMSearchResponse(MicrosoftDynamicsCRMSearchResults searchResults = default(MicrosoftDynamicsCRMSearchResults)) { SearchResults = searchResults; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// </summary> [JsonProperty(PropertyName = "SearchResults")] public MicrosoftDynamicsCRMSearchResults SearchResults { get; set; } } }
29
143
0.62931
[ "Apache-2.0" ]
danieltruong/ag-lclb-cllc-public
cllc-interfaces/Dynamics-Autorest/Models/MicrosoftDynamicsCRMSearchResponse.cs
1,392
C#
using System.Web; using System.Web.Mvc; using System.Web.UI; using ClientDependency.Core; using ClientDependency.Core.CompositeFiles; namespace Umbraco.Web.Mvc { /// <summary> /// Minifies and caches the result for the JavaScriptResult /// </summary> /// <remarks> /// Only minifies in release mode /// </remarks> public class MinifyJavaScriptResultAttribute : ActionFilterAttribute { /// <summary> /// Minify the result if in release mode /// </summary> /// <param name="filterContext"></param> public override void OnResultExecuting(ResultExecutingContext filterContext) { base.OnResultExecuting(filterContext); if (filterContext.Result == null) return; var jsResult = filterContext.Result as JavaScriptResult; if (jsResult == null) return; if (filterContext.HttpContext.IsDebuggingEnabled) return; //minify the result var result = jsResult.Script; var minifier = new JSMin(); var minified = minifier.Minify(result); jsResult.Script = minified; } } }
31.394737
84
0.612741
[ "MIT" ]
AdrianJMartin/Umbraco-CMS
src/Umbraco.Web/Mvc/MinifyJavaScriptResultAttribute.cs
1,195
C#
using d60.Cirqus.AzureServiceBus.Dispatcher; using d60.Cirqus.AzureServiceBus.Relay; using d60.Cirqus.Config.Configurers; using d60.Cirqus.Events; using Microsoft.ServiceBus; namespace d60.Cirqus.AzureServiceBus.Config { public static class AzureServiceBusConfigurationExtensions { public static void UseAzureServiceBusEventDispatcher(this EventDispatcherConfigurationBuilder builder, string connectionString, string topicName) { builder.UseEventDispatcher(context => new AzureServiceBusEventDispatcherSender(connectionString, topicName)); } /// <summary> /// Installs an event dispatcher that can be contacted from anywhere /// </summary> public static void UseAzureServiceBusRelayEventDispatcher(this EventDispatcherConfigurationBuilder builder, string serviceNamespace, string servicePath, string keyName, string sharesAccessKey, NetTcpRelayBinding netTcpRelayBinding = null) { builder.UseEventDispatcher(context => { var eventStore = context.Get<IEventStore>(); return new AzureServiceBusRelayEventDispatcher(eventStore, serviceNamespace, servicePath, keyName, sharesAccessKey, netTcpRelayBinding); }); } } }
45.103448
247
0.71789
[ "MIT" ]
d60/Cirqus
d60.Cirqus.AzureServiceBus/Config/AzureServiceBusConfigurationExtensions.cs
1,310
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ChangeCamera : MonoBehaviour { public Camera topDownCam; public Animator topAnimator; public Camera sideCam; private BoxCollider birdCollider; // Start is called before the first frame update void Start() { // start game in top down view topDownCam.enabled = true; sideCam.enabled = false; topAnimator = topDownCam.GetComponent<Animator>(); birdCollider = gameObject.GetComponent<BoxCollider>(); } // Update is called once per frame void Update() { if (Input.GetKeyDown(KeyCode.P)) { // play animation depending on which camera is on if (topDownCam.enabled) { topAnimator.CrossFadeInFixedTime("ShiftToSide", 0); // wait a second and switch to side camera StartCoroutine(WaitAndSwitch()); } else // sideCam.enabled { //switch back to top camera topDownCam.enabled = true; sideCam.enabled = false; topAnimator.CrossFadeInFixedTime("ShiftToTop", 0); //change collider back to 3D birdCollider.size = new Vector3(1.0f, 1.0f, 1.0f); } } } // Wait one second (length of animation) before switching to side camera // and extending collider to at least double width of stage IEnumerator WaitAndSwitch() { yield return new WaitForSeconds(1f); topDownCam.enabled = false; sideCam.enabled = true; birdCollider.size = new Vector3(100.0f, 1.0f, 1.0f); } }
27.571429
76
0.591825
[ "MIT" ]
ama28/game-bytes
Crucible/Assets/Minigames/Perspective/Scripts/ChangeCamera.cs
1,737
C#
using System; namespace NMaier.SimpleDlna.Server { public interface IMediaItem : IComparable<IMediaItem>, IEquatable<IMediaItem>, ITitleComparable { string Id { get; set; } string Path { get; } IHeaders Properties { get; } string Title { get; } } }
17.882353
73
0.611842
[ "BSD-2-Clause" ]
dburner/simpleDLNA
server/Interfaces/IMediaItem.cs
306
C#
using System; using Spring.Web.Conversation; public partial class EndPausedTest : System.Web.UI.Page { private IConversationState convA; public IConversationState ConvA { get { return convA; } set { convA = value; } } private IConversationState convB; public IConversationState ConvB { get { return convB; } set { convB = value; } } protected void Page_Load(object sender, EventArgs e) { if (this.Request["testPhase"] == "begin") { if (!this.convA.Ended && !this.convB.Ended) this.Session["result"] = "OK"; else this.Session["result"] = "(!this.convA.Ended && !this.convB.Ended) is false"; } else if (this.Request["testPhase"] == "startConvA") { this.convA.StartResumeConversation(); if (!this.convA.Ended && this.convB.Ended) this.Session["result"] = "OK"; else this.Session["result"] = "(!this.convA.Ended && this.convB.Ended) is false"; } } }
26.804878
93
0.549591
[ "Apache-2.0" ]
Magicianred/spring-net
test/Spring/Spring.Web.Conversation.NHibernate5.Tests/Data/Spring/Conversation/WebConversationStateTest/EndPausedTest.aspx.cs
1,099
C#
using System; namespace Car { public class StartUp { static void Main(string[] args) { string driver = Console.ReadLine(); Ferrari ferrari = new Ferrari(driver); Console.WriteLine(ferrari); } } }
16
50
0.533088
[ "MIT" ]
ITonev/SoftUni
C#-OOP/Interfaces-And-Abstraction/Exercise/Car/StartUp.cs
274
C#
using System; using System.Windows; using System.Windows.Controls; using Nomad.Regions.Behaviors; namespace Nomad.Regions.Adapters { /// <summary> /// Region adapter for <see cref="TabControl"/> region hosts. /// </summary> /// <remarks> /// <para> /// Regions created using this this adapter are <see cref="SingleActiveViewRegion">SingleActiveViewRegions</see>. /// This allows region to mimic the behavior of <see cref="TabControl"/>, which does not allow multiple tabs to be /// selected. /// </para> /// <para> /// Region's view collection and region host's items collection are synchronized by <see cref="SynchronizeItemsBehavior"/>. /// Region's active views and host's selected item are synchronized using <see cref="SynchronizeActiveItemsBehavior"/>. /// Active views can be notified when they are activated/deactivated if they implement <see cref="IActiveAware"/> interface /// (see <see cref="ActiveAwareBehavior"/>) /// </para> /// </remarks> public class TabControlAdapter : IRegionAdapter { /// <summary>Gets type of control that this adapter can adapt to be region host.</summary> public Type SupportedType { get { return typeof (TabControl); } } /// <summary> /// Creates and attaches new region to <paramref name="regionHost"/> /// </summary> /// <param name="regionHost">Control that will become a region host</param> /// <returns>Created and attached region</returns> /// <exception cref="ArgumentNullException">When <paramref name="regionHost"/> is null</exception> /// <exception cref="InvalidOperationException"> /// When <paramref name="regionHost"/> is of type that is not supported by this adapter /// </exception> public IRegion AdaptView(DependencyObject regionHost) { if (regionHost == null) throw new ArgumentNullException("regionHost"); if (!(regionHost is TabControl)) throw new InvalidOperationException( "This adapter only supports regionHosts that are TabControls"); var tabControl = (TabControl) regionHost; var region = new SingleActiveViewRegion(); new SynchronizeItemsBehavior().Attach(region, tabControl); new SynchronizeActiveItemsBehavior().Attach(region, tabControl); new ActiveAwareBehavior().Attach(region, tabControl); new TabControlHeaderTemplateSelectorBehavior().Attach(region, tabControl); return region; } } }
45.135593
131
0.642884
[ "Unlicense" ]
psla/Nomad
Source/Nomad/Regions/Adapters/TabControlAdapter.cs
2,663
C#
using System; using System.Linq; using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using PureCloudPlatform.Client.V2.Client; namespace PureCloudPlatform.Client.V2.Model { /// <summary> /// RuleSetNotificationRule /// </summary> [DataContract] public partial class RuleSetNotificationRule : IEquatable<RuleSetNotificationRule> { /// <summary> /// Gets or Sets Category /// </summary> [JsonConverter(typeof(UpgradeSdkEnumConverter))] public enum CategoryEnum { /// <summary> /// Your SDK version is out of date and an unknown enum value was encountered. /// Please upgrade the SDK using the command "Upgrade-Package PureCloudApiSdk" /// in the Package Manager Console /// </summary> [EnumMember(Value = "OUTDATED_SDK_VERSION")] OutdatedSdkVersion, /// <summary> /// Enum DialerPrecall for "DIALER_PRECALL" /// </summary> [EnumMember(Value = "DIALER_PRECALL")] DialerPrecall, /// <summary> /// Enum DialerWrapup for "DIALER_WRAPUP" /// </summary> [EnumMember(Value = "DIALER_WRAPUP")] DialerWrapup } /// <summary> /// Gets or Sets Category /// </summary> [DataMember(Name="category", EmitDefaultValue=false)] public CategoryEnum? Category { get; set; } /// <summary> /// Initializes a new instance of the <see cref="RuleSetNotificationRule" /> class. /// </summary> /// <param name="Id">Id.</param> /// <param name="Name">Name.</param> /// <param name="Order">Order.</param> /// <param name="Category">Category.</param> /// <param name="Conditions">Conditions.</param> /// <param name="Actions">Actions.</param> /// <param name="AdditionalProperties">AdditionalProperties.</param> public RuleSetNotificationRule(string Id = null, string Name = null, int? Order = null, CategoryEnum? Category = null, List<RuleSetNotificationConditions> Conditions = null, List<RuleSetNotificationActions> Actions = null, Object AdditionalProperties = null) { this.Id = Id; this.Name = Name; this.Order = Order; this.Category = Category; this.Conditions = Conditions; this.Actions = Actions; this.AdditionalProperties = AdditionalProperties; } /// <summary> /// Gets or Sets Id /// </summary> [DataMember(Name="id", EmitDefaultValue=false)] public string Id { get; set; } /// <summary> /// Gets or Sets Name /// </summary> [DataMember(Name="name", EmitDefaultValue=false)] public string Name { get; set; } /// <summary> /// Gets or Sets Order /// </summary> [DataMember(Name="order", EmitDefaultValue=false)] public int? Order { get; set; } /// <summary> /// Gets or Sets Conditions /// </summary> [DataMember(Name="conditions", EmitDefaultValue=false)] public List<RuleSetNotificationConditions> Conditions { get; set; } /// <summary> /// Gets or Sets Actions /// </summary> [DataMember(Name="actions", EmitDefaultValue=false)] public List<RuleSetNotificationActions> Actions { get; set; } /// <summary> /// Gets or Sets AdditionalProperties /// </summary> [DataMember(Name="additionalProperties", EmitDefaultValue=false)] public Object AdditionalProperties { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class RuleSetNotificationRule {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" Name: ").Append(Name).Append("\n"); sb.Append(" Order: ").Append(Order).Append("\n"); sb.Append(" Category: ").Append(Category).Append("\n"); sb.Append(" Conditions: ").Append(Conditions).Append("\n"); sb.Append(" Actions: ").Append(Actions).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as RuleSetNotificationRule); } /// <summary> /// Returns true if RuleSetNotificationRule instances are equal /// </summary> /// <param name="other">Instance of RuleSetNotificationRule to be compared</param> /// <returns>Boolean</returns> public bool Equals(RuleSetNotificationRule other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return true && ( this.Id == other.Id || this.Id != null && this.Id.Equals(other.Id) ) && ( this.Name == other.Name || this.Name != null && this.Name.Equals(other.Name) ) && ( this.Order == other.Order || this.Order != null && this.Order.Equals(other.Order) ) && ( this.Category == other.Category || this.Category != null && this.Category.Equals(other.Category) ) && ( this.Conditions == other.Conditions || this.Conditions != null && this.Conditions.SequenceEqual(other.Conditions) ) && ( this.Actions == other.Actions || this.Actions != null && this.Actions.SequenceEqual(other.Actions) ) && ( this.AdditionalProperties == other.AdditionalProperties || this.AdditionalProperties != null && this.AdditionalProperties.Equals(other.AdditionalProperties) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.Id != null) hash = hash * 59 + this.Id.GetHashCode(); if (this.Name != null) hash = hash * 59 + this.Name.GetHashCode(); if (this.Order != null) hash = hash * 59 + this.Order.GetHashCode(); if (this.Category != null) hash = hash * 59 + this.Category.GetHashCode(); if (this.Conditions != null) hash = hash * 59 + this.Conditions.GetHashCode(); if (this.Actions != null) hash = hash * 59 + this.Actions.GetHashCode(); if (this.AdditionalProperties != null) hash = hash * 59 + this.AdditionalProperties.GetHashCode(); return hash; } } } }
26.066339
266
0.424357
[ "MIT" ]
maxwang/platform-client-sdk-dotnet
build/src/PureCloudPlatform.Client.V2/Model/RuleSetNotificationRule.cs
10,609
C#
// <copyright file="TJCompressorExtensions.cs" company="Autonomic Systems, Quamotion"> // Copyright (c) Autonomic Systems. All rights reserved. // Copyright (c) Quamotion. All rights reserved. // </copyright> using System; using System.Drawing; using System.Drawing.Imaging; using Validation; namespace TurboJpegWrapper { /// <summary> /// Provides extension methods which allow using <see cref="TJCompressor"/> with <see cref="Image"/> objects. /// </summary> public static class TJCompressorExtensions { /// <summary> /// Compresses input image to the jpeg format with specified quality. /// </summary> /// <param name="compressor"> /// The <see cref="TJCompressor"/> to use. /// </param> /// <param name="srcImage"> Source image to be converted. </param> /// <param name="subSamp"> /// The level of chrominance subsampling to be used when /// generating the JPEG image (see <see cref="TJSubsamplingOption"/> "Chrominance subsampling options".) /// </param> /// <param name="quality">The image quality of the generated JPEG image (1 = worst, 100 = best).</param> /// <param name="flags">The bitwise OR of one or more of the <see cref="TJFlags"/> "flags".</param> /// <returns> /// A <see cref="byte"/> array containing the compressed image. /// </returns> /// <remarks>Only <see cref="PixelFormat.Format24bppRgb"/>, <see cref="PixelFormat.Format32bppArgb"/>, <see cref="PixelFormat.Format8bppIndexed"/> pixel formats are supported.</remarks> /// <exception cref="TJException"> Throws if compress function failed. </exception> /// <exception cref="ObjectDisposedException">Object is disposed and can not be used anymore.</exception> /// <exception cref="NotSupportedException"> /// Some parameters' values are incompatible: /// <list type="bullet"> /// <item><description>Subsampling not equals to <see cref="TJSubsamplingOption.Gray"/> and pixel format <see cref="TJPixelFormat.Gray"/></description></item> /// </list> /// </exception> public static byte[] Compress(this TJCompressor compressor, Bitmap srcImage, TJSubsamplingOption subSamp, int quality, TJFlags flags) { Requires.NotNull(compressor, nameof(compressor)); Verify.NotDisposed(compressor); var pixelFormat = srcImage.PixelFormat; var width = srcImage.Width; var height = srcImage.Height; var srcData = srcImage.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadOnly, pixelFormat); var stride = srcData.Stride; var srcPtr = srcData.Scan0; try { return compressor.Compress(srcPtr, stride, width, height, pixelFormat, subSamp, quality, flags); } finally { srcImage.UnlockBits(srcData); } } /// <summary> /// Compresses input image to the jpeg format with specified quality. /// </summary> /// <param name="compressor"> /// The <see cref="TJCompressor"/> to use. /// </param> /// <param name="srcPtr"> /// Pointer to an image buffer containing RGB, grayscale, or CMYK pixels to be compressed. /// This buffer is not modified. /// </param> /// <param name="stride"> /// Bytes per line in the source image. /// Normally, this should be <c>width * BytesPerPixel</c> if the image is unpadded, /// or <c>TJPAD(width * BytesPerPixel</c> if each line of the image /// is padded to the nearest 32-bit boundary, as is the case for Windows bitmaps. /// You can also be clever and use this parameter to skip lines, etc. /// Setting this parameter to 0 is the equivalent of setting it to /// <c>width * BytesPerPixel</c>. /// </param> /// <param name="width">Width (in pixels) of the source image.</param> /// <param name="height">Height (in pixels) of the source image.</param> /// <param name="pixelFormat">Pixel format of the source image (see <see cref="PixelFormat"/> "Pixel formats").</param> /// <param name="subSamp"> /// The level of chrominance subsampling to be used when /// generating the JPEG image (see <see cref="TJSubsamplingOption"/> "Chrominance subsampling options".) /// </param> /// <param name="quality">The image quality of the generated JPEG image (1 = worst, 100 = best).</param> /// <param name="flags">The bitwise OR of one or more of the <see cref="TJFlags"/> "flags".</param> /// <returns> /// A <see cref="byte"/> array containing the compressed image. /// </returns> /// <exception cref="TJException"> Throws if compress function failed. </exception> /// <exception cref="ObjectDisposedException">Object is disposed and can not be used anymore.</exception> /// <exception cref="NotSupportedException"> /// Some parameters' values are incompatible: /// <list type="bullet"> /// <item><description>Subsampling not equals to <see cref="TJSubsamplingOption.Gray"/> and pixel format <see cref="TJPixelFormat.Gray"/></description></item> /// </list> /// </exception> public static unsafe byte[] Compress(this TJCompressor compressor, IntPtr srcPtr, int stride, int width, int height, PixelFormat pixelFormat, TJSubsamplingOption subSamp, int quality, TJFlags flags) { Requires.NotNull(compressor, nameof(compressor)); Verify.NotDisposed(compressor); return compressor.Compress(srcPtr, stride, width, height, TJDrawingUtils.ConvertPixelFormat(pixelFormat), subSamp, quality, flags); } /// <summary> /// Compresses input image to the jpeg format with specified quality. /// </summary> /// <param name="compressor"> /// The <see cref="TJCompressor"/> to use. /// </param> /// <param name="srcBuf"> /// Image buffer containing RGB, grayscale, or CMYK pixels to be compressed. /// This buffer is not modified. /// </param> /// <param name="stride"> /// Bytes per line in the source image. /// Normally, this should be <c>width * BytesPerPixel</c> if the image is unpadded, /// or <c>TJPAD(width * BytesPerPixel</c> if each line of the image /// is padded to the nearest 32-bit boundary, as is the case for Windows bitmaps. /// You can also be clever and use this parameter to skip lines, etc. /// Setting this parameter to 0 is the equivalent of setting it to /// <c>width * BytesPerPixel</c>. /// </param> /// <param name="width">Width (in pixels) of the source image.</param> /// <param name="height">Height (in pixels) of the source image.</param> /// <param name="pixelFormat">Pixel format of the source image (see <see cref="PixelFormat"/> "Pixel formats").</param> /// <param name="subSamp"> /// The level of chrominance subsampling to be used when /// generating the JPEG image (see <see cref="TJSubsamplingOption"/> "Chrominance subsampling options".) /// </param> /// <param name="quality">The image quality of the generated JPEG image (1 = worst, 100 = best).</param> /// <param name="flags">The bitwise OR of one or more of the <see cref="TJFlags"/> "flags".</param> /// <returns> /// A <see cref="byte"/> array containing the compressed image. /// </returns> /// <exception cref="TJException"> /// Throws if compress function failed. /// </exception> /// <exception cref="ObjectDisposedException">Object is disposed and can not be used anymore.</exception> /// <exception cref="NotSupportedException"> /// Some parameters' values are incompatible: /// <list type="bullet"> /// <item><description>Subsampling not equals to <see cref="TJSubsamplingOption.Gray"/> and pixel format <see cref="TJPixelFormat.Gray"/></description></item> /// </list> /// </exception> public static unsafe byte[] Compress(this TJCompressor compressor, byte[] srcBuf, int stride, int width, int height, PixelFormat pixelFormat, TJSubsamplingOption subSamp, int quality, TJFlags flags) { fixed (byte* srcBufPtr = srcBuf) { return Compress(compressor, (IntPtr)srcBufPtr, stride, width, height, pixelFormat, subSamp, quality, flags); } } /// <summary> /// Compresses input image to the jpeg format with specified quality. /// </summary> /// <param name="compressor"> /// The <see cref="TJCompressor"/> to use. /// </param> /// <param name="srcBuf"> /// Image buffer containing RGB, grayscale, or CMYK pixels to be compressed. /// This buffer is not modified. /// </param> /// <param name="destBuf"> /// A <see cref="byte"/> array containing the compressed image. /// </param> /// <param name="stride"> /// Bytes per line in the source image. /// Normally, this should be <c>width * BytesPerPixel</c> if the image is unpadded, /// or <c>TJPAD(width * BytesPerPixel</c> if each line of the image /// is padded to the nearest 32-bit boundary, as is the case for Windows bitmaps. /// You can also be clever and use this parameter to skip lines, etc. /// Setting this parameter to 0 is the equivalent of setting it to /// <c>width * BytesPerPixel</c>. /// </param> /// <param name="width">Width (in pixels) of the source image.</param> /// <param name="height">Height (in pixels) of the source image.</param> /// <param name="pixelFormat">Pixel format of the source image (see <see cref="PixelFormat"/> "Pixel formats").</param> /// <param name="subSamp"> /// The level of chrominance subsampling to be used when /// generating the JPEG image (see <see cref="TJSubsamplingOption"/> "Chrominance subsampling options".) /// </param> /// <param name="quality">The image quality of the generated JPEG image (1 = worst, 100 = best).</param> /// <param name="flags">The bitwise OR of one or more of the <see cref="TJFlags"/> "flags".</param> /// <returns> /// A <see cref="Span{T}"/> which is a slice of <paramref name="destBuf"/> which holds the compressed image. /// </returns> /// <exception cref="TJException"> /// Throws if compress function failed. /// </exception> /// <exception cref="ObjectDisposedException">Object is disposed and can not be used anymore.</exception> /// <exception cref="NotSupportedException"> /// Some parameters' values are incompatible: /// <list type="bullet"> /// <item><description>Subsampling not equals to <see cref="TJSubsamplingOption.Gray"/> and pixel format <see cref="TJPixelFormat.Gray"/></description></item> /// </list> /// </exception> public static unsafe Span<byte> Compress(this TJCompressor compressor, Span<byte> srcBuf, Span<byte> destBuf, int stride, int width, int height, PixelFormat pixelFormat, TJSubsamplingOption subSamp, int quality, TJFlags flags) { Requires.NotNull(compressor, nameof(compressor)); Verify.NotDisposed(compressor); var tjPixelFormat = TJDrawingUtils.ConvertPixelFormat(pixelFormat); return compressor.Compress(srcBuf, destBuf, stride, width, height, tjPixelFormat, subSamp, quality, flags); } /// <summary> /// Compresses input image to the jpeg format with specified quality. /// </summary> /// <param name="compressor"> /// The <see cref="TJCompressor"/> to use. /// </param> /// <param name="srcBuf"> /// Image buffer containing RGB, grayscale, or CMYK pixels to be compressed. /// This buffer is not modified. /// </param> /// <param name="destBuf"> /// A <see cref="byte"/> array containing the compressed image. /// </param> /// <param name="stride"> /// Bytes per line in the source image. /// Normally, this should be <c>width * BytesPerPixel</c> if the image is unpadded, /// or <c>TJPAD(width * BytesPerPixel</c> if each line of the image /// is padded to the nearest 32-bit boundary, as is the case for Windows bitmaps. /// You can also be clever and use this parameter to skip lines, etc. /// Setting this parameter to 0 is the equivalent of setting it to /// <c>width * BytesPerPixel</c>. /// </param> /// <param name="width">Width (in pixels) of the source image.</param> /// <param name="height">Height (in pixels) of the source image.</param> /// <param name="pixelFormat">Pixel format of the source image (see <see cref="PixelFormat"/> "Pixel formats").</param> /// <param name="subSamp"> /// The level of chrominance subsampling to be used when /// generating the JPEG image (see <see cref="TJSubsamplingOption"/> "Chrominance subsampling options".) /// </param> /// <param name="quality">The image quality of the generated JPEG image (1 = worst, 100 = best).</param> /// <param name="flags">The bitwise OR of one or more of the <see cref="TJFlags"/> "flags".</param> /// <returns> /// The size of the JPEG image (in bytes). /// </returns> /// <exception cref="TJException"> /// Throws if compress function failed. /// </exception> /// <exception cref="ObjectDisposedException">Object is disposed and can not be used anymore.</exception> /// <exception cref="NotSupportedException"> /// Some parameters' values are incompatible: /// <list type="bullet"> /// <item><description>Subsampling not equals to <see cref="TJSubsamplingOption.Gray"/> and pixel format <see cref="TJPixelFormat.Gray"/></description></item> /// </list> /// </exception> public static unsafe int Compress(this TJCompressor compressor, byte[] srcBuf, byte[] destBuf, int stride, int width, int height, PixelFormat pixelFormat, TJSubsamplingOption subSamp, int quality, TJFlags flags) { return Compress(compressor, srcBuf.AsSpan(), destBuf.AsSpan(), stride, width, height, pixelFormat, subSamp, quality, flags).Length; } } }
55.419476
234
0.616409
[ "MIT" ]
quamotion/AS.TurboJpegWrapper
Quamotion.TurboJpegWrapper.Drawing/TJCompressorExtensions.cs
14,799
C#
using Bit0.Utils.Tests.Data.Providers; using Microsoft.AspNetCore.Mvc; namespace Bit0.Utils.Tests.TestSetup { public class Test2Controller : ControllerBase { [HttpGet] public User Action1() { return new User { Username = "user1", Password = "user1" }; } } }
20.555556
49
0.524324
[ "MIT" ]
0b00/Bit0.Utils
tests/Tests/TestSetup/Test2Controller.cs
370
C#
using System; using System.Collections.Generic; using System.Globalization; using System.Text; using ORMMap.VectorTile.Contants; namespace ORMMap.VectorTile { //TODO: implement DataView using the same byte array instead of copying byte arrays //public struct DataView { // public ulong start; // public ulong end; //} /// <summary> /// Low level protobuf (PBF) decoder https://developers.google.com/protocol-buffers/docs/overview /// </summary> public class PbfReader { private readonly byte[] _buffer; private readonly ulong _length; private ulong _pos; /// <summary> /// PbfReader constructor /// </summary> /// <param name="tileBuffer">Byte array containing the raw (already unzipped) tile data</param> public PbfReader(byte[] tileBuffer) { _buffer = tileBuffer; _length = (ulong) _buffer.Length; WireType = WireTypes.UNDEFINED; } /// <summary>Tag at current position</summary> public int Tag { get; private set; } /// <summary>Value at current position</summary> public ulong Value { get; private set; } //public ulong Pos { get; private set; } /// <summary>Wire type at current position</summary> public WireTypes WireType { get; private set; } /// <summary> /// <para>Gets Varint at current position, moves to position after Varint.</para> /// <para>Throws exception if Varint cannot be decoded</para> /// </summary> /// <returns>Decoded Varint</returns> public long Varint() { // convert to base 128 varint // https://developers.google.com/protocol-buffers/docs/encoding int shift = 0; long result = 0; while (shift < 64) { byte b = _buffer[_pos]; result |= (long) (b & 0x7F) << shift; _pos++; if ((b & 0x80) == 0) { return result; } shift += 7; } throw new ArgumentException("Invalid varint"); } /// <summary> /// <para>Get a view into the buffer.</para> /// <para>TODO: refactor to return a DataView instead of a byte array</para> /// </summary> /// <returns>Byte array containing the view</returns> public byte[] View() { // return layer/feature subsections of the main stream if (Tag == 0) { throw new Exception("call next() before accessing field value"); } ; if (WireType != WireTypes.BYTES) { throw new Exception("not of type string, bytes or message"); } ulong skipBytes = (ulong) Varint(); SkipBytes(skipBytes); var buf = new byte[skipBytes]; Array.Copy(_buffer, (int) _pos - (int) skipBytes, buf, 0, (int) skipBytes); return buf; } /// <summary> /// Get repeated `uint`s a current position, move position /// </summary> /// <returns>List of decoded `uint`s</returns> public List<uint> GetPackedUnit32() { var values = new List<uint>(200); ulong sizeInByte = (ulong) Varint(); ulong end = _pos + sizeInByte; while (_pos < end) { values.Add((uint) Varint()); } return values; } public List<int> GetPackedSInt32() { var values = new List<int>(200); ulong sizeInByte = (ulong) Varint(); ulong end = _pos + sizeInByte; while (_pos < end) { values.Add(decodeZigZag32((int) Varint())); } return values; } public List<long> GetPackedSInt64() { var values = new List<long>(200); ulong sizeInByte = (ulong) Varint(); ulong end = _pos + sizeInByte; while (_pos < end) { values.Add(decodeZigZag64(Varint())); } return values; } private int decodeZigZag32(int value) { return (value >> 1) ^ -(value & 1); } private long decodeZigZag64(long value) { return (value >> 1) ^ -(value & 1); } /// <summary> /// Get double at current position, move to next position /// </summary> /// <returns>Decoded double</returns> public double GetDouble() { var buf = new byte[8]; Array.Copy(_buffer, (int) _pos, buf, 0, 8); _pos += 8; double dblVal = BitConverter.ToDouble(buf, 0); return dblVal; } /// <summary> /// Get float a current position, move to next position /// </summary> /// <returns>Decoded float</returns> public float GetFloat() { var buf = new byte[4]; Array.Copy(_buffer, (int) _pos, buf, 0, 4); _pos += 4; float snglVal = BitConverter.ToSingle(buf, 0); return snglVal; } /// <summary> /// Get bytes as string /// </summary> /// <param name="length">Number of bytes to read</param> /// <returns>Decoded string</returns> public string GetString(ulong length) { var buf = new byte[length]; Array.Copy(_buffer, (int) _pos, buf, 0, (int) length); _pos += length; return Encoding.UTF8.GetString(buf, 0, buf.Length); } /// <summary> /// Move to next byte and set wire type. Throws exeception if tag is out of range /// </summary> /// <returns>Returns false if at end of buffer</returns> public bool NextByte() { if (_pos >= _length) { return false; } // get and process the next byte in the buffer // return true until end of stream Value = (ulong) Varint(); Tag = (int) Value >> 3; if ( (Tag == 0 || Tag >= 19000) && (Tag > 19999 || Tag <= (1 << 29) - 1) ) { throw new Exception("tag out of range"); } WireType = (WireTypes) (Value & 0x07); return true; } /// <summary> /// Skip over a Varint /// </summary> public void SkipVarint() { Varint(); //while (0 == (_buffer[Pos] & 0x80)) //{ // Pos++; // if (Pos >= _length) // { // throw new Exception("Truncated message."); // } //} //if (Pos > _length) //{ // throw new Exception("Truncated message."); //} } /// <summary> /// Skip bytes /// </summary> /// <param name="skip">Number of bytes to skip</param> public void SkipBytes(ulong skip) { if (_pos + skip > _length) { string msg = string.Format(NumberFormatInfo.InvariantInfo, "[SkipBytes()] skip:{0} pos:{1} len:{2}", skip, _pos, _length); throw new Exception(msg); } _pos += skip; } /// <summary> /// Automatically skip bytes based on wire type /// </summary> /// <returns>New position within the byte array</returns> public ulong Skip() { if (Tag == 0) { throw new Exception("call next() before calling skip()"); } switch (WireType) { case WireTypes.VARINT: SkipVarint(); break; case WireTypes.BYTES: SkipBytes((ulong) Varint()); break; case WireTypes.FIXED32: SkipBytes(4); break; case WireTypes.FIXED64: SkipBytes(8); break; case WireTypes.UNDEFINED: throw new Exception("undefined wire type"); default: throw new Exception("unknown wire type"); } return _pos; } } }
21.987013
110
0.606468
[ "MIT" ]
emptycoder/ORMMapViewer
src/PbfReader/PbfReader.cs
6,774
C#
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // <auto-generated/> // Template Source: EnumType.cs.tt namespace Microsoft.Graph { using System; using Newtonsoft.Json; /// <summary> /// The enum AndroidProfileApplicability. /// </summary> [JsonConverter(typeof(EnumConverter))] public enum AndroidProfileApplicability { /// <summary> /// Default /// </summary> Default = 0, /// <summary> /// Android Work Profile /// </summary> AndroidWorkProfile = 1, /// <summary> /// Android Device Owner /// </summary> AndroidDeviceOwner = 2, } }
25.9
153
0.502896
[ "MIT" ]
GeertVL/msgraph-beta-sdk-dotnet
src/Microsoft.Graph/Generated/model/AndroidProfileApplicability.cs
1,036
C#
#if HE_SYSCORE using HeathenEngineering.Serializable; using UnityEngine; namespace HeathenEngineering { [CreateAssetMenu(menuName = "System Core/Variables/Serializable/Lists/RectTransform")] public class RectTransformListVariable : CollectionDataVariable<SerializableRectTransform> { } } #endif
28
94
0.811688
[ "MIT" ]
heathen-engineering/Heathen-s-System-Core
com.heathen.systemcore/Runtime/Variables/Data Types/Transform/RectTransformListVariable.cs
310
C#
namespace Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210 { using Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.PowerShell; /// <summary>Input for test migrate.</summary> [System.ComponentModel.TypeConverter(typeof(TestMigrateInputTypeConverter))] public partial class TestMigrateInput { /// <summary> /// <c>AfterDeserializeDictionary</c> will be called after the deserialization has finished, allowing customization of the /// object before it is returned. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); /// <summary> /// <c>AfterDeserializePSObject</c> will be called after the deserialization has finished, allowing customization of the object /// before it is returned. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); /// <summary> /// <c>BeforeDeserializeDictionary</c> will be called before the deserialization has commenced, allowing complete customization /// of the object before it is deserialized. /// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter. /// Implement this method in a partial class to enable this behavior. /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> /// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return /// instantly.</param> partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); /// <summary> /// <c>BeforeDeserializePSObject</c> will be called before the deserialization has commenced, allowing complete customization /// of the object before it is deserialized. /// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter. /// Implement this method in a partial class to enable this behavior. /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> /// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return /// instantly.</param> partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); /// <summary> /// Deserializes a <see cref="global::System.Collections.IDictionary" /> into an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.TestMigrateInput" /// />. /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> /// <returns> /// an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.ITestMigrateInput" />. /// </returns> public static Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.ITestMigrateInput DeserializeFromDictionary(global::System.Collections.IDictionary content) { return new TestMigrateInput(content); } /// <summary> /// Deserializes a <see cref="global::System.Management.Automation.PSObject" /> into an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.TestMigrateInput" /// />. /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> /// <returns> /// an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.ITestMigrateInput" />. /// </returns> public static Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.ITestMigrateInput DeserializeFromPSObject(global::System.Management.Automation.PSObject content) { return new TestMigrateInput(content); } /// <summary> /// Creates a new instance of <see cref="TestMigrateInput" />, deserializing the content from a json string. /// </summary> /// <param name="jsonText">a string containing a JSON serialized instance of this model.</param> /// <returns>an instance of the <see cref="className" /> model class.</returns> public static Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.ITestMigrateInput FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonNode.Parse(jsonText)); /// <summary> /// Deserializes a <see cref="global::System.Collections.IDictionary" /> into a new instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.TestMigrateInput" /// />. /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> internal TestMigrateInput(global::System.Collections.IDictionary content) { bool returnNow = false; BeforeDeserializeDictionary(content, ref returnNow); if (returnNow) { return; } // actually deserialize ((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.ITestMigrateInputInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.ITestMigrateInputProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.ITestMigrateInputInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.TestMigrateInputPropertiesTypeConverter.ConvertFrom); ((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.ITestMigrateInputInternal)this).ProviderSpecificDetail = (Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.ITestMigrateProviderSpecificInput) content.GetValueForProperty("ProviderSpecificDetail",((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.ITestMigrateInputInternal)this).ProviderSpecificDetail, Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.TestMigrateProviderSpecificInputTypeConverter.ConvertFrom); AfterDeserializeDictionary(content); } /// <summary> /// Deserializes a <see cref="global::System.Management.Automation.PSObject" /> into a new instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.TestMigrateInput" /// />. /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> internal TestMigrateInput(global::System.Management.Automation.PSObject content) { bool returnNow = false; BeforeDeserializePSObject(content, ref returnNow); if (returnNow) { return; } // actually deserialize ((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.ITestMigrateInputInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.ITestMigrateInputProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.ITestMigrateInputInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.TestMigrateInputPropertiesTypeConverter.ConvertFrom); ((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.ITestMigrateInputInternal)this).ProviderSpecificDetail = (Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.ITestMigrateProviderSpecificInput) content.GetValueForProperty("ProviderSpecificDetail",((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.ITestMigrateInputInternal)this).ProviderSpecificDetail, Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.TestMigrateProviderSpecificInputTypeConverter.ConvertFrom); AfterDeserializePSObject(content); } /// <summary>Serializes this instance to a json string.</summary> /// <returns>a <see cref="System.String" /> containing this model serialized to JSON text.</returns> public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.SerializationMode.IncludeAll)?.ToString(); } /// Input for test migrate. [System.ComponentModel.TypeConverter(typeof(TestMigrateInputTypeConverter))] public partial interface ITestMigrateInput { } }
70.180451
526
0.710842
[ "MIT" ]
AverageDesigner/azure-powershell
src/Migrate/generated/api/Models/Api20210210/TestMigrateInput.PowerShell.cs
9,202
C#
using MappingSPO.Entities; namespace MappingSPO { public class CalcCode7EntityConfiguration : System.Data.Entity.ModelConfiguration.EntityTypeConfiguration<CalcCode7Entity> { public CalcCode7EntityConfiguration() : this("Project") { } public CalcCode7EntityConfiguration(string schema) { ToTable("tCalcCode7", schema); HasKey(x => x.CalcCodeId); Property(x => x.CalcCodeId).HasColumnName(@"CalcCodeID").HasColumnType("int").IsRequired().HasDatabaseGeneratedOption(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity); Property(x => x.CalcCode).HasColumnName(@"CalcCode").HasColumnType("nvarchar").IsOptional().HasMaxLength(255); Property(x => x.CalcDisabled).HasColumnName(@"CalcDisabled").HasColumnType("bit").IsRequired(); Property(x => x.Domain).HasColumnName(@"Domain").HasColumnType("nchar").IsRequired().IsFixedLength().HasMaxLength(1); } } }
42.583333
209
0.683953
[ "MIT" ]
hmohcine/MappingSPO
MappingSPO/Configurations/CalcCode7EntityConfiguration.cs
1,022
C#
// ***************************************************************************** // BSD 3-Clause License (https://github.com/ComponentFactory/Krypton/blob/master/LICENSE) // © Component Factory Pty Ltd, 2006-2019, All rights reserved. // The software and associated documentation supplied hereunder are the // proprietary information of Component Factory Pty Ltd, 13 Swallows Close, // Mornington, Vic 3931, Australia and are supplied subject to licence terms. // // Modifications by Peter Wagner(aka Wagnerp) & Simon Coghlan(aka Smurf-IV) 2017 - 2019. All rights reserved. (https://github.com/Wagnerp/Krypton-NET-5.472) // Version 5.472.0.0 www.ComponentFactory.com // ***************************************************************************** using System; using System.Drawing; using System.Drawing.Drawing2D; namespace ComponentFactory.Krypton.Toolkit { /// <summary> /// Restrict graphics clipping using the provided path/region instance. /// </summary> public class Clipping : GlobalId, IDisposable { #region Instance Fields private readonly Graphics _graphics; private readonly Region _previousRegion; private Region _newRegion; #endregion #region Identity /// <summary> /// Initialize a new instance of the Clipping class. /// </summary> /// <param name="graphics">Graphics context.</param> /// <param name="path">Path to clip.</param> public Clipping(Graphics graphics, GraphicsPath path) : this(graphics, path, false) { } /// <summary> /// Initialize a new instance of the Clipping class. /// </summary> /// <param name="graphics">Graphics context.</param> /// <param name="path">Path to clip.</param> /// <param name="exclude">Exclude path from clipping.</param> public Clipping(Graphics graphics, GraphicsPath path, bool exclude) { // Cache graphics instance _graphics = graphics; // Save the existing clipping region _previousRegion = _graphics.Clip; // Add clipping of path to existing clipping region _newRegion = _previousRegion.Clone(); if (exclude) { _newRegion.Exclude(path); } else { _newRegion.Intersect(path); } _graphics.Clip = _newRegion; } /// <summary> /// Initialize a new instance of the Clipping class. /// </summary> /// <param name="graphics">Graphics context.</param> /// <param name="region">Clipping region.</param> public Clipping(Graphics graphics, Region region) : this(graphics, region, false) { } /// <summary> /// Initialize a new instance of the Clipping class. /// </summary> /// <param name="graphics">Graphics context.</param> /// <param name="region">Clipping region.</param> /// <param name="exclude">Exclude region from clipping.</param> public Clipping(Graphics graphics, Region region, bool exclude) { // Cache graphics instance _graphics = graphics; // Save the existing clipping region _previousRegion = _graphics.Clip; // Add clipping of region to existing clipping region _newRegion = _previousRegion.Clone(); if (exclude) { _newRegion.Exclude(region); } else { _newRegion.Intersect(region); } _graphics.Clip = _newRegion; } /// <summary> /// Initialize a new instance of the Clipping class. /// </summary> /// <param name="graphics">Graphics context.</param> /// <param name="rect">Clipping rectangle.</param> public Clipping(Graphics graphics, Rectangle rect) : this(graphics, rect, false) { } /// <summary> /// Initialize a new instance of the Clipping class. /// </summary> /// <param name="graphics">Graphics context.</param> /// <param name="rect">Clipping rectangle.</param> /// <param name="exclude">Exclude rectangle from clipping.</param> public Clipping(Graphics graphics, Rectangle rect, bool exclude) { // Cache graphics instance _graphics = graphics; // Save the existing clipping region _previousRegion = _graphics.Clip; // Add clipping of rectangle to existing clipping region _newRegion = _previousRegion.Clone(); if (exclude) { _newRegion.Exclude(rect); } else { _newRegion.Intersect(rect); } _graphics.Clip = _newRegion; } /// <summary> /// Reverse the smoothing mode change. /// </summary> public void Dispose() { if (_graphics != null) { try { // Restore the original clipping region _graphics.Clip = _previousRegion; } catch { } } if (_newRegion != null) { try { // Dispose of created resources _newRegion.Dispose(); _newRegion = null; } catch { } } } #endregion } }
31.179775
157
0.542703
[ "BSD-3-Clause" ]
anuprakash/Krypton-NET-5.472
Source/Krypton Components/ComponentFactory.Krypton.Toolkit/General/Clipping.cs
5,553
C#
using System.Collections.Generic; using System.Linq; using Agridea.Prototypes.Akka.Common.Messages; using Akka.Actor; using Akka.Util.Internal; namespace Agridea.Prototypes.Akka.Common { public class SupervisorActorV2 : ReceiveActor { private readonly IActorRef worker_ = Context.ActorOf(Props.Create(() => new JobActor(Context.Self, new DoNothingJobFactory()))); //private readonly IActorRef worker_ = Context.ActorOf(Props.Create(() => new JobActor(Context.Self, new AgisJobFactory()))); private readonly Dictionary<string, IActorRef> consumers_ = new Dictionary<string, IActorRef>(); private readonly Dictionary<string, JobSummary> jobs_ = new Dictionary<string, JobSummary>(); #region Messages public class Hello { public string Id { get; } public Hello(string id) { Id = id; } } public class Bye { public string Id { get; } public Bye(string id) { Id = id; } } #endregion /// <summary> /// The supervisor actor talks with signalR actor. It maintains a list of consumers, and then signalr as one of /// these consumer registers himself to supervisor it (supervisor.Tell("hello I am signalr")). It then tells all consumers /// about jobs progress. Signalr can also unregister, by telling supervisor, who removes him from his list of consumers. /// SignalR actor must know about supervisor when he gets created. /// </summary> public SupervisorActorV2() { #region Commands Receive<Hello>(hello => { if (!consumers_.ContainsKey(hello.Id)) consumers_.Add(hello.Id, Sender); Sender.Tell(new RegistrationSuccessful()); }); Receive<Bye>(bye => { if (consumers_.ContainsKey(bye.Id)) consumers_.Remove(bye.Id); }); Receive<string>(s => { switch (s) { case "start": worker_.Tell(new Run()); break; case "purge": PurgeFinishedJobs(); Sender.Tell("purged"); break; case "getjobs": Sender.Tell(jobs_.Values.ToList()); break; } }); Receive<Cancel>(cancel => worker_.Tell(cancel)); Receive<Pause>(pause => worker_.Tell(pause)); Receive<Resume>(resume => worker_.Tell(resume)); Receive<GetResult>(getResult => worker_.Tell(getResult)); #endregion #region Feedback Receive<Started>(started => { var job = new JobSummary { Name = started.Name, Percent = 0, Status = JobStatus.Running }; jobs_.Add(job.Name, job); consumers_.ForEach(c => c.Value.Tell(job)); }); Receive<Progress>(progress => { JobSummary job; jobs_.TryGetValue(progress.Name, out job); if (job != null) { job.Percent = progress.Percent; consumers_.ForEach(c => c.Value.Tell(job)); } }); Receive<Finished>(finished => { consumers_.ForEach(c => c.Value.Tell(finished)); }); Receive<StatusChanged>(statusChanged => { JobSummary job; jobs_.TryGetValue(statusChanged.Name, out job); if (job != null) { job.Status = statusChanged.Status; consumers_.ForEach(c => c.Value.Tell(statusChanged)); } }); Receive<Result>(result => { IActorRef consumer; consumers_.TryGetValue(result.ConsumerId, out consumer); consumer?.Tell(result); }); #endregion } private void PurgeFinishedJobs() { var keysToRemove = jobs_.Where(j => j.Value.Status == JobStatus.Completed).Select(j => j.Key).ToList(); keysToRemove.ForEach(key => jobs_.Remove(key)); } } public class JobSummary { public string Name { get; set; } public int Percent { get; set; } public JobStatus Status { get; set; } } }
32.231293
136
0.500211
[ "MIT" ]
ni11c/AkkaJobs
Common/Actors/SupervisorActorV2.cs
4,740
C#
using HotChocolate.Types; using Order.API.Models; namespace Order.API.GraphQL.SchemaTypes { public class LineItemType : ObjectType<LineItem> { protected override void Configure(IObjectTypeDescriptor<LineItem> descriptor) { descriptor.Name("LineItem"); descriptor.Field(x => x.Id).Type<NonNullType<IdType>>(); descriptor.Field(x => x.SKU).Name("sku").Type<NonNullType<StringType>>(); descriptor.Field(x => x.Quantity).Type<NonNullType<IntType>>(); } } }
33.5625
85
0.646182
[ "MIT" ]
royarin/Demos
2021/BLDTalk/GraphQL/GraphQLServer/Order.API/GraphQL/SchemaTypes/LineItemType.cs
537
C#
using System; using System.ComponentModel; namespace StackExchange.Redis { /// <summary> /// The class of the connection /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1069:Enums values should not be duplicated", Justification = "Compatibility")] public enum ClientType { /// <summary> /// Regular connections, including MONITOR connections /// </summary> Normal = 0, /// <summary> /// Replication connections /// </summary> Replica = 1, // as an implementation detail, note that enum.ToString without [Flags] prefers *earlier* values /// <summary> /// Replication connections /// </summary> [Obsolete("Starting with Redis version 5, Redis has moved to 'replica' terminology. Please use " + nameof(Replica) + " instead, this will be removed in 3.0.")] [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] Slave = 1, /// <summary> /// Subscription connections /// </summary> PubSub = 2, } }
34.53125
167
0.611765
[ "Apache-2.0" ]
NicoAvanzDev/StackExchange.Redis
src/StackExchange.Redis/Enums/ClientType.cs
1,107
C#
namespace StreamRC.Streaming.Text.Images { internal struct PixelData32 { public PixelData32(byte alpha, byte red, byte green, byte blue) { this.blue = blue; this.green = green; this.red = red; this.alpha = alpha; } public byte blue; public byte green; public byte red; public byte alpha; } }
21.578947
71
0.531707
[ "Unlicense" ]
telmengedar/StreamRC
Streaming/Text/Images/PixelData32.cs
412
C#
/* * Copyright 2018 JDCLOUD.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. * * Domain * 域名配置相关接口 * * OpenAPI spec version: v1 * Contact: * * NOTE: This class is auto generated by the jdcloud code generator program. */ using JDCloudSDK.Core.Client; using JDCloudSDK.Core.Http; using System; using System.Collections.Generic; using System.Text; namespace JDCloudSDK.Vod.Client { /// <summary> /// 设置CDN域名SSL配置 /// </summary> public class SetHttpSslExecutor : JdcloudExecutor { /// <summary> /// 设置CDN域名SSL配置接口的Http 请求方法 /// </summary> public override string Method { get { return "POST"; } } /// <summary> /// 设置CDN域名SSL配置接口的Http资源请求路径 /// </summary> public override string Url { get { return "/domains/{domainId}:setHttpSsl"; } } } }
24.35
76
0.624914
[ "Apache-2.0" ]
jdcloud-api/jdcloud-sdk-net
sdk/src/Service/Vod/Client/SetHttpSslExecutor.cs
1,545
C#
using System; using System.Xml.Serialization; namespace SAML2.Schema.Protocol { /// <summary> /// The <c>&lt;AuthnQuery&gt;</c> message element is used to make the query "What assertions containing /// authentication statements are available for this subject?" A successful <c>&lt;Response&gt;</c> will contain one or /// more assertions containing authentication statements. /// </summary> [Serializable] [XmlType(Namespace = Saml20Constants.Protocol)] [XmlRoot(ElementName, Namespace = Saml20Constants.Protocol, IsNullable = false)] public class AuthnQuery : SubjectQueryAbstract { /// <summary> /// The XML Element name of this class /// </summary> public new const string ElementName = "AuthnQuery"; #region Attributes /// <summary> /// Gets or sets the index of the session. /// If present, specifies a filter for possible responses. Such a query asks the question "What assertions /// containing authentication statements do you have for this subject within the context of the supplied /// session information?" /// </summary> /// <value>The index of the session.</value> [XmlAttribute] public string SessionIndex { get; set; } #endregion #region Elements /// <summary> /// Gets or sets the requested authentication context. /// If present, specifies a filter for possible responses. Such a query asks the question "What assertions /// containing authentication statements do you have for this subject that satisfy the authentication /// context requirements in this element?" /// </summary> /// <value>The requested authentication context.</value> [XmlElement("RequestedAuthnContext", Order = 1)] public RequestedAuthnContext RequestedAuthnContext { get; set; } #endregion } }
38.86
123
0.658775
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
Codersson/SAML2
src/SAML2.Core/Schema/Protocol/AuthnQuery.cs
1,943
C#
using System.Collections.Generic; using DuckGame; using JetBrains.Annotations; using TMGmod.Core; using TMGmod.Core.WClasses; namespace TMGmod { [EditorGroup("TMG|Sniper|Semi-Automatic")] public class M50 : BaseGun, ISpeedAccuracy, IAmSr, IHaveSkin, IHaveBipods { private readonly SpriteMap _sprite; private const int NonSkinFrames = 1; public StateBinding FrameIdBinding { get; } = new StateBinding(nameof(FrameId)); [UsedImplicitly] // ReSharper disable once InconsistentNaming private readonly EditorProperty<int> skin; // ReSharper disable once ConvertToAutoProperty public EditorProperty<int> Skin => skin; private static readonly List<int> Allowedlst = new List<int>(new[] { 0 }); public M50(float xval, float yval) : base(xval, yval) { skin = new EditorProperty<int>(0, this, -1f, 9f, 0.5f); ammo = 7; _ammoType = new Cal50Explode { range = 1100f, accuracy = 1f, penetration = 1f, bulletThickness = 2.5f }; _type = "gun"; _sprite = new SpriteMap(GetPath("M50"), 40, 13); _graphic = _sprite; _sprite.frame = 0; _center = new Vec2(20f, 7f); _collisionOffset = new Vec2(-20f, -7f); _collisionSize = new Vec2(40f, 13f); _barrelOffsetTL = new Vec2(40f, 5f); _flare = new SpriteMap(GetPath("FlareOnePixel3"), 13, 10) { center = new Vec2(0.0f, 5f) }; _fireSound = GetPath("sounds/HeavySniper.wav"); _fullAuto = false; _fireWait = 3.75f; _kickForce = 8f; loseAccuracy = 0.1f; maxAccuracyLost = 0.3f; _holdOffset = new Vec2(6f, -1f); ShellOffset = new Vec2(0f, 0f); laserSight = true; _laserOffsetTL = new Vec2(31f, 9f); _editorName = "M50"; _weight = 6.75f; MuAccuracySr = 1f; LambdaAccuracySr = 0.67f; } public override void Update() { base.Update(); Bipods = Bipods; } public bool Bipods { get => HandleQ(); set { _kickForce = value ? 1f : 8f; loseAccuracy = value ? 0f : 0.1f; maxAccuracyLost = value ? 0f : 0.3f; LambdaAccuracySr = value ? 0f : 0.5f; } } [UsedImplicitly] public BitBuffer BipodsBuffer { get { var b = new BitBuffer(); b.Write(Bipods); return b; } set => Bipods = value.ReadBool(); } public StateBinding BipodsBinding { get; } = new StateBinding(nameof(BipodsBuffer)); public bool BipodsDisabled => false; public float MuAccuracySr { get; } public float LambdaAccuracySr { get; private set; } private void UpdateSkin() { var bublic = Skin.value; while (!Allowedlst.Contains(bublic)) { bublic = Rando.Int(0, 9); } _sprite.frame = bublic; } [UsedImplicitly] public int FrameId { get => _sprite.frame; set => _sprite.frame = value % (10 * NonSkinFrames); } public override void EditorPropertyChanged(object property) { UpdateSkin(); base.EditorPropertyChanged(property); } } }
32.234783
92
0.510925
[ "BSD-3-Clause" ]
OnGoTeam/TMGmod
build/src/M50.cs
3,709
C#
/* * OpenAPI Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git */ using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using System.ComponentModel.DataAnnotations; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; namespace Org.OpenAPITools.Model { /// <summary> /// HasOnlyReadOnly /// </summary> [DataContract(Name = "hasOnlyReadOnly")] public partial class HasOnlyReadOnly : IEquatable<HasOnlyReadOnly>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="HasOnlyReadOnly" /> class. /// </summary> [JsonConstructorAttribute] public HasOnlyReadOnly() { } /// <summary> /// Gets or Sets Bar /// </summary> [DataMember(Name = "bar", EmitDefaultValue = false)] public string Bar { get; private set; } /// <summary> /// Returns false as Bar should not be serialized given that it's read-only. /// </summary> /// <returns>false (boolean)</returns> public bool ShouldSerializeBar() { return false; } /// <summary> /// Gets or Sets Foo /// </summary> [DataMember(Name = "foo", EmitDefaultValue = false)] public string Foo { get; private set; } /// <summary> /// Returns false as Foo should not be serialized given that it's read-only. /// </summary> /// <returns>false (boolean)</returns> public bool ShouldSerializeFoo() { return false; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("class HasOnlyReadOnly {\n"); sb.Append(" Bar: ").Append(Bar).Append("\n"); sb.Append(" Foo: ").Append(Foo).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public virtual string ToJson() { return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return OpenAPIClientUtils.compareLogic.Compare(this, input as HasOnlyReadOnly).AreEqual; } /// <summary> /// Returns true if HasOnlyReadOnly instances are equal /// </summary> /// <param name="input">Instance of HasOnlyReadOnly to be compared</param> /// <returns>Boolean</returns> public bool Equals(HasOnlyReadOnly input) { return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.Bar != null) { hashCode = (hashCode * 59) + this.Bar.GetHashCode(); } if (this.Foo != null) { hashCode = (hashCode * 59) + this.Foo.GetHashCode(); } return hashCode; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> public IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> Validate(ValidationContext validationContext) { yield break; } } }
32.727891
159
0.582207
[ "Apache-2.0" ]
0x0c/openapi-generator
samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/HasOnlyReadOnly.cs
4,811
C#
#pragma checksum "E:\Code\My-UWP-Tutorial-Code\Make-New-App\Make-New-App\App.xaml" "{406ea660-64cf-4c82-b6f0-42d48172a799}" "F8A9C47BC51B8345CF5C14D228034845" //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Make_New_App { partial class App : global::Windows.UI.Xaml.Application { } }
34.333333
159
0.522654
[ "MIT" ]
Baka632/Learning-UWP
My-UWP-Tutorial-Code/Make-New-App/Make-New-App/obj/x86/Debug/App.g.cs
620
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using MarketMvc.Entities; namespace MarketMvc.Models { public class HomeIndexViewModel { public int VisitorCount; public IList<Category> Categories { get; set; } public IList<Product> Products { get; set; } } }
21.625
55
0.702312
[ "MIT" ]
sammysoftware/market
MarketMvc/MarketMvc/Models/HomeIndexViewModel.cs
348
C#
using NBomber; using NBomber.CSharp; using Serilog; using TestConsole.Constants; using TestConsole.Steps; namespace TestConsole; public static class AirplaneLoad { public static void Start() { var httpFactory = ClientFactory.Create( name: "factory", clientCount: 10, initClient: (number, context) => Task.FromResult(new HttpClient())); var airplane = Step.Create(StepName.PostAirplane, timeout: TimeSpan.FromSeconds(5), clientFactory: httpFactory, execute: async context => await PostAirplaneStep.PostAirplane(context)); var scenario = ScenarioBuilder.CreateScenario("airplane", airplane); NBomberRunner .RegisterScenarios(scenario) .WithTestName("Airplane") .WithTestSuite("Airplane") .WithLoggerConfig(() => new LoggerConfiguration() .Enrich.FromLogContext() .MinimumLevel.Information() .WriteTo.Seq("http://localhost:5341") ) .Run(); } }
32.757576
193
0.612396
[ "Apache-2.0" ]
jokk-itu/BookVacation
TestConsole/Tests/AirplaneLoad.cs
1,081
C#
 namespace CompareArrays { enum ComparisonState { First, Second, Equal } }
10.181818
24
0.508929
[ "MIT" ]
VProfirov/Telerik-Academy
Module 1/[02] CSharp Advanced/[performance improvement versions] C# Advanced/C# Advanced v0.1/Arrays/CompareArrays/ComparisonState.cs
114
C#
using System; namespace JPPhotoManager.Domain { public class Folder { public string FolderId { get; set; } public string Path { get; set; } public string ThumbnailsFilename => FolderId + ".bin"; public string Name { get { string[] pathParts = this.Path.Split(new char[] { '\\' }, StringSplitOptions.RemoveEmptyEntries); string result = pathParts[pathParts.Length - 1]; return result; } } // TODO: Remove storageService parameter. public bool IsParentOf(Folder otherFolder, IStorageService storageService) { bool result; string[] thisPathDirectories = this.Path.Split(System.IO.Path.DirectorySeparatorChar); string[] otherPathDirectories = otherFolder.Path.Split(System.IO.Path.DirectorySeparatorChar); result = (thisPathDirectories != null && otherPathDirectories != null && thisPathDirectories.Length == (otherPathDirectories.Length - 1)); if (result) { for (int i = 0; i < thisPathDirectories.Length; i++) { if (string.Compare(thisPathDirectories[i], otherPathDirectories[i], StringComparison.OrdinalIgnoreCase) != 0) { result = false; break; } } } return result; } public override bool Equals(object obj) { Folder folder = obj as Folder; return folder != null && folder.Path == this.Path; } public override int GetHashCode() { return this.Path != null ? this.Path.GetHashCode() : base.GetHashCode(); } public override string ToString() { return this.Path; } } }
29.666667
129
0.522983
[ "MIT" ]
jpablodrexler/jp-photo-manager
JPPhotoManager/JPPhotoManager.Domain/Folder.cs
1,960
C#
using System.Collections.Generic; using System.Collections.ObjectModel; using EventStore.ClientAPI; using SiaConsulting.EO.Abstractions; namespace SiaConsulting.EO { public class HandleNotifications { public static IEnumerable<ICommand> Handle(INotification notification, ReadOnlyCollection<ResolvedEvent> eventStream, Microsoft.Extensions.Logging.ILogger log) { var pumps = EoRegistry.GetNotificationPumps(notification); foreach(var pump in pumps) { var notificationPump = pump; var context = CommonUtils.LoadContext(notification, notificationPump.ContextLoader, eventStream, log); foreach(var result in Process(notification, context, (INotificationProcessor)notificationPump.Processor, log)) { yield return result; } } } private static IEnumerable<ICommand> Process(INotification notification, IContext context, INotificationProcessor processor, Microsoft.Extensions.Logging.ILogger log) { return processor.Process(notification, context); } } }
40.413793
175
0.674915
[ "MIT" ]
dersia/eo
src/EoAppFramework/Handler/HandleNotifications.cs
1,172
C#
using System; using System.IO; using System.Text; using LibroLib.WebUtils.Ftp; using NUnit.Framework; using Rhino.Mocks; namespace LibroLib.Tests.WebUtilsTests.FtpTests { public class FtpCommunicatorTests { [Test] public void ReadSingleLineResponse() { StubChannelResponse("200 bla\r\n"); comm.AttachToChannel(channel); FtpServerResponse response = comm.ReadResponse(); Assert.AreEqual((int)FtpReturnCode.CommandOk, response.ReturnCode); Assert.AreEqual("bla", response.Message); } [Test] public void ReadMultiLineResponse() { StubChannelResponse("200-bla\r\n"); StubChannelResponse(" 300 test\r\n"); StubChannelResponse("200 OK\r\n"); comm.AttachToChannel(channel); FtpServerResponse response = comm.ReadResponse(); Assert.AreEqual((int)FtpReturnCode.CommandOk, response.ReturnCode); Assert.AreEqual("bla", response.Message); } [Test] public void ReadMultiLineResponseInBatch() { StubChannelResponse("200-bla\r\n 300 test\r\n200 OK\r\n"); comm.AttachToChannel(channel); FtpServerResponse response = comm.ReadResponse(); Assert.AreEqual((int)FtpReturnCode.CommandOk, response.ReturnCode); Assert.AreEqual("bla", response.Message); } [Test] public void ReadInvalidSingleLineResponse() { StubChannelResponse("bla\r\n"); comm.AttachToChannel(channel); Assert.Throws<FtpException>(delegate { comm.ReadResponse(); }); } [Test] public void ReadInvalidMultiLineResponse() { StubChannelResponse("200-bla\r\n"); StubChannelResponse(" 300 test\r\n"); comm.AttachToChannel(channel); Assert.Throws<FtpException>(delegate { comm.ReadResponse (); }); } [SetUp] public void Setup() { channel = MockRepository.GenerateMock<IFtpChannel>(); comm = new FtpCommunicator(); } private void StubChannelResponse (string text) { channel.Stub(x => x.Receive(null)) .IgnoreArguments() .Do(new Action<Stream>(s => WriteToStream(s, text))) .Repeat.Once(); } private static void WriteToStream(Stream stream, string text) { byte[] data = Encoding.ASCII.GetBytes(text); stream.Write(data, 0, data.Length); } private IFtpChannel channel; private IFtpCommunicator comm; } }
30.857143
80
0.565883
[ "MIT" ]
breki/librolib
LibroLib.Tests/WebUtilsTests/FtpTests/FtpCommunicatorTests.cs
2,808
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class InitScene : MonoBehaviour { public GameObject gameManagerTemplate; private void Start() { Instantiate(gameManagerTemplate); } }
17.642857
42
0.732794
[ "MIT" ]
DontCallMeShurley/Unity-DigitalLab
Assets/_Project/Scripts/SoundRoom/InitScene.cs
249
C#