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 GroupDocs.Editor.MVC.Products.Editor.Entity.Web { public enum EditableDocumentType { Words = 0, Cells = 1 } }
17.333333
57
0.589744
[ "MIT" ]
groupdocs-editor/GroupDocs.Editor-for-.NET
Demos/MVC/src/Products/Editor/Entity/Web/EditableDocumentType.cs
158
C#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Game.Rulesets.Mods; namespace osu.Game.Rulesets.Taiko.Mods { public class TaikoModHardRock : ModHardRock { public override double ScoreMultiplier => 1.06; public override bool Ranked => true; } }
28.5
80
0.681704
[ "MIT" ]
123tris/osu
osu.Game.Rulesets.Taiko/Mods/TaikoModHardRock.cs
388
C#
using System.Collections.Generic; namespace VendorOrderTracker.Models { public class Order { public string Description { get; set; } public int Id { get; } private static List<Order> _instances = new List<Order> {}; public Order(string description) { Description = description; _instances.Add(this); Id = _instances.Count; } public static void ClearAll() { _instances.Clear(); } public static List<Order> GetAll() { return _instances; } public static Order FindOrder(int searchId) { return _instances[searchId - 1]; } } }
20.833333
63
0.6288
[ "MIT" ]
JohnNilsOlson/VendorOrderTracker.Solution
VendorOrderTracker/Models/Order.cs
625
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace LeetCode.Naive.Problems { /// <summary> /// Problem: https://leetcode.com/problems/construct-target-array-with-multiple-sums/ /// Submission: https://leetcode.com/submissions/detail/303790486/ /// </summary> internal class P1354 { public class Solution { public bool IsPossible(int[] target) { long sum = target.Sum(x => (long)x); while (true) { var max = int.MinValue; var maxIndex = 0; for (int i = 0; i < target.Length; i++) { if (target[i] > max) { max = target[i]; maxIndex = i; } } if (max == 1) return true; var restsum = sum - max; var prevval = max - restsum; if (prevval < 1) return false; target[maxIndex] = (int)prevval; sum = restsum + prevval; } return true; } } } }
21.615385
91
0.476868
[ "MIT" ]
viacheslave/leetcode-naive
c#/Problems/P1354.cs
1,124
C#
using System; using System.Collections.Generic; using System.Text; namespace Bakery.Models.Drinks { public class Water : Drink { private const decimal WaterPrice = 1.50m; public Water(string name, int portion, string brand) : base(name, portion, WaterPrice, brand) { } } }
20.6875
60
0.628399
[ "MIT" ]
GeorgiPopovIT/CSharp-OOP
Exam/01. Bakery-Structure and Business Logic/Bakery/Models/Drinks/Water.cs
333
C#
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System.Reflection; using Xunit; [assembly: AssemblyTitle("Avalonia.Interactive.UnitTests")] // Don't run tests in parallel. [assembly: CollectionBehavior(DisableTestParallelization = true)]
36.3
104
0.787879
[ "MIT" ]
AvtRikki/Avalonia
tests/Avalonia.Interactivity.UnitTests/Properties/AssemblyInfo.cs
363
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Linq; using Axe.Windows.Core.Bases; using Axe.Windows.Core.Enums; using Axe.Windows.Core.Types; using Axe.Windows.Rules.Resources; using static Axe.Windows.Rules.PropertyConditions.ControlType; using static Axe.Windows.Rules.PropertyConditions.StringProperties; namespace Axe.Windows.Rules.Library { [RuleInfo(ID = RuleId.LocalizedControlTypeReasonable)] class LocalizedControlTypeIsReasonable : Rule { public LocalizedControlTypeIsReasonable() { this.Info.Description = Descriptions.LocalizedControlTypeReasonable; this.Info.HowToFix = HowToFix.LocalizedControlTypeReasonable; this.Info.Standard = A11yCriteriaId.ObjectInformation; this.Info.PropertyID = PropertyType.UIA_LocalizedControlTypePropertyId; } public override EvaluationCode Evaluate(IA11yElement e) { if (e == null) throw new ArgumentNullException(nameof(e)); return HasReasonableLocalizedControlType(e) ? EvaluationCode.Pass : EvaluationCode.Warning; } private bool HasReasonableLocalizedControlType(IA11yElement e) { var names = GetExpectedLocalizedControlTypeNames(e.ControlTypeId); if (names == null) throw new InvalidProgramException(ErrorMessages.NoLocalizedControlTypeStringFound); return Array.Exists(names, s => String.Compare(e.LocalizedControlType, s, StringComparison.OrdinalIgnoreCase) == 0); } private static string[] GetExpectedLocalizedControlTypeNames(int controlTypeId) { string names = null; switch(controlTypeId) { case Axe.Windows.Core.Types.ControlType.UIA_AppBarControlTypeId: names = LocalizedControlTypeNames.AppBar; break; case Axe.Windows.Core.Types.ControlType.UIA_ButtonControlTypeId: names = LocalizedControlTypeNames.Button; break; case Axe.Windows.Core.Types.ControlType.UIA_CalendarControlTypeId: names = LocalizedControlTypeNames.Calendar; break; case Axe.Windows.Core.Types.ControlType.UIA_CheckBoxControlTypeId: names = LocalizedControlTypeNames.CheckBox; break; case Axe.Windows.Core.Types.ControlType.UIA_ComboBoxControlTypeId: names = LocalizedControlTypeNames.ComboBox; break; case Axe.Windows.Core.Types.ControlType.UIA_EditControlTypeId: names = LocalizedControlTypeNames.Edit; break; case Axe.Windows.Core.Types.ControlType.UIA_HyperlinkControlTypeId: names = LocalizedControlTypeNames.Hyperlink; break; case Axe.Windows.Core.Types.ControlType.UIA_ImageControlTypeId: names = LocalizedControlTypeNames.Image; break; case Axe.Windows.Core.Types.ControlType.UIA_ListItemControlTypeId: names = LocalizedControlTypeNames.ListItem; break; case Axe.Windows.Core.Types.ControlType.UIA_ListControlTypeId: names = LocalizedControlTypeNames.List; break; case Axe.Windows.Core.Types.ControlType.UIA_MenuControlTypeId: names = LocalizedControlTypeNames.Menu; break; case Axe.Windows.Core.Types.ControlType.UIA_MenuBarControlTypeId: names = LocalizedControlTypeNames.MenuBar; break; case Axe.Windows.Core.Types.ControlType.UIA_MenuItemControlTypeId: names = LocalizedControlTypeNames.MenuItem; break; case Axe.Windows.Core.Types.ControlType.UIA_ProgressBarControlTypeId: names = LocalizedControlTypeNames.ProgressBar; break; case Axe.Windows.Core.Types.ControlType.UIA_RadioButtonControlTypeId: names = LocalizedControlTypeNames.RadioButton; break; case Axe.Windows.Core.Types.ControlType.UIA_ScrollBarControlTypeId: names = LocalizedControlTypeNames.ScrollBar; break; case Axe.Windows.Core.Types.ControlType.UIA_SliderControlTypeId: names = LocalizedControlTypeNames.Slider; break; case Axe.Windows.Core.Types.ControlType.UIA_SpinnerControlTypeId: names = LocalizedControlTypeNames.Spinner; break; case Axe.Windows.Core.Types.ControlType.UIA_StatusBarControlTypeId: names = LocalizedControlTypeNames.StatusBar; break; case Axe.Windows.Core.Types.ControlType.UIA_TabControlTypeId: names = LocalizedControlTypeNames.Tab; break; case Axe.Windows.Core.Types.ControlType.UIA_TabItemControlTypeId: names = LocalizedControlTypeNames.TabItem; break; case Axe.Windows.Core.Types.ControlType.UIA_TextControlTypeId: names = LocalizedControlTypeNames.Text; break; case Axe.Windows.Core.Types.ControlType.UIA_ToolBarControlTypeId: names = LocalizedControlTypeNames.ToolBar; break; case Axe.Windows.Core.Types.ControlType.UIA_ToolTipControlTypeId: names = LocalizedControlTypeNames.ToolTip; break; case Axe.Windows.Core.Types.ControlType.UIA_TreeControlTypeId: names = LocalizedControlTypeNames.Tree; break; case Axe.Windows.Core.Types.ControlType.UIA_TreeItemControlTypeId: names = LocalizedControlTypeNames.TreeItem; break; case Axe.Windows.Core.Types.ControlType.UIA_GroupControlTypeId: names = LocalizedControlTypeNames.Group; break; case Axe.Windows.Core.Types.ControlType.UIA_ThumbControlTypeId: names = LocalizedControlTypeNames.Thumb; break; case Axe.Windows.Core.Types.ControlType.UIA_DataGridControlTypeId: names = LocalizedControlTypeNames.DataGrid; break; case Axe.Windows.Core.Types.ControlType.UIA_DataItemControlTypeId: names = LocalizedControlTypeNames.DataItem; break; case Axe.Windows.Core.Types.ControlType.UIA_DocumentControlTypeId: names = LocalizedControlTypeNames.Document; break; case Axe.Windows.Core.Types.ControlType.UIA_SplitButtonControlTypeId: names = LocalizedControlTypeNames.SplitButton; break; case Axe.Windows.Core.Types.ControlType.UIA_WindowControlTypeId: names = LocalizedControlTypeNames.Window; break; case Axe.Windows.Core.Types.ControlType.UIA_PaneControlTypeId: names = LocalizedControlTypeNames.Pane; break; case Axe.Windows.Core.Types.ControlType.UIA_HeaderControlTypeId: names = LocalizedControlTypeNames.Header; break; case Axe.Windows.Core.Types.ControlType.UIA_HeaderItemControlTypeId: names = LocalizedControlTypeNames.HeaderItem; break; case Axe.Windows.Core.Types.ControlType.UIA_TableControlTypeId: names = LocalizedControlTypeNames.Table; break; case Axe.Windows.Core.Types.ControlType.UIA_TitleBarControlTypeId: names = LocalizedControlTypeNames.TitleBar; break; case Axe.Windows.Core.Types.ControlType.UIA_SeparatorControlTypeId: names = LocalizedControlTypeNames.Separator; break; case Axe.Windows.Core.Types.ControlType.UIA_SemanticZoomControlTypeId: names = LocalizedControlTypeNames.SemanticZoom; break; default: break; } return names == null ? null : names.Split(','); } protected override Condition CreateCondition() { return ~Custom & LocalizedControlType.NotNullOrEmpty & LocalizedControlType.NotWhiteSpace; } } // class } // namespace
51.333333
129
0.594481
[ "MIT" ]
dbjorge/axe-windows
src/Rules/Library/LocalizedControlTypeIsReasonable.cs
9,061
C#
using System; namespace Database.Common.DataOperation { /// <summary> /// Used when a document is invalid. /// </summary> internal class InvalidDocumentException : Exception { /// <summary> /// Initializes a new instance of the <see cref="InvalidDocumentException"/> class. /// </summary> public InvalidDocumentException() : base() { } /// <summary> /// Initializes a new instance of the <see cref="InvalidDocumentException"/> class. /// </summary> /// <param name="reason">The reason for the exception.</param> public InvalidDocumentException(string reason) : base(reason) { } } }
27.259259
91
0.569293
[ "MIT" ]
CaptainCow95/Database
DatabaseCommon/DataOperation/InvalidDocumentException.cs
738
C#
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Attribute Manager")] [assembly: AssemblyDescription("Renames an attribute for an Entity, optionally preserving Data as well")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("D La B")] [assembly: AssemblyProduct("DLaB.AttributeManager")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("35250a37-d9d6-4fe5-93f8-3f9e470b13bd")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.2021.1.18")] [assembly: AssemblyFileVersion("1.2021.1.18")]
40.416667
105
0.749141
[ "MIT" ]
lnetrebskii/DLaB.Xrm.XrmToolBoxTools
DLaB.AttributeManager/Properties/AssemblyInfo.cs
1,456
C#
#if UNITY_STANDALONE_OSX || UNITY_EDITOR_OSX using System.Runtime.InteropServices; using UnityEngine.Experimental.Input.Layouts; using UnityEngine.Experimental.Input.Plugins.XInput.LowLevel; using UnityEngine.Experimental.Input.Utilities; namespace UnityEngine.Experimental.Input.Plugins.XInput.LowLevel { // Xbox one controller on OSX. State layout can be found here: // https://github.com/360Controller/360Controller/blob/master/360Controller/ControlStruct.h // struct InputReport // { // byte command; // byte size; // short buttons; // byte triggerLeft; // byte triggerRight; // short leftX; // short leftY; // short rightX; // short rightY; // } // Report size is 14 bytes. First two bytes are header information for the report. [StructLayout(LayoutKind.Explicit, Size = 4)] public struct XInputControllerOSXState : IInputStateTypeInfo { public static FourCC kFormat { get { return new FourCC('H', 'I', 'D'); } } public enum Button { DPadUp = 0, DPadDown = 1, DPadLeft = 2, DPadRight = 3, Start = 4, Select = 5, LeftThumbstickPress = 6, RightThumbstickPress = 7, LeftShoulder = 8, RightShoulder = 9, A = 12, B = 13, X = 14, Y = 15, } [InputControl(name = "dpad", layout = "Dpad", sizeInBits = 4, bit = 0)] [InputControl(name = "dpad/up", bit = (uint)Button.DPadUp)] [InputControl(name = "dpad/down", bit = (uint)Button.DPadDown)] [InputControl(name = "dpad/left", bit = (uint)Button.DPadLeft)] [InputControl(name = "dpad/right", bit = (uint)Button.DPadRight)] [InputControl(name = "start", bit = (uint)Button.Start, displayName = "Start")] [InputControl(name = "select", bit = (uint)Button.Select, displayName = "Select")] [InputControl(name = "leftStickPress", bit = (uint)Button.LeftThumbstickPress)] [InputControl(name = "rightStickPress", bit = (uint)Button.RightThumbstickPress)] [InputControl(name = "leftShoulder", bit = (uint)Button.LeftShoulder)] [InputControl(name = "rightShoulder", bit = (uint)Button.RightShoulder)] [InputControl(name = "buttonSouth", bit = (uint)Button.A, displayName = "A")] [InputControl(name = "buttonEast", bit = (uint)Button.B, displayName = "B")] [InputControl(name = "buttonWest", bit = (uint)Button.X, displayName = "X")] [InputControl(name = "buttonNorth", bit = (uint)Button.Y, displayName = "Y")] [FieldOffset(2)] public uint buttons; [InputControl(name = "leftTrigger", format = "BYTE")] [FieldOffset(4)] public byte leftTrigger; [InputControl(name = "rightTrigger", format = "BYTE")] [FieldOffset(5)] public byte rightTrigger; [InputControl(name = "leftStick", layout = "Stick", format = "VC2S")] [InputControl(name = "leftStick/x", offset = 0, format = "SHRT", parameters = "")] [InputControl(name = "leftStick/left", offset = 0, format = "SHRT", parameters = "")] [InputControl(name = "leftStick/right", offset = 0, format = "SHRT", parameters = "")] [InputControl(name = "leftStick/y", offset = 2, format = "SHRT", parameters = "invert")] [InputControl(name = "leftStick/up", offset = 2, format = "SHRT", parameters = "clamp,clampMin=-1,clampMax=0,invert=true")] [InputControl(name = "leftStick/down", offset = 2, format = "SHRT", parameters = "clamp,clampMin=0,clampMax=1,invert=false")] [FieldOffset(6)] public short leftStickX; [FieldOffset(8)] public short leftStickY; [InputControl(name = "rightStick", layout = "Stick", format = "VC2S")] [InputControl(name = "rightStick/x", offset = 0, format = "SHRT", parameters = "")] [InputControl(name = "rightStick/left", offset = 0, format = "SHRT", parameters = "")] [InputControl(name = "rightStick/right", offset = 0, format = "SHRT", parameters = "")] [InputControl(name = "rightStick/y", offset = 2, format = "SHRT", parameters = "invert")] [InputControl(name = "rightStick/up", offset = 2, format = "SHRT", parameters = "clamp,clampMin=-1,clampMax=0,invert=true")] [InputControl(name = "rightStick/down", offset = 2, format = "SHRT", parameters = "clamp,clampMin=0,clampMax=1,invert=false")] [FieldOffset(10)] public short rightStickX; [FieldOffset(12)] public short rightStickY; public FourCC GetFormat() { return kFormat; } public XInputControllerOSXState WithButton(Button button) { buttons |= (uint)1 << (int)button; return this; } } } namespace UnityEngine.Experimental.Input.Plugins.XInput { [InputControlLayout(stateType = typeof(XInputControllerOSXState))] public class XInputControllerOSX : XInputController { } } #endif // UNITY_STANDALONE_OSX || UNITY_EDITOR_OSX
44.327586
134
0.613574
[ "MIT" ]
ToadsworthLP/Millenium
Library/PackageCache/com.unity.inputsystem@0.2.6-preview/InputSystem/Plugins/XInput/XInputControllerOSX.cs
5,142
C#
using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Text; using System.Threading.Tasks; using AutoMapper; using GWSuncoastAPI.Entity; using GWSuncoastAPI.Entity.UnitofWork; namespace GWSuncoastAPI.Domain.Service { public class GenericServiceAsync<Tv, Te> : IServiceAsync<Tv, Te> where Tv : BaseDomain where Te : BaseEntity { protected IUnitOfWork _unitOfWork; protected IMapper _mapper; public GenericServiceAsync(IUnitOfWork unitOfWork, IMapper mapper) { _unitOfWork = unitOfWork; _mapper = mapper; } public GenericServiceAsync() { } public virtual async Task<IEnumerable<Tv>> GetAll() { var entities = await _unitOfWork.GetRepositoryAsync<Te>() .GetAll(); return _mapper.Map<IEnumerable<Tv>>(source: entities); } public virtual async Task<Tv> GetOne(int id) { var entity = await _unitOfWork.GetRepositoryAsync<Te>() .GetOne(predicate: x => x.Id == id); return _mapper.Map<Tv>(source: entity); } public virtual async Task<int> Add(Tv view) { var entity = _mapper.Map<Te>(source: view); await _unitOfWork.GetRepositoryAsync<Te>().Insert(entity); await _unitOfWork.SaveAsync(); return entity.Id; } public async Task<int> Update(Tv view) { await _unitOfWork.GetRepositoryAsync<Te>().Update(view.Id, _mapper.Map<Te>(source: view)); return await _unitOfWork.SaveAsync(); } public virtual async Task<int> Remove(int id) { Te entity = await _unitOfWork.Context.Set<Te>().FindAsync(id); await _unitOfWork.GetRepositoryAsync<Te>().Delete(id); return await _unitOfWork.SaveAsync(); } public virtual async Task<IEnumerable<Tv>> Get(Expression<Func<Te, bool>> predicate) { var items = await _unitOfWork.GetRepositoryAsync<Te>() .Get(predicate: predicate); return _mapper.Map<IEnumerable<Tv>>(source: items); } } }
30.621622
102
0.596646
[ "MIT" ]
wcrowe/GWSuncoastAPI
src/GWSuncoastAPI.Domain/Service/Generic/GenericServiceAsync.cs
2,268
C#
using System; using System.Collections; using System.IO; using System.Runtime.InteropServices; //using BOOL = System.Boolean; using DWORD = System.UInt32; using LPWSTR = System.String; using NET_API_STATUS = System.UInt32; namespace UNCFunctions { public class UNCAccess { [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct USE_INFO_2 { internal LPWSTR ui2_local; internal LPWSTR ui2_remote; internal LPWSTR ui2_password; internal DWORD ui2_status; internal DWORD ui2_asg_type; internal DWORD ui2_refcount; internal DWORD ui2_usecount; internal LPWSTR ui2_username; internal LPWSTR ui2_domainname; } const int USER_PRIV_GUEST = 0; // lmaccess.h:656 const int USER_PRIV_USER = 1; // lmaccess.h:657 const int USER_PRIV_ADMIN = 2; // lmaccess.h:658 //const DWORD USE_WILDCARD = ((DWORD) - 1); const DWORD USE_DISKDEV = 0; const DWORD USE_SPOOLDEV = 1; const DWORD USE_CHARDEV = 2; const DWORD USE_IPC = 3; [DllImport("NetApi32.dll", SetLastError = true, CharSet = CharSet.Unicode)] internal static extern NET_API_STATUS NetUseAdd( LPWSTR UncServerName, DWORD Level, ref USE_INFO_2 Buf, out DWORD ParmError); [DllImport("NetApi32.dll", SetLastError = true, CharSet = CharSet.Unicode)] internal static extern NET_API_STATUS NetUseDel( LPWSTR UncServerName, LPWSTR UseName, DWORD ForceCond); private string sUNCPath; private string sUser; private string sPassword; private string sDomain; private int iLastError; public UNCAccess() { } public UNCAccess(string UNCPath, string User, string Domain, string Password) { login(UNCPath, User, Domain, Password); } public int LastError { get { return iLastError; } } /// <summary> /// Connects to a UNC share folder with credentials /// </summary> /// <param name="UNCPath">UNC share path</param> /// <param name="User">Username</param> /// <param name="Domain">Domain</param> /// <param name="Password">Password</param> /// <returns>True if login was successful</returns> public bool login(string UNCPath, string User, string Domain, string Password) { //Verify that sUNCPath does not have a ending \ if (UNCPath.LastIndexOf('\\') == UNCPath.Length-1) UNCPath = UNCPath.Remove(UNCPath.Length - 1); //Split the item into parts and only connect to the \\server\share (not \\sever\share\whatever\directory) string[] sParts = UNCPath.Split('\\'); if (sParts.Length > 4) UNCPath = @"\\" + sParts[2] + @"\" + sParts[3]; sUNCPath = UNCPath; sUser = User; if (sUser == null) //Database uses null insted of "" sUser = ""; sPassword = Password; if (sPassword == null) sPassword = ""; sDomain = Domain; //No need to login without credentials if (sUser.Length == 0) return true; return NetUseWithCredentials(); } private bool NetUseWithCredentials() { uint returncode; try { USE_INFO_2 useinfo = new USE_INFO_2(); useinfo.ui2_remote = sUNCPath; useinfo.ui2_username = sUser; useinfo.ui2_domainname = sDomain; useinfo.ui2_password = sPassword; useinfo.ui2_asg_type = USE_DISKDEV; if(sUNCPath.ToUpper().IndexOf("IPC$") != -1) useinfo.ui2_asg_type = USE_IPC; useinfo.ui2_usecount = 1; uint paramErrorIndex; returncode = NetUseAdd(null, 2, ref useinfo, out paramErrorIndex); iLastError = (int)returncode; return returncode == 0; } catch { iLastError = Marshal.GetLastWin32Error(); return false; } } /// <summary> /// Closes the UNC share /// </summary> /// <returns>True if closing was successful</returns> public bool NetUseDelete() { uint returncode; try { returncode = NetUseDel(null, sUNCPath, 2); iLastError = (int)returncode; return (returncode == 0); } catch { iLastError = Marshal.GetLastWin32Error(); return false; } } } #region Share Type /// <summary> /// Type of share /// </summary> [Flags] public enum ShareType { /// <summary>Disk share</summary> Disk = 0, /// <summary>Printer share</summary> Printer = 1, /// <summary>Device share</summary> Device = 2, /// <summary>IPC share</summary> IPC = 3, /// <summary>Special share</summary> Special = -2147483648, // 0x80000000, } #endregion #region Share /// <summary> /// Information about a local share /// </summary> public class Share { #region Private data private string _server; private string _netName; private string _path; private ShareType _shareType; private string _remark; #endregion #region Constructor /// <summary> /// Constructor /// </summary> /// <param name="Server"></param> /// <param name="shi"></param> public Share(string server, string netName, string path, ShareType shareType, string remark) { if (ShareType.Special == shareType && "IPC$" == netName) { shareType |= ShareType.IPC; } _server = server; _netName = netName; _path = path; _shareType = shareType; _remark = remark; } #endregion #region Properties /// <summary> /// The name of the computer that this share belongs to /// </summary> public string Server { get { return _server; } } /// <summary> /// Share name /// </summary> public string NetName { get { return _netName; } } /// <summary> /// Local path /// </summary> public string Path { get { return _path; } } /// <summary> /// Share type /// </summary> public ShareType ShareType { get { return _shareType; } } /// <summary> /// Comment /// </summary> public string Remark { get { return _remark; } } /// <summary> /// Returns true if this is a file system share /// </summary> public bool IsFileSystem { get { // Shared device if (0 != (_shareType & ShareType.Device)) return false; // IPC share if (0 != (_shareType & ShareType.IPC)) return false; // Shared printer if (0 != (_shareType & ShareType.Printer)) return false; // Standard disk share if (0 == (_shareType & ShareType.Special)) return true; // Special disk share (e.g. C$) if (ShareType.Special == _shareType && null != _netName && 0 != _netName.Length) return true; else return false; } } /// <summary> /// Get the root of a disk-based share /// </summary> public DirectoryInfo Root { get { if (IsFileSystem) { if (null == _server || 0 == _server.Length) if (null == _path || 0 == _path.Length) return new DirectoryInfo(ToString()); else return new DirectoryInfo(_path); else return new DirectoryInfo(ToString()); } else return null; } } #endregion /// <summary> /// Returns the path to this share /// </summary> /// <returns></returns> public override string ToString() { if (null == _server || 0 == _server.Length) { return string.Format(@"\\{0}\{1}", Environment.MachineName, _netName); } else return string.Format(@"\\{0}\{1}", _server, _netName); } /// <summary> /// Returns true if this share matches the local path /// </summary> /// <param name="path"></param> /// <returns></returns> public bool MatchesPath(string path) { if (!IsFileSystem) return false; if (null == path || 0 == path.Length) return true; return path.ToLower().StartsWith(_path.ToLower()); } } #endregion #region Share Collection /// <summary> /// A collection of shares /// </summary> public class ShareCollection : ReadOnlyCollectionBase { #region Platform /// <summary> /// Is this an NT platform? /// </summary> protected static bool IsNT { get { return (PlatformID.Win32NT == Environment.OSVersion.Platform); } } /// <summary> /// Returns true if this is Windows 2000 or higher /// </summary> protected static bool IsW2KUp { get { OperatingSystem os = Environment.OSVersion; if (PlatformID.Win32NT == os.Platform && os.Version.Major >= 5) return true; else return false; } } #endregion #region Interop #region Constants /// <summary>Maximum path length</summary> protected const int MAX_PATH = 260; /// <summary>No error</summary> protected const int NO_ERROR = 0; /// <summary>Access denied</summary> protected const int ERROR_ACCESS_DENIED = 5; /// <summary>Access denied</summary> protected const int ERROR_WRONG_LEVEL = 124; /// <summary>More data available</summary> protected const int ERROR_MORE_DATA = 234; /// <summary>Not connected</summary> protected const int ERROR_NOT_CONNECTED = 2250; /// <summary>Level 1</summary> protected const int UNIVERSAL_NAME_INFO_LEVEL = 1; /// <summary>Max extries (9x)</summary> protected const int MAX_SI50_ENTRIES = 20; #endregion #region Structures /// <summary>Unc name</summary> [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] protected struct UNIVERSAL_NAME_INFO { [MarshalAs(UnmanagedType.LPTStr)] public string lpUniversalName; } /// <summary>Share information, NT, level 2</summary> /// <remarks> /// Requires admin rights to work. /// </remarks> [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] protected struct SHARE_INFO_2 { [MarshalAs(UnmanagedType.LPWStr)] public string NetName; public ShareType ShareType; [MarshalAs(UnmanagedType.LPWStr)] public string Remark; public int Permissions; public int MaxUsers; public int CurrentUsers; [MarshalAs(UnmanagedType.LPWStr)] public string Path; [MarshalAs(UnmanagedType.LPWStr)] public string Password; } /// <summary>Share information, NT, level 1</summary> /// <remarks> /// Fallback when no admin rights. /// </remarks> [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] protected struct SHARE_INFO_1 { [MarshalAs(UnmanagedType.LPWStr)] public string NetName; public ShareType ShareType; [MarshalAs(UnmanagedType.LPWStr)] public string Remark; } /// <summary>Share information, Win9x</summary> [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)] protected struct SHARE_INFO_50 { [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 13)] public string NetName; public byte bShareType; public ushort Flags; [MarshalAs(UnmanagedType.LPTStr)] public string Remark; [MarshalAs(UnmanagedType.LPTStr)] public string Path; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 9)] public string PasswordRW; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 9)] public string PasswordRO; public ShareType ShareType { get { return (ShareType)((int)bShareType & 0x7F); } } } /// <summary>Share information level 1, Win9x</summary> [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)] protected struct SHARE_INFO_1_9x { [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 13)] public string NetName; public byte Padding; public ushort bShareType; [MarshalAs(UnmanagedType.LPTStr)] public string Remark; public ShareType ShareType { get { return (ShareType)((int)bShareType & 0x7FFF); } } } #endregion #region Functions /// <summary>Get a UNC name</summary> [DllImport("mpr", CharSet = CharSet.Auto)] protected static extern int WNetGetUniversalName(string lpLocalPath, int dwInfoLevel, ref UNIVERSAL_NAME_INFO lpBuffer, ref int lpBufferSize); /// <summary>Get a UNC name</summary> [DllImport("mpr", CharSet = CharSet.Auto)] protected static extern int WNetGetUniversalName(string lpLocalPath, int dwInfoLevel, IntPtr lpBuffer, ref int lpBufferSize); /// <summary>Enumerate shares (NT)</summary> [DllImport("netapi32", CharSet = CharSet.Unicode)] protected static extern int NetShareEnum(string lpServerName, int dwLevel, out IntPtr lpBuffer, int dwPrefMaxLen, out int entriesRead, out int totalEntries, ref int hResume); /// <summary>Enumerate shares (9x)</summary> [DllImport("svrapi", CharSet = CharSet.Ansi)] protected static extern int NetShareEnum( [MarshalAs(UnmanagedType.LPTStr)] string lpServerName, int dwLevel, IntPtr lpBuffer, ushort cbBuffer, out ushort entriesRead, out ushort totalEntries); /// <summary>Free the buffer (NT)</summary> [DllImport("netapi32")] protected static extern int NetApiBufferFree(IntPtr lpBuffer); #endregion #region Enumerate shares /// <summary> /// Enumerates the shares on Windows NT /// </summary> /// <param name="server">The server name</param> /// <param name="shares">The ShareCollection</param> protected static void EnumerateSharesNT(string server, ShareCollection shares) { int level = 2; int entriesRead, totalEntries, nRet, hResume = 0; IntPtr pBuffer = IntPtr.Zero; try { nRet = NetShareEnum(server, level, out pBuffer, -1, out entriesRead, out totalEntries, ref hResume); if (ERROR_ACCESS_DENIED == nRet) { //Need admin for level 2, drop to level 1 level = 1; nRet = NetShareEnum(server, level, out pBuffer, -1, out entriesRead, out totalEntries, ref hResume); } if (NO_ERROR == nRet && entriesRead > 0) { Type t = (2 == level) ? typeof(SHARE_INFO_2) : typeof(SHARE_INFO_1); int offset = Marshal.SizeOf(t); for (int i = 0, lpItem = pBuffer.ToInt32(); i < entriesRead; i++, lpItem += offset) { IntPtr pItem = new IntPtr(lpItem); if (1 == level) { SHARE_INFO_1 si = (SHARE_INFO_1)Marshal.PtrToStructure(pItem, t); shares.Add(si.NetName, string.Empty, si.ShareType, si.Remark); } else { SHARE_INFO_2 si = (SHARE_INFO_2)Marshal.PtrToStructure(pItem, t); shares.Add(si.NetName, si.Path, si.ShareType, si.Remark); } } } } finally { // Clean up buffer allocated by system if (IntPtr.Zero != pBuffer) NetApiBufferFree(pBuffer); } } /// <summary> /// Enumerates the shares on Windows 9x /// </summary> /// <param name="server">The server name</param> /// <param name="shares">The ShareCollection</param> protected static void EnumerateShares9x(string server, ShareCollection shares) { int level = 50; int nRet = 0; ushort entriesRead, totalEntries; Type t = typeof(SHARE_INFO_50); int size = Marshal.SizeOf(t); ushort cbBuffer = (ushort)(MAX_SI50_ENTRIES * size); //On Win9x, must allocate buffer before calling API IntPtr pBuffer = Marshal.AllocHGlobal(cbBuffer); try { nRet = NetShareEnum(server, level, pBuffer, cbBuffer, out entriesRead, out totalEntries); if (ERROR_WRONG_LEVEL == nRet) { level = 1; t = typeof(SHARE_INFO_1_9x); size = Marshal.SizeOf(t); nRet = NetShareEnum(server, level, pBuffer, cbBuffer, out entriesRead, out totalEntries); } if (NO_ERROR == nRet || ERROR_MORE_DATA == nRet) { for (int i = 0, lpItem = pBuffer.ToInt32(); i < entriesRead; i++, lpItem += size) { IntPtr pItem = new IntPtr(lpItem); if (1 == level) { SHARE_INFO_1_9x si = (SHARE_INFO_1_9x)Marshal.PtrToStructure(pItem, t); shares.Add(si.NetName, string.Empty, si.ShareType, si.Remark); } else { SHARE_INFO_50 si = (SHARE_INFO_50)Marshal.PtrToStructure(pItem, t); shares.Add(si.NetName, si.Path, si.ShareType, si.Remark); } } } else Console.WriteLine(nRet); } finally { //Clean up buffer Marshal.FreeHGlobal(pBuffer); } } /// <summary> /// Enumerates the shares /// </summary> /// <param name="server">The server name</param> /// <param name="shares">The ShareCollection</param> protected static void EnumerateShares(string server, ShareCollection shares) { if (null != server && 0 != server.Length && !IsW2KUp) { server = server.ToUpper(); // On NT4, 9x and Me, server has to start with "\\" if (!('\\' == server[0] && '\\' == server[1])) server = @"\\" + server; } if (IsNT) EnumerateSharesNT(server, shares); else EnumerateShares9x(server, shares); } #endregion #endregion #region Static methods /// <summary> /// Returns true if fileName is a valid local file-name of the form: /// X:\, where X is a drive letter from A-Z /// </summary> /// <param name="fileName">The filename to check</param> /// <returns></returns> public static bool IsValidFilePath(string fileName) { if (null == fileName || 0 == fileName.Length) return false; char drive = char.ToUpper(fileName[0]); if ('A' > drive || drive > 'Z') return false; else if (Path.VolumeSeparatorChar != fileName[1]) return false; else if (Path.DirectorySeparatorChar != fileName[2]) return false; else return true; } /// <summary> /// Returns the UNC path for a mapped drive or local share. /// </summary> /// <param name="fileName">The path to map</param> /// <returns>The UNC path (if available)</returns> public static string PathToUnc(string fileName) { if (null == fileName || 0 == fileName.Length) return string.Empty; fileName = Path.GetFullPath(fileName); if (!IsValidFilePath(fileName)) return fileName; int nRet = 0; UNIVERSAL_NAME_INFO rni = new UNIVERSAL_NAME_INFO(); int bufferSize = Marshal.SizeOf(rni); nRet = WNetGetUniversalName( fileName, UNIVERSAL_NAME_INFO_LEVEL, ref rni, ref bufferSize); if (ERROR_MORE_DATA == nRet) { IntPtr pBuffer = Marshal.AllocHGlobal(bufferSize); ; try { nRet = WNetGetUniversalName( fileName, UNIVERSAL_NAME_INFO_LEVEL, pBuffer, ref bufferSize); if (NO_ERROR == nRet) { rni = (UNIVERSAL_NAME_INFO)Marshal.PtrToStructure(pBuffer, typeof(UNIVERSAL_NAME_INFO)); } } finally { Marshal.FreeHGlobal(pBuffer); } } switch (nRet) { case NO_ERROR: return rni.lpUniversalName; case ERROR_NOT_CONNECTED: //Local file-name ShareCollection shi = LocalShares; if (null != shi) { Share share = shi[fileName]; if (null != share) { string path = share.Path; if (null != path && 0 != path.Length) { int index = path.Length; if (Path.DirectorySeparatorChar != path[path.Length - 1]) index++; if (index < fileName.Length) fileName = fileName.Substring(index); else fileName = string.Empty; fileName = Path.Combine(share.ToString(), fileName); } } } return fileName; default: Console.WriteLine("Unknown return value: {0}", nRet); return string.Empty; } } /// <summary> /// Returns the local <see cref="Share"/> object with the best match /// to the specified path. /// </summary> /// <param name="fileName"></param> /// <returns></returns> public static Share PathToShare(string fileName) { if (null == fileName || 0 == fileName.Length) return null; fileName = Path.GetFullPath(fileName); if (!IsValidFilePath(fileName)) return null; ShareCollection shi = LocalShares; if (null == shi) return null; else return shi[fileName]; } #endregion #region Local shares /// <summary>The local shares</summary> private static ShareCollection _local = null; /// <summary> /// Return the local shares /// </summary> public static ShareCollection LocalShares { get { if (null == _local) _local = new ShareCollection(); return _local; } } /// <summary> /// Return the shares for a specified machine /// </summary> /// <param name="server"></param> /// <returns></returns> public static ShareCollection GetShares(string server) { return new ShareCollection(server); } #endregion #region Private Data /// <summary>The name of the server this collection represents</summary> private string _server; #endregion #region Constructor /// <summary> /// Default constructor - local machine /// </summary> public ShareCollection() { _server = string.Empty; EnumerateShares(_server, this); } /// <summary> /// Constructor /// </summary> /// <param name="Server"></param> public ShareCollection(string server) { _server = server; EnumerateShares(_server, this); } #endregion #region Add protected void Add(Share share) { InnerList.Add(share); } protected void Add(string netName, string path, ShareType shareType, string remark) { InnerList.Add(new Share(_server, netName, path, shareType, remark)); } #endregion #region Properties /// <summary> /// Returns the name of the server this collection represents /// </summary> public string Server { get { return _server; } } /// <summary> /// Returns the <see cref="Share"/> at the specified index. /// </summary> public Share this[int index] { get { return (Share)InnerList[index]; } } /// <summary> /// Returns the <see cref="Share"/> which matches a given local path /// </summary> /// <param name="path">The path to match</param> public Share this[string path] { get { if (null == path || 0 == path.Length) return null; path = Path.GetFullPath(path); if (!IsValidFilePath(path)) return null; Share match = null; for (int i = 0; i < InnerList.Count; i++) { Share s = (Share)InnerList[i]; if (s.IsFileSystem && s.MatchesPath(path)) { //Store first match if (null == match) match = s; // If this has a longer path, // and this is a disk share or match is a special share, // then this is a better match else if (match.Path.Length < s.Path.Length) { if (ShareType.Disk == s.ShareType || ShareType.Disk != match.ShareType) match = s; } } } return match; } } #endregion #region Implementation of ICollection /// <summary> /// Copy this collection to an array /// </summary> /// <param name="array"></param> /// <param name="index"></param> public void CopyTo(Share[] array, int index) { InnerList.CopyTo(array, index); } #endregion } #endregion }
34.133404
117
0.452021
[ "MIT" ]
large/MOTRd
MOTRd/UNC.cs
31,985
C#
#if UNITY_EDITOR using UnityEngine; namespace PolyFew { public class HandleControlsUtility : System.IDisposable { public static HandleControlsUtility handleControls; public static readonly string s_xAxisMoveHandleHash = "xAxisFreeMoveHandleHash"; public static readonly string s_yAxisMoveHandleHash = "yAxisFreeMoveHandleHash"; public static readonly string s_zAxisMoveHandleHash = "zAxisFreeMoveHandleHash"; public static readonly string s_FreeMoveHandleHash = "FreeMoveHandleHash"; public static readonly string s_xzAxisMoveHandleHash = "xzAxisFreeMoveHandleHash"; public static readonly string s_xyAxisMoveHandleHash = "xyAxisFreeMoveHandleHash"; public static readonly string s_yzAxisMoveHandleHash = "yzAxisFreeMoveHandleHash"; public static readonly string s_xRotateHandleHash = "xRotateHandleHash"; public static readonly string s_yRotateHandleHash = "yRotateHandleHash"; public static readonly string s_zRotateHandleHash = "zRotateHandleHash"; public static readonly string s_camRotateHandleHash = "cameraAxisRotateHandleHash"; public static readonly string s_xyzRotateHandleHash = "xyzRotateHandleHash"; public static readonly int[] handleControlsIds; public enum HandleControls { xAxisMoveHandle = 0, yAxisMoveHandle, zAxisMoveHandle, xyAxisMoveHandle, xzAxisMoveHandle, yzAxisMoveHandle, allAxisMoveHandle, xAxisRotateHandle, yAxisRotateHandle, zAxisRotateHandle, camera, allAxisRotateHandle, unknown } static HandleControlsUtility() { if (handleControlsIds == null) { handleControlsIds = new int[12]; handleControlsIds[0] = GetHandlesControlId(s_xAxisMoveHandleHash); handleControlsIds[1] = GetHandlesControlId(s_yAxisMoveHandleHash); handleControlsIds[2] = GetHandlesControlId(s_zAxisMoveHandleHash); handleControlsIds[3] = GetHandlesControlId(s_xyAxisMoveHandleHash); handleControlsIds[4] = GetHandlesControlId(s_xzAxisMoveHandleHash); handleControlsIds[5] = GetHandlesControlId(s_yzAxisMoveHandleHash); handleControlsIds[6] = GetHandlesControlId(s_FreeMoveHandleHash); handleControlsIds[7] = GetHandlesControlId(s_xRotateHandleHash); handleControlsIds[8] = GetHandlesControlId(s_yRotateHandleHash); handleControlsIds[9] = GetHandlesControlId(s_zRotateHandleHash); handleControlsIds[10] = GetHandlesControlId(s_camRotateHandleHash); handleControlsIds[11] = GetHandlesControlId(s_xyzRotateHandleHash); } } public int GetControlId(HandleControls handleControl) { int index = (int)handleControl; if (index >= handleControlsIds.Length) { return -1; } return handleControlsIds[index]; } public HandleControls GetControlFromId(int handleControlId) { HandleControls control = HandleControls.unknown; for (int a = 0; a < handleControlsIds.Length; a++) { if (handleControlsIds[a] == handleControlId) { control = (HandleControls)a; break; } } return control; } public HandleControls GetCurrentSelectedControl() { return GetControlFromId(GUIUtility.hotControl); } public static int GetHandlesControlId(string controlName) { return GUIUtility.GetControlID(controlName.GetHashCode(), FocusType.Passive); } public HandleType GetManipulatedHandleType() { var selectedControl = GetCurrentSelectedControl(); switch (selectedControl) { case HandleControls.xAxisMoveHandle: case HandleControls.yAxisMoveHandle: case HandleControls.zAxisMoveHandle: case HandleControls.allAxisMoveHandle: Debug.Log("Pos selected"); return HandleType.position; case HandleControls.xAxisRotateHandle: case HandleControls.yAxisRotateHandle: case HandleControls.zAxisRotateHandle: case HandleControls.allAxisRotateHandle: Debug.Log("Rot selected"); return HandleType.rotation; default: Debug.Log("None selected"); return HandleType.none; } } public HandleType GetHandleType(HandleControls selectedControl) { switch (selectedControl) { case HandleControls.xAxisMoveHandle: case HandleControls.yAxisMoveHandle: case HandleControls.zAxisMoveHandle: case HandleControls.allAxisMoveHandle: return HandleType.position; case HandleControls.xAxisRotateHandle: case HandleControls.yAxisRotateHandle: case HandleControls.zAxisRotateHandle: case HandleControls.allAxisRotateHandle: return HandleType.rotation; default: return HandleType.none; } } public enum HandleType { position, rotation, none } public void Dispose() { //throw new NotImplementedException(); } } } #endif
27.443396
100
0.612754
[ "MIT" ]
skymeson/JITLDanceParty
Assets/PolyFew/Scripts/NonEditor-Scripts/HandleControlsUtility.cs
5,820
C#
#region BSD License /* * Use of this source code is governed by a BSD-style * license that can be found in the LICENSE.md file or at * https://github.com/Wagnerp/Krypton-Toolkit-Suite-Extended-NET-5.462/blob/master/LICENSE * */ #endregion using PaletteExplorer.Controls; using System; using System.Drawing; namespace PaletteExplorer.Classes.Controllers { /// <summary> /// This class will control the size & layout of the <see cref="CircularPictureBoxControl"/> control. /// </summary> public class CircularPictureBoxControlController { #region Constructors /// <summary> /// Initializes a new instance of the <see cref="CircularPictureBoxControlController"/> class. /// </summary> public CircularPictureBoxControlController() { } #endregion #region Methods /// <summary> /// /// </summary> /// <param name="control"></param> public static void CustomColourLayout(CircularPictureBoxControl control) { #region Size control.Size = new Size(1625, 537); #endregion #region Basic Colour Location control.GetBaseColourPreview().Location = new Point(19, 15); control.GetDarkColourPreview().Location = new Point(272, 15); control.GetMiddleColourPreview().Location = new Point(525, 15); control.GetLightColourPreview().Location = new Point(778, 15); control.GetLightestColourPreview().Location = new Point(1031, 15); #endregion #region Rest of First Row control.GetBorderColourPreview().Location = new Point(1284, 18); control.GetAlternativeNormalTextColourPreview().Location = new Point(1537, 18); #endregion #region Second Row control.GetDisabledTextColourPreview().Location = new Point(19, 147); control.GetFocusedTextColourPreview().Location = new Point(272, 147); control.GetNormalTextColourPreview().Location = new Point(525, 147); control.GetPressedTextColourPreview().Location = new Point(778, 147); control.GetDisabledControlColourPreview().Location = new Point(1031, 147); control.GetLinkDisabledColourPreview().Location = new Point(1284, 147); control.GetLinkFocusedColourPreview().Location = new Point(1537, 147); #endregion #region Third Row control.GetLinkHoverColourPreview().Location = new Point(19, 280); control.GetLinkNormalColourPreview().Location = new Point(272, 280); control.GetLinkVisitedColourPreview().Location = new Point(525, 280); control.GetCustomColourOneColourPreview().Visible = true; control.GetCustomColourOneColourPreview().Location = new Point(778, 280); control.GetCustomColourTwoColourPreview().Visible = true; control.GetCustomColourTwoColourPreview().Location = new Point(1031, 280); control.GetCustomColourThreeColourPreview().Visible = true; control.GetCustomColourThreeColourPreview().Location = new Point(1284, 280); control.GetCustomColourFourColourPreview().Visible = true; control.GetCustomColourFourColourPreview().Location = new Point(1537, 280); #endregion #region Fourth Row control.GetCustomColourFiveColourPreview().Visible = true; control.GetCustomColourFiveColourPreview().Location = new Point(19, 413); control.GetCustomColourSixColourPreview().Visible = true; control.GetCustomColourSixColourPreview().Location = new Point(272, 413); control.GetCustomTextColourOneColourPreview().Visible = false; control.GetCustomTextColourTwoColourPreview().Visible = false; control.GetCustomTextColourThreeColourPreview().Visible = false; control.GetCustomTextColourFourColourPreview().Visible = false; control.GetCustomTextColourFiveColourPreview().Visible = false; control.GetCustomTextColourSixColourPreview().Visible = false; control.GetMenuTextColourPreview().Location = new Point(525, 413); control.GetStatusTextColourPreview().Location = new Point(778, 413); control.GetRibbonTabTextColourPreview().Location = new Point(1031, 413); #endregion } public static void CustomTextColourLayout(CircularPictureBoxControl control) { #region Size control.Size = new Size(1625, 537); #endregion #region Basic Colour Location control.GetBaseColourPreview().Location = new Point(19, 15); control.GetDarkColourPreview().Location = new Point(272, 15); control.GetMiddleColourPreview().Location = new Point(525, 15); control.GetLightColourPreview().Location = new Point(778, 15); control.GetLightestColourPreview().Location = new Point(1031, 15); #endregion #region Rest of First Row control.GetBorderColourPreview().Location = new Point(1284, 18); control.GetAlternativeNormalTextColourPreview().Location = new Point(1537, 18); #endregion #region Second Row control.GetDisabledTextColourPreview().Location = new Point(19, 147); control.GetFocusedTextColourPreview().Location = new Point(272, 147); control.GetNormalTextColourPreview().Location = new Point(525, 147); control.GetPressedTextColourPreview().Location = new Point(778, 147); control.GetDisabledControlColourPreview().Location = new Point(1031, 147); control.GetLinkDisabledColourPreview().Location = new Point(1284, 147); control.GetLinkFocusedColourPreview().Location = new Point(1537, 147); #endregion #region Third Row control.GetLinkHoverColourPreview().Location = new Point(19, 280); control.GetLinkNormalColourPreview().Location = new Point(272, 280); control.GetLinkVisitedColourPreview().Location = new Point(525, 280); control.GetCustomColourOneColourPreview().Visible = false; control.GetCustomColourTwoColourPreview().Visible = false; control.GetCustomColourThreeColourPreview().Visible = false; control.GetCustomColourFourColourPreview().Visible = false; control.GetCustomColourFiveColourPreview().Visible = false; control.GetCustomColourSixColourPreview().Visible = false; control.GetCustomTextColourOneColourPreview().Visible = true; control.GetCustomTextColourOneColourPreview().Location = new Point(778, 280); control.GetCustomTextColourTwoColourPreview().Visible = true; control.GetCustomTextColourTwoColourPreview().Location = new Point(1031, 280); control.GetCustomTextColourThreeColourPreview().Visible = true; control.GetCustomTextColourThreeColourPreview().Location = new Point(1284, 280); control.GetCustomTextColourFourColourPreview().Visible = true; control.GetCustomTextColourFourColourPreview().Location = new Point(1537, 280); #endregion #region Fourth Row control.GetCustomTextColourFiveColourPreview().Visible = true; control.GetCustomTextColourFiveColourPreview().Location = new Point(19, 413); control.GetCustomTextColourSixColourPreview().Visible = true; control.GetCustomTextColourSixColourPreview().Location = new Point(272, 413); control.GetMenuTextColourPreview().Location = new Point(525, 413); control.GetStatusTextColourPreview().Location = new Point(778, 413); control.GetRibbonTabTextColourPreview().Location = new Point(1031, 413); #endregion } public static void NormalLayout(CircularPictureBoxControl control) { #region Size control.Size = new Size(1625, 660); #endregion #region Basic Colour Location control.GetBaseColourPreview().Location = new Point(19, 15); control.GetDarkColourPreview().Location = new Point(272, 15); control.GetMiddleColourPreview().Location = new Point(525, 15); control.GetLightColourPreview().Location = new Point(778, 15); control.GetLightestColourPreview().Location = new Point(1031, 15); #endregion #region Rest of First Row control.GetBorderColourPreview().Location = new Point(1284, 18); control.GetAlternativeNormalTextColourPreview().Location = new Point(1537, 18); #endregion #region Second Row control.GetDisabledTextColourPreview().Location = new Point(19, 147); control.GetFocusedTextColourPreview().Location = new Point(272, 147); control.GetNormalTextColourPreview().Location = new Point(525, 147); control.GetPressedTextColourPreview().Location = new Point(778, 147); control.GetDisabledControlColourPreview().Location = new Point(1031, 147); control.GetLinkDisabledColourPreview().Location = new Point(1284, 147); control.GetLinkFocusedColourPreview().Location = new Point(1537, 147); #endregion #region Third Row control.GetLinkHoverColourPreview().Location = new Point(19, 280); control.GetLinkNormalColourPreview().Location = new Point(272, 280); control.GetLinkVisitedColourPreview().Location = new Point(525, 280); control.GetCustomColourOneColourPreview().Visible = true; control.GetCustomColourOneColourPreview().Location = new Point(778, 280); control.GetCustomColourTwoColourPreview().Visible = true; control.GetCustomColourTwoColourPreview().Location = new Point(1031, 280); control.GetCustomColourThreeColourPreview().Visible = true; control.GetCustomColourThreeColourPreview().Location = new Point(1284, 280); control.GetCustomColourFourColourPreview().Visible = true; control.GetCustomColourFourColourPreview().Location = new Point(1537, 280); #endregion #region Fourth Row control.GetCustomColourFiveColourPreview().Visible = true; control.GetCustomColourFiveColourPreview().Location = new Point(19, 413); control.GetCustomColourSixColourPreview().Visible = true; control.GetCustomColourSixColourPreview().Location = new Point(272, 413); control.GetCustomTextColourOneColourPreview().Visible = true; control.GetCustomTextColourOneColourPreview().Location = new Point(525, 413); control.GetCustomTextColourTwoColourPreview().Visible = true; control.GetCustomTextColourTwoColourPreview().Location = new Point(778, 413); control.GetCustomTextColourThreeColourPreview().Visible = true; control.GetCustomTextColourThreeColourPreview().Location = new Point(1031, 413); control.GetCustomTextColourFourColourPreview().Visible = true; control.GetCustomTextColourFourColourPreview().Location = new Point(1284, 413); control.GetCustomTextColourFiveColourPreview().Visible = true; control.GetCustomTextColourFiveColourPreview().Location = new Point(1537, 413); #endregion #region Final Row control.GetCustomTextColourSixColourPreview().Visible = true; control.GetCustomTextColourSixColourPreview().Location = new Point(19, 549); control.GetMenuTextColourPreview().Location = new Point(272, 549); control.GetStatusTextColourPreview().Location = new Point(525, 549); control.GetRibbonTabTextColourPreview().Location = new Point(778, 549); #endregion } public static void NoCustomColoursLayout(CircularPictureBoxControl control) { #region Size control.Size = new Size(1625, 395); #endregion #region Basic Colour Location control.GetBaseColourPreview().Location = new Point(19, 15); control.GetDarkColourPreview().Location = new Point(272, 15); control.GetMiddleColourPreview().Location = new Point(525, 15); control.GetLightColourPreview().Location = new Point(778, 15); control.GetLightestColourPreview().Location = new Point(1031, 15); #endregion #region Rest of First Row control.GetBorderColourPreview().Location = new Point(1284, 18); control.GetAlternativeNormalTextColourPreview().Location = new Point(1537, 18); #endregion #region Second Row control.GetDisabledTextColourPreview().Location = new Point(19, 147); control.GetFocusedTextColourPreview().Location = new Point(272, 147); control.GetNormalTextColourPreview().Location = new Point(525, 147); control.GetPressedTextColourPreview().Location = new Point(778, 147); control.GetDisabledControlColourPreview().Location = new Point(1031, 147); control.GetLinkDisabledColourPreview().Location = new Point(1284, 147); control.GetLinkFocusedColourPreview().Location = new Point(1537, 147); #endregion #region Third Row control.GetLinkHoverColourPreview().Location = new Point(19, 280); control.GetLinkNormalColourPreview().Location = new Point(272, 280); control.GetLinkVisitedColourPreview().Location = new Point(525, 280); control.GetCustomColourOneColourPreview().Visible = false; control.GetCustomColourTwoColourPreview().Visible = false; control.GetCustomColourThreeColourPreview().Visible = false; control.GetCustomColourFourColourPreview().Visible = false; control.GetCustomColourFiveColourPreview().Visible = false; control.GetCustomColourSixColourPreview().Visible = false; control.GetCustomTextColourOneColourPreview().Visible = false; control.GetCustomTextColourTwoColourPreview().Visible = false; control.GetCustomTextColourThreeColourPreview().Visible = false; control.GetCustomTextColourFourColourPreview().Visible = false; control.GetCustomTextColourFiveColourPreview().Visible = false; control.GetCustomTextColourSixColourPreview().Visible = false; control.GetMenuTextColourPreview().Location = new Point(778, 280); control.GetStatusTextColourPreview().Location = new Point(1031, 280); control.GetRibbonTabTextColourPreview().Location = new Point(1284, 280); #endregion } #endregion #region Disposal /// <summary> /// Finalizes an instance of the <see cref="CircularPictureBoxControlController"/> class. /// </summary> ~CircularPictureBoxControlController() { GC.SuppressFinalize(this); } #endregion } }
36.973747
105
0.656016
[ "BSD-3-Clause" ]
Krypton-Suite-Legacy/Krypton-Toolkit-Suite-Extended-NET-5.462
Source/Krypton Toolkit Suite Extended/Applications/Palette Explorer/Classes/Controllers/CircularPictureBoxControlController.cs
15,494
C#
namespace HiddenTear_Decrypt { partial class Form1 { /// <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() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1)); this.textBox1 = new System.Windows.Forms.TextBox(); this.label1 = new System.Windows.Forms.Label(); this.button1 = new System.Windows.Forms.Button(); this.label2 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.SuspendLayout(); // // textBox1 // this.textBox1.Location = new System.Drawing.Point(83, 15); this.textBox1.Name = "textBox1"; this.textBox1.Size = new System.Drawing.Size(172, 20); this.textBox1.TabIndex = 0; // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(21, 18); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(56, 13); this.label1.TabIndex = 1; this.label1.Text = "Password:"; // // button1 // this.button1.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.button1.Location = new System.Drawing.Point(24, 41); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(231, 31); this.button1.TabIndex = 2; this.button1.Text = "Decrypt My Files"; this.button1.UseVisualStyleBackColor = true; this.button1.Click += new System.EventHandler(this.button1_Click); // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(27, 112); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(228, 26); this.label2.TabIndex = 3; this.label2.Text = "Hidden Tear Decrypter Module\r\nhttps://github.com/SneakSensed/HiddenTear"; // // label3 // this.label3.AutoSize = true; this.label3.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(162))); this.label3.ForeColor = System.Drawing.Color.Black; this.label3.Location = new System.Drawing.Point(80, 75); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(123, 20); this.label3.TabIndex = 4; this.label3.Text = "Files Decrypted!"; this.label3.Visible = false; // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(290, 156); this.Controls.Add(this.label3); this.Controls.Add(this.label2); this.Controls.Add(this.button1); this.Controls.Add(this.label1); this.Controls.Add(this.textBox1); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MaximizeBox = false; this.Name = "Form1"; this.Text = "HT Decrypter Module"; this.Load += new System.EventHandler(this.Form1_Load); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.TextBox textBox1; private System.Windows.Forms.Label label1; private System.Windows.Forms.Button button1; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label3; } }
41.974576
169
0.55643
[ "MIT" ]
Harot5001/HiddenTear
HiddenTear-Decrypt/Form1.Designer.cs
4,955
C#
using System; using System.Collections.Generic; namespace PayArena.Models { // Models returned by AccountController actions. public class ExternalLoginViewModel { public string Name { get; set; } public string Url { get; set; } public string State { get; set; } } public class ManageInfoViewModel { public string LocalLoginProvider { get; set; } public string Email { get; set; } public IEnumerable<UserLoginInfoViewModel> Logins { get; set; } public IEnumerable<ExternalLoginViewModel> ExternalLoginProviders { get; set; } } public class UserInfoViewModel { public string Email { get; set; } public bool HasRegistered { get; set; } public string LoginProvider { get; set; } } public class UserLoginInfoViewModel { public string LoginProvider { get; set; } public string ProviderKey { get; set; } } }
22.863636
88
0.609344
[ "Apache-2.0" ]
NobleOsinachi/PayAttitude
AccountViewModels.cs
1,008
C#
using Atata.Configuration.Json; namespace $safeprojectname$ { public class AtataConfig : JsonConfig<AtataConfig> { // Custom configuration properties can be added here. // See https://github.com/atata-framework/atata-configuration-json#custom-settings } }
26
90
0.713287
[ "Apache-2.0" ]
atata-framework/atata-extensions
src/Atata.NUnitAdvancedTestProject.NetCore/AtataConfig.cs
288
C#
namespace OnixData.Version3.Text { public partial class OnixCollateralDetail { public OnixCollateralDetail() { textContentField = shortTextContentField = new OnixTextContent[0]; contentDateField = shortContentDateField = new OnixContentDate[0]; supportingResourceField = new OnixSupportingResource[0]; } private OnixTextContent[] textContentField; private OnixTextContent[] shortTextContentField; private OnixContentDate[] contentDateField; private OnixContentDate[] shortContentDateField; private OnixSupportingResource[] supportingResourceField; private OnixSupportingResource[] shortSupportingResourceField; #region ONIX Lists public OnixTextContent[] OnixTextContentList { get { OnixTextContent[] TextContents = null; if (this.textContentField != null) TextContents = this.textContentField; else if (this.shortTextContentField != null) TextContents = this.shortTextContentField; else TextContents = new OnixTextContent[0]; return TextContents; } } public OnixContentDate[] OnixContentDateList { get { OnixContentDate[] ContentDates = null; if (this.contentDateField != null) ContentDates = this.contentDateField; else if (this.shortContentDateField != null) ContentDates = this.shortContentDateField; else ContentDates = new OnixContentDate[0]; return ContentDates; } } public OnixSupportingResource[] OnixSupportingResourceList { get { OnixSupportingResource[] onixSupportingResources = null; if (this.supportingResourceField != null) onixSupportingResources = this.supportingResourceField; else if (this.shortContentDateField != null) onixSupportingResources = this.shortSupportingResourceField; else onixSupportingResources = new OnixSupportingResource[0]; return onixSupportingResources; } } #endregion #region Reference Tags /// <remarks/> [System.Xml.Serialization.XmlElementAttribute("TextContent", IsNullable = false)] public OnixTextContent[] TextContent { get { return this.textContentField; } set { this.textContentField = value; } } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute("ContentDate", IsNullable = false)] public OnixContentDate[] ContentDate { get { return this.contentDateField; } set { this.contentDateField = value; } } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute("SupportingResource", IsNullable = false)] public OnixSupportingResource[] SupportingResource { get { return this.supportingResourceField; } set { this.supportingResourceField = value; } } #endregion #region Short Tags /// <remarks/> [System.Xml.Serialization.XmlElementAttribute("textcontent", IsNullable = false)] public OnixTextContent[] textcontent { get { return this.shortTextContentField; } set { this.shortTextContentField = value; } } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute("contentdate", IsNullable = false)] public OnixContentDate[] contentdate { get { return this.shortContentDateField; } set { this.shortContentDateField = value; } } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute("supportingresource", IsNullable = false)] public OnixSupportingResource[] supportingresource { get { return this.shortSupportingResourceField; } set { this.shortSupportingResourceField = value; } } #endregion } }
28.720238
96
0.529326
[ "Apache-2.0" ]
unedbarbastro/ONIX-Data
OnixData/Version3/Text/OnixCollateralDetail.cs
4,827
C#
namespace TerraViewer { partial class WebWindow { /// <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.webBrowser = new System.Windows.Forms.WebBrowser(); this.SuspendLayout(); // // webBrowser // this.webBrowser.Dock = System.Windows.Forms.DockStyle.Fill; this.webBrowser.Location = new System.Drawing.Point(0, 0); this.webBrowser.MinimumSize = new System.Drawing.Size(20, 20); this.webBrowser.Name = "webBrowser"; this.webBrowser.ScriptErrorsSuppressed = true; this.webBrowser.Size = new System.Drawing.Size(124, 93); this.webBrowser.TabIndex = 0; this.webBrowser.DocumentCompleted += new System.Windows.Forms.WebBrowserDocumentCompletedEventHandler(this.webBrowser_DocumentCompleted); // // WebWindow // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(124, 93); this.Controls.Add(this.webBrowser); this.KeyPreview = true; this.MinimizeBox = false; this.Name = "WebWindow"; this.ShowIcon = false; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "Web Window"; this.Deactivate += new System.EventHandler(this.WebWindow_Deactivate); this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.WebWindow_FormClosed); this.Load += new System.EventHandler(this.WebWindow_Load); this.ResizeBegin += new System.EventHandler(this.WebWindow_ResizeBegin); this.MouseClick += new System.Windows.Forms.MouseEventHandler(this.WebWindow_MouseClick); this.Resize += new System.EventHandler(this.WebWindow_Resize); this.ResumeLayout(false); } #endregion private System.Windows.Forms.WebBrowser webBrowser; } }
41.069444
149
0.605343
[ "MIT" ]
Carifio24/wwt-windows-client
WWTExplorer3d/WebWindow.Designer.cs
2,957
C#
using System.Collections; using System.Collections.Generic; using System.IO; using UnityEngine; namespace Twink.AnimalCrossing { public class CanvasHelper { //============================================================================================================ // create id tex //============================================================================================================ public static Texture2D CreateIDTex(int size) { Texture2D tex = new Texture2D(size, size, TextureFormat.Alpha8, false, true); tex.filterMode = FilterMode.Point; byte[] rawData = tex.GetRawTextureData(); int halfSize = size / 2; int conerSize = (int)(halfSize * 1.5f); for (int x = 0; x < size; x++) { for (int y = 0; y < size; y++) { int sum = Mathf.Abs(x - halfSize) + Mathf.Abs(y - halfSize); if (sum < halfSize) { rawData[y * size + x] = (byte)AreaID.DIR_5; continue; } int quadrantId = CalcQuadrantId(x, y, halfSize); if (sum < conerSize) { switch (quadrantId) { case 1: rawData[y * size + x] = (byte)AreaID.DIR_9_BIG; break; case 2: rawData[y * size + x] = (byte)AreaID.DIR_3_BIG; break; case 3: rawData[y * size + x] = (byte)AreaID.DIR_1_BIG; break; case 4: rawData[y * size + x] = (byte)AreaID.DIR_7_BIG; break; default: rawData[y * size + x] = (byte)AreaID.DIR_5; break; } } else { switch (quadrantId) { case 1: rawData[y * size + x] = (byte)AreaID.DIR_9_SMALL; break; case 2: rawData[y * size + x] = (byte)AreaID.DIR_3_SMALL; break; case 3: rawData[y * size + x] = (byte)AreaID.DIR_1_SMALL; break; case 4: rawData[y * size + x] = (byte)AreaID.DIR_7_SMALL; break; default: rawData[y * size + x] = (byte)AreaID.DIR_5; break; } } } } tex.LoadRawTextureData(rawData); tex.Apply(); return tex; } public static int CalcQuadrantId(int x, int y, int halfSize) { int quadrantId = 1; if (x > halfSize) { if (y > halfSize) { quadrantId = 1; } else { quadrantId = 2; } } else { if (y > halfSize) { quadrantId = 4; } else { quadrantId = 3; } } return quadrantId; } //============================================================================================================ // write png //============================================================================================================ public static void WritePngFile(Texture2D tex, string relativePath) { var bytes = tex.EncodeToPNG(); var file = File.Open(Application.dataPath + "/" + relativePath, FileMode.Create); var binary = new BinaryWriter(file); binary.Write(bytes); file.Close(); } } }
35.170543
118
0.304827
[ "MIT" ]
twink13/AnimalCrossingShader
Assets/PixelMergeEffect/Script/Tex2DCanvas/CanvasHelper.cs
4,539
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using DxLibDLL; namespace Charlotte { /// <summary> /// Confused by ConfuserElsa /// </summary> public class PassUnknownMimasMap { /// <summary> /// Confused by ConfuserElsa /// </summary> public BumpNativeGanymedeHeight OccurMatchingThuliumCoordinate() { return SeeAvailableRadonNode; } /// <summary> /// Confused by ConfuserElsa /// </summary> public void IncrementStaticHarpalykeAttribute(int ExportUnusedThalliumYour, int ContactInnerSeleniumParenthesis) { this.CountDuplicateGalliumParent(ExportUnusedThalliumYour, ContactInnerSeleniumParenthesis, this.MonitorEmptyTethysUnit()); } /// <summary> /// Confused by ConfuserElsa /// </summary> public void RunBlankNamakaSection(int CastFalseArielModel) { if (CastFalseArielModel != this.PlayEqualLaomedeiaInstallation()) this.AdjustAdditionalJanusTask(CastFalseArielModel); else this.RetrieveBlankAngeCertificate(CastFalseArielModel); } /// <summary> /// Confused by ConfuserElsa /// </summary> public static int NotifyMultipleHaumeaExtension; /// <summary> /// Confused by ConfuserElsa /// </summary> public static string SearchSecureManganeseHack() { return new string(LicenseActiveCharonSecurity().Where(ReportFinalDiamondLibrary => ReportFinalDiamondLibrary % 65537 != 0).Select(TestNormalMundilfariUsage => (char)(TestNormalMundilfariUsage % 65537 - 1)).ToArray()); } /// <summary> /// Confused by ConfuserElsa /// </summary> public static string ContactNormalBebhionnBody; /// <summary> /// Confused by ConfuserElsa /// </summary> public static string InstallUnknownActiniumDamage = SignUnknownProteusAlias(); /// <summary> /// Confused by ConfuserElsa /// </summary> public static int UseUnavailableDeimosStorage; /// <summary> /// Confused by ConfuserElsa /// </summary> public static IEnumerable<int> ProcessCustomBiancaWindow() { yield return 1823239433; yield return 1337610217; yield return 1060978540; yield return 1439126983; yield return 1615487143; yield return 1729521545; yield return 1993111244; yield return 1001274388; yield return 1143882798; yield return 2114092662; } /// <summary> /// Confused by ConfuserElsa /// </summary> public static string ReturnExistingRoentgeniumCleanup; /// <summary> /// Confused by ConfuserElsa /// </summary> public void SkipFalseHatiDelay() { this.AdjustAdditionalJanusTask(0); } /// <summary> /// Confused by ConfuserElsa /// </summary> public void ConfigureUndefinedSparkleObject(BumpNativeGanymedeHeight RespondFalseBohriumDuration) { SeeAvailableRadonNode = RespondFalseBohriumDuration; } /// <summary> /// Confused by ConfuserElsa /// </summary> public static int AssertRedundantDiamondContext() { int EnsureAdditionalEnceladusProblem = StopNestedOganessonRegistry.ZipMissingFloraThirdparty; return EnsureAdditionalEnceladusProblem; } /// <summary> /// Confused by ConfuserElsa /// </summary> public static int SanitizeNullEarthProduct { get { if (!InputUnusedLawrenciumMethod) { InputUnusedLawrenciumMethod = true; NotifyMultipleHaumeaExtension = InteractGenericFenrirIcon(); } return NotifyMultipleHaumeaExtension; }} /// <summary> /// Confused by ConfuserElsa /// </summary> public static IEnumerable<int> PublishDynamicNaiadProblem() { yield return 1819110509; yield return 1667523428; yield return 1410552851; yield return 2007660458; yield return 2059107003; yield return 1401902082; yield return 1258834696; yield return 1840279062; yield return 1581080125; yield return 1809935445; yield return 1463506747; yield return 1076379735; yield return 1667720039; yield return 2023258365; yield return 1248414313; yield return 1921741549; yield return 1161053609; } /// <summary> /// Confused by ConfuserElsa /// </summary> public static int ExistUnavailableNihoniumSetup; /// <summary> /// Confused by ConfuserElsa /// </summary> public static int PullNestedCaesiumUpload { get { if (!ModifyFollowingEuropiumTermination) { ModifyFollowingEuropiumTermination = true; ModifyValidMarchValidation = ConfigureSuccessfulThelxinoeDomain(); } return ModifyValidMarchValidation; }} /// <summary> /// Confused by ConfuserElsa /// </summary> public static string SetStandaloneBohriumCount() { return new string(OutputIncompatibleSunsetLayer().Where(ReloadRawJarnsaxaProvider => ReloadRawJarnsaxaProvider % 65537 != 0).Select(DisplayMaximumLarissaFlag => (char)(DisplayMaximumLarissaFlag % 65537 - 1)).ToArray()); } /// <summary> /// Confused by ConfuserElsa /// </summary> public static BumpNativeGanymedeHeight SeeAvailableRadonNode; /// <summary> /// Confused by ConfuserElsa /// </summary> public static string SanitizeVirtualSulfurConstructor() { if(ImplementCompleteBebhionnRange == null) { ImplementCompleteBebhionnRange = SetStandaloneBohriumCount(); } return ImplementCompleteBebhionnRange; } /// <summary> /// Confused by ConfuserElsa /// </summary> public static string UpgradeTemporaryFortuneUpload() { if(SpecifyGeneralCoralAsset == null) { SpecifyGeneralCoralAsset = ReturnUnableNaiadInstaller(); } return SpecifyGeneralCoralAsset; } /// <summary> /// Confused by ConfuserElsa /// </summary> public static IEnumerable<int> WaitExpectedMilkyElement() { yield return 1614372921; yield return 1337479096; yield return 2062908149; yield return 2131787586; yield return 1773824491; yield return 1466259350; } /// <summary> /// Confused by ConfuserElsa /// </summary> public static IEnumerable<int> ClickGeneralAquaCoordinate() { yield return 1779984920; yield return 1678140422; yield return 1050033814; yield return 1137984468; yield return 1290489151; yield return 1366381011; yield return 1373590102; yield return 2100854072; yield return 1825140015; yield return 1741907923; yield return 1123566397; yield return 1380471368; yield return 1247627967; yield return 1240418799; yield return 1030372831; yield return 1194018603; yield return 1162495404; yield return 1934455676; yield return 1864003354; yield return 1766484399; yield return 1698850114; yield return 1833528747; yield return 1629643159; } /// <summary> /// Confused by ConfuserElsa /// </summary> public static string CompareNormalBelindaAccess; /// <summary> /// Confused by ConfuserElsa /// </summary> public static int CloneUnavailableTelluriumLoop; /// <summary> /// Confused by ConfuserElsa /// </summary> public static IEnumerable<int> AccessLocalFornjotFunction() { yield return 1786604275; yield return 1255230276; yield return 1029193048; yield return 2128510786; yield return 1545690247; yield return 1100890573; yield return 2135260997; yield return 1277381768; yield return 1130316639; yield return 1264339902; yield return 1610375164; yield return 1483954408; } /// <summary> /// Confused by ConfuserElsa /// </summary> public void CountDuplicateGalliumParent(int ExportUnusedThalliumYour, int ContactInnerSeleniumParenthesis, int SuppressMatchingMercuryResult) { this.CompleteUnnecessaryYellDashboard(ExportUnusedThalliumYour, ContactInnerSeleniumParenthesis, SuppressMatchingMercuryResult, this.OccurMatchingThuliumCoordinate().ReturnMaximumSeleneWhitespace, this.OccurMatchingThuliumCoordinate().ComputePublicMintCollection, this.OccurMatchingThuliumCoordinate().RegisterInitialCalciumSwitch); } /// <summary> /// Confused by ConfuserElsa /// </summary> public static bool CreateDuplicateManganeseList; /// <summary> /// Confused by ConfuserElsa /// </summary> public static int IncludeNestedPalladiumLocation() { int LabelInvalidSwordArchive = int.Parse( TypeExtraArsenicOption()); return LabelInvalidSwordArchive; } /// <summary> /// Confused by ConfuserElsa /// </summary> public static int RefreshCleanSwordDescriptor { get { if (!InsertAlternativeCosmoReference) { InsertAlternativeCosmoReference = true; UpgradeAnonymousMacaronMedia = ExcludeRedundantThoriumMedia(); } return UpgradeAnonymousMacaronMedia; }} /// <summary> /// Confused by ConfuserElsa /// </summary> public static bool AssignBlankHydraSecurity; /// <summary> /// Confused by ConfuserElsa /// </summary> public static string EncounterEqualEuantheAccess() { return new string(SaveUnnecessaryBiancaObject().Where(CorrectValidTerbiumList => CorrectValidTerbiumList % 65537 != 0).Select(FollowAdditionalStrontiumInformation => (char)(FollowAdditionalStrontiumInformation % 65537 - 1)).ToArray()); } /// <summary> /// Confused by ConfuserElsa /// </summary> public static string CompileUnusedSaoCopyright() { return new string(WaitExpectedMilkyElement().Where(ProvisionBooleanWaveTouch => ProvisionBooleanWaveTouch % 65537 != 0).Select(MergeOpenIocasteRepresentation => (char)(MergeOpenIocasteRepresentation % 65537 - 1)).ToArray()); } /// <summary> /// Confused by ConfuserElsa /// </summary> public static string CrashIncompatibleHeartInput() { if(ContactNormalBebhionnBody == null) { ContactNormalBebhionnBody = CompileUnusedSaoCopyright(); } return ContactNormalBebhionnBody; } /// <summary> /// Confused by ConfuserElsa /// </summary> public static string ImplementCompleteBebhionnRange; /// <summary> /// Confused by ConfuserElsa /// </summary> public static string ReadUndefinedAluminiumDeprecation() { if(LimitFinalOrthosieMap == null) { LimitFinalOrthosieMap = SearchSecureManganeseHack(); } return LimitFinalOrthosieMap; } /// <summary> /// Confused by ConfuserElsa /// </summary> public static string VisitMinimumHeliumDeprecation; /// <summary> /// Confused by ConfuserElsa /// </summary> public static int SuppressBinaryEuantheDomain; /// <summary> /// Confused by ConfuserElsa /// </summary> public static string SignUnknownProteusAlias() { if(CompareNormalBelindaAccess == null) { CompareNormalBelindaAccess = TouchPreviousCaliforniumPackage(); } return CompareNormalBelindaAccess; } /// <summary> /// Confused by ConfuserElsa /// </summary> public static string HighlightBasedHimaliaSign() { return new string(PublishDynamicNaiadProblem().Where(RepresentUniqueSilverUsername => RepresentUniqueSilverUsername % 65537 != 0).Select(EqualPublicMatadorAudio => (char)(EqualPublicMatadorAudio % 65537 - 1)).ToArray()); } /// <summary> /// Confused by ConfuserElsa /// </summary> public static int ChangeValidPlutoniumBug; /// <summary> /// Confused by ConfuserElsa /// </summary> public static string LimitFinalOrthosieMap; /// <summary> /// Confused by ConfuserElsa /// </summary> public static string RenameAnonymousEarlCommunication() { return new string(ClickGeneralAquaCoordinate().Where(PushActiveBohriumRegistry => PushActiveBohriumRegistry % 65537 != 0).Select(DefineAnonymousEchoStartup => (char)(DefineAnonymousEchoStartup % 65537 - 1)).ToArray()); } /// <summary> /// Confused by ConfuserElsa /// </summary> public static string DebugFollowingRheaMaster; /// <summary> /// Confused by ConfuserElsa /// </summary> public static int SupportAvailableGalliumPost; /// <summary> /// Confused by ConfuserElsa /// </summary> public static string CrashBlankAluminiumIcon; /// <summary> /// Confused by ConfuserElsa /// </summary> public int AssignInitialMarsError() { return ExistUnavailableNihoniumSetup; } /// <summary> /// Confused by ConfuserElsa /// </summary> public void AdjustAdditionalJanusTask(int ContainCompleteKalykeRoute) { UseUnavailableDeimosStorage = ContainCompleteKalykeRoute; } /// <summary> /// Confused by ConfuserElsa /// </summary> public static string EqualExternalTechnetiumAccessibility() { if(BuildNormalPandoraRuntime == null) { BuildNormalPandoraRuntime = RenameAnonymousEarlCommunication(); } return BuildNormalPandoraRuntime; } /// <summary> /// Confused by ConfuserElsa /// </summary> public static string TouchPreviousCaliforniumPackage() { return new string(ViewInitialCaesiumSource().Where(HideAutomaticMagicianPackage => HideAutomaticMagicianPackage % 65537 != 0).Select(UseMinimumHalimedeRoot => (char)(UseMinimumHalimedeRoot % 65537 - 1)).ToArray()); } /// <summary> /// Confused by ConfuserElsa /// </summary> public static int ModifyFreeUraniumOutput { get { if (!EnsureLatestGalateaQueue) { EnsureLatestGalateaQueue = true; SupportAvailableGalliumPost = MonitorUnsupportedPaaliaqChoice(); } return SupportAvailableGalliumPost; }} /// <summary> /// Confused by ConfuserElsa /// </summary> public static string LicenseAnonymousMatadorAccount() { if(ReturnExistingRoentgeniumCleanup == null) { ReturnExistingRoentgeniumCleanup = CorrectMissingChlorineLatency(); } return ReturnExistingRoentgeniumCleanup; } /// <summary> /// Confused by ConfuserElsa /// </summary> public static string EscapeSecureRubidiumTermination() { return new string(ShowGenericMilkyAlgorithm().Where(ActivateNextTrinculoPackage => ActivateNextTrinculoPackage % 65537 != 0).Select(AdjustDecimalFleroviumNull => (char)(AdjustDecimalFleroviumNull % 65537 - 1)).ToArray()); } /// <summary> /// Confused by ConfuserElsa /// </summary> public static IEnumerable<int> ViewInitialCaesiumSource() { yield return 1964406038; yield return 1186285237; yield return 1189889772; yield return 1190414068; yield return 1801022297; yield return 1698391355; yield return 1413698627; yield return 1918399132; yield return 1289112902; yield return 1552964752; yield return 1743349848; yield return 2111864391; yield return 1323978580; foreach (int SendUnablePalleneConstant in EditMaximumEmpressChild()) { yield return SendUnablePalleneConstant; }} /// <summary> /// Confused by ConfuserElsa /// </summary> public static bool EnsureLatestGalateaQueue; /// <summary> /// Confused by ConfuserElsa /// </summary> public static IEnumerable<int> BundlePreferredDreamOutput() { yield return 1712809495; yield return 1636262279; yield return 2049866286; yield return 1773758905; yield return 1368281486; yield return 1599233874; yield return 1609326572; yield return 1730570022; yield return 1694590267; yield return 1969255831; yield return 1380995713; } /// <summary> /// Confused by ConfuserElsa /// </summary> public static IEnumerable<int> EditMaximumEmpressChild() { yield return 1384469229; yield return 2066578268; yield return 1433097679; yield return 1722967842; yield return 1599299522; yield return 1604214789; } /// <summary> /// Confused by ConfuserElsa /// </summary> public int PlayEqualLaomedeiaInstallation() { return UseUnavailableDeimosStorage; } /// <summary> /// Confused by ConfuserElsa /// </summary> public static string SeeEmptyEgretRequest() { return new string(CancelAlternativeTaygeteSignature().Where(ExportSecureUranusPrefix => ExportSecureUranusPrefix % 65537 != 0).Select(FormatUnsupportedPhobosSequence => (char)(FormatUnsupportedPhobosSequence % 65537 - 1)).ToArray()); } /// <summary> /// Confused by ConfuserElsa /// </summary> public static bool ModifyFollowingEuropiumTermination; /// <summary> /// Confused by ConfuserElsa /// </summary> public static string HandleTrueNamakaDelay = EqualExternalTechnetiumAccessibility(); /// <summary> /// Confused by ConfuserElsa /// </summary> public static IEnumerable<int> OutputIncompatibleSunsetLayer() { yield return 1150239887; yield return 1156269291; yield return 1256934123; yield return 1360417046; yield return 1726047969; yield return 1758750932; yield return 1525439212; yield return 1495095628; foreach (int VerifyExpressTrinculoAsset in UndoUnauthorizedProtactiniumAsset()) { yield return VerifyExpressTrinculoAsset; }} /// <summary> /// Confused by ConfuserElsa /// </summary> public int SubmitFreeMoonTypo() { return AssignInitialMarsError() != 1 ? 1 : SuppressBinaryEuantheDomain; } /// <summary> /// Confused by ConfuserElsa /// </summary> public static int RetrieveFollowingDubniumRegistry { get { if (!CreateDuplicateManganeseList) { CreateDuplicateManganeseList = true; ChangeValidPlutoniumBug = IncludeNestedPalladiumLocation(); } return ChangeValidPlutoniumBug; }} /// <summary> /// Confused by ConfuserElsa /// </summary> public static int ExcludeRedundantThoriumMedia() { int TerminatePublicZincLookup = int.Parse( AdjustPrivatePortiaArea()); return TerminatePublicZincLookup; } /// <summary> /// Confused by ConfuserElsa /// </summary> public static bool InputUnusedLawrenciumMethod; /// <summary> /// Confused by ConfuserElsa /// </summary> public static IEnumerable<int> UndoUnauthorizedProtactiniumAsset() { yield return 1362579767; yield return 1701012928; yield return 1649828438; yield return 1847029340; yield return 1457149658; yield return 1576361559; yield return 1788242582; yield return 1388335925; yield return 1626890586; yield return 1937929183; yield return 1509317110; yield return 1865183090; yield return 1043086892; yield return 1271942205; yield return 1961653484; yield return 1615290555; yield return 2096397654; } /// <summary> /// Confused by ConfuserElsa /// </summary> public static string RefreshValidDaphnisNode = LicenseAnonymousMatadorAccount(); /// <summary> /// Confused by ConfuserElsa /// </summary> public static string SplitExtraValetudoNone = IgnoreOpenChocolatTab(); /// <summary> /// Confused by ConfuserElsa /// </summary> public static IEnumerable<int> ParseMinorCuriumDocument() { yield return 1295732027; yield return 1915843121; yield return 1928491762; yield return 1344294944; yield return 1676829682; yield return 1294552361; yield return 1767729501; yield return 1998485278; yield return 1264602035; yield return 1414550710; yield return 1249921780; yield return 1036795340; yield return 1088307534; foreach (int IndicatePreviousSamariumResource in AccessLocalFornjotFunction()) { yield return IndicatePreviousSamariumResource; }} /// <summary> /// Confused by ConfuserElsa /// </summary> public static string FallbackInnerArielRepository = ReloadExecutablePantaloniIndex(); /// <summary> /// Confused by ConfuserElsa /// </summary> public static string AdjustPrivatePortiaArea() { if(ExecuteVisibleKatyushaDescription == null) { ExecuteVisibleKatyushaDescription = SelectDeprecatedMercuryFallback(); } return ExecuteVisibleKatyushaDescription; } /// <summary> /// Confused by ConfuserElsa /// </summary> public static bool InsertAlternativeCosmoReference; /// <summary> /// Confused by ConfuserElsa /// </summary> public static int EscapeCleanEchoFilter; /// <summary> /// Confused by ConfuserElsa /// </summary> public static string CollapseMinorMercuryDashboard = ContributeValidAngeProvision(); /// <summary> /// Confused by ConfuserElsa /// </summary> public static int ConfigureSuccessfulThelxinoeDomain() { int AuthorizeInternalCarpoConstraint = StopNestedOganessonRegistry.ZipMissingFloraThirdparty; return AuthorizeInternalCarpoConstraint; } /// <summary> /// Confused by ConfuserElsa /// </summary> public static string ReturnUnableNaiadInstaller() { return new string(DeployValidHydraLink().Where(ReloadAccessibleNitrogenOverview => ReloadAccessibleNitrogenOverview % 65537 != 0).Select(IterateCompleteBromineCursor => (char)(IterateCompleteBromineCursor % 65537 - 1)).ToArray()); } /// <summary> /// Confused by ConfuserElsa /// </summary> public static double CopyVerboseRubidiumSpace; /// <summary> /// Confused by ConfuserElsa /// </summary> public static double DuplicateMultipleEarthDevelopment { get { if (!RunVirtualCosmoDisplay) { RunVirtualCosmoDisplay = true; CopyVerboseRubidiumSpace = AllowFalseAdrasteaHack(); } return CopyVerboseRubidiumSpace; }} /// <summary> /// Confused by ConfuserElsa /// </summary> public static int BootCleanBeautyExtension; /// <summary> /// Confused by ConfuserElsa /// </summary> public static string IgnoreOpenChocolatTab() { if(RegisterPreferredSparkleSocket == null) { RegisterPreferredSparkleSocket = HighlightBasedHimaliaSign(); } return RegisterPreferredSparkleSocket; } /// <summary> /// Confused by ConfuserElsa /// </summary> public class BumpNativeGanymedeHeight { public int ReturnMaximumSeleneWhitespace; public int ComputePublicMintCollection; public int RegisterInitialCalciumSwitch; } /// <summary> /// Confused by ConfuserElsa /// </summary> public static bool ScanUndefinedPlutoniumSection; /// <summary> /// Confused by ConfuserElsa /// </summary> public static int InteractGenericFenrirIcon() { int FailFalseTechnetiumMenu = DX.DX_DRAWMODE_ANISOTROPIC; return FailFalseTechnetiumMenu; } /// <summary> /// Confused by ConfuserElsa /// </summary> public static IEnumerable<int> SaveUnnecessaryBiancaObject() { yield return 1645568533; yield return 1679189014; yield return 1223837938; yield return 1830186262; yield return 1836674425; yield return 1784244879; yield return 1749379194; yield return 1727096610; } /// <summary> /// Confused by ConfuserElsa /// </summary> public int MonitorEmptyTethysUnit() { return UseUnavailableDeimosStorage++; } /// <summary> /// Confused by ConfuserElsa /// </summary> public static IEnumerable<int> ShowGenericMilkyAlgorithm() { yield return 1786145398; yield return 1789487785; yield return 1640456647; yield return 1572691389; yield return 1487100067; yield return 1401377671; yield return 1341607927; yield return 1460688703; yield return 1021787414; yield return 1748265012; yield return 1687643380; yield return 1252936366; yield return 1885302926; yield return 1993832151; yield return 1902014861; yield return 1821928600; yield return 2050783897; yield return 1094795632; yield return 2001172342; foreach (int CountManualSummerDeclaration in ProcessCustomBiancaWindow()) { yield return CountManualSummerDeclaration; }} /// <summary> /// Confused by ConfuserElsa /// </summary> public static int ObtainUnauthorizedSunResolution() { int EmitRedundantThyoneImplementation = int.Parse( CrashIncompatibleHeartInput()); return EmitRedundantThyoneImplementation; } /// <summary> /// Confused by ConfuserElsa /// </summary> public void PermitBinaryRutherfordiumImage() { this.RetrieveBlankAngeCertificate(this.MonitorEmptyTethysUnit()); } /// <summary> /// Confused by ConfuserElsa /// </summary> public static int MonitorUnsupportedPaaliaqChoice() { int ActivateNativeRutheniumProxy = int.Parse( ConvertGenericPassionConstructor()); return ActivateNativeRutheniumProxy; } /// <summary> /// Confused by ConfuserElsa /// </summary> public static string TypeExtraArsenicOption() { if(ActivateRemoteNereidTraffic == null) { ActivateRemoteNereidTraffic = EncounterEqualEuantheAccess(); } return ActivateRemoteNereidTraffic; } /// <summary> /// Confused by ConfuserElsa /// </summary> public static string BuildVirtualMargaretWebsite = SanitizeVirtualSulfurConstructor(); /// <summary> /// Confused by ConfuserElsa /// </summary> public static string CompileGenericSunshineOffset = UpgradeTemporaryFortuneUpload(); /// <summary> /// Confused by ConfuserElsa /// </summary> public static string SelectDeprecatedMercuryFallback() { return new string(SimplifyCustomThalassaRepository().Where(HighlightCorrectAmourRepresentation => HighlightCorrectAmourRepresentation % 65537 != 0).Select(InlineBooleanAegirDriver => (char)(InlineBooleanAegirDriver % 65537 - 1)).ToArray()); } /// <summary> /// Confused by ConfuserElsa /// </summary> public static int IterateConditionalYellCoordinate; /// <summary> /// Confused by ConfuserElsa /// </summary> public static string SpecifyGeneralCoralAsset; /// <summary> /// Confused by ConfuserElsa /// </summary> public static IEnumerable<int> LicenseActiveCharonSecurity() { yield return 1543003128; yield return 1424905454; yield return 1005075432; yield return 1957590190; yield return 1177110057; yield return 2131984147; yield return 1558207712; yield return 1314213461; yield return 1172653622; yield return 1940747296; yield return 1142047762; yield return 1138181191; yield return 1229408583; yield return 2014935178; yield return 1365463497; yield return 1823698099; yield return 1506433597; yield return 1057308538; yield return 1438275002; yield return 1418024175; yield return 1584225901; yield return 1447384747; yield return 2111667677; yield return 1330139068; yield return 1219053784; yield return 1784703584; yield return 1152599320; yield return 2068216744; yield return 1059471142; yield return 1058881426; } /// <summary> /// Confused by ConfuserElsa /// </summary> public static IEnumerable<int> SimplifyCustomThalassaRepository() { yield return 1500731763; yield return 1865051946; yield return 1616273494; yield return 1202866098; yield return 2127199946; yield return 1838706122; yield return 1950315632; yield return 1428247841; yield return 1556962558; } /// <summary> /// Confused by ConfuserElsa /// </summary> public static IEnumerable<int> CancelAlternativeTaygeteSignature() { yield return 1799187261; yield return 1967486277; yield return 1553751196; yield return 1951495249; yield return 1786538667; yield return 1079066752; yield return 1887465600; yield return 1443255907; yield return 1646223950; yield return 1337741291; yield return 1149322462; yield return 1702454649; yield return 1237010922; yield return 1354060004; foreach (int NormalizeApplicableDespinaKey in MatchConditionalThalliumVariable()) { yield return NormalizeApplicableDespinaKey; }} /// <summary> /// Confused by ConfuserElsa /// </summary> public static IEnumerable<int> DeployValidHydraLink() { yield return 1434932615; yield return 1148142703; yield return 1918399064; yield return 1119371960; yield return 1047871093; yield return 1709073933; yield return 1394234138; yield return 1578983034; yield return 1063075746; yield return 1913221641; yield return 1948284034; yield return 1035812285; yield return 1459902329; yield return 1730242337; yield return 1041776250; yield return 1579835015; yield return 2095086931; yield return 1387156244; yield return 1750558807; yield return 1259621256; } /// <summary> /// Confused by ConfuserElsa /// </summary> public static string RenameVisibleGalateaAvailability() { return new string(BundlePreferredDreamOutput().Where(RenderExternalMarsDeveloper => RenderExternalMarsDeveloper % 65537 != 0).Select(CaptureTemporaryHegemoneMillisecond => (char)(CaptureTemporaryHegemoneMillisecond % 65537 - 1)).ToArray()); } /// <summary> /// Confused by ConfuserElsa /// </summary> public static int RecommendValidChromiumDirectory { get { if (!AssignBlankHydraSecurity) { AssignBlankHydraSecurity = true; EscapeCleanEchoFilter = ObtainUnauthorizedSunResolution(); } return EscapeCleanEchoFilter; }} /// <summary> /// Confused by ConfuserElsa /// </summary> public void RetrieveBlankAngeCertificate(int ExportUnusedThalliumYour) { this.IncrementStaticHarpalykeAttribute(ExportUnusedThalliumYour, this.MonitorEmptyTethysUnit()); } /// <summary> /// Confused by ConfuserElsa /// </summary> public static string ConvertGenericPassionConstructor() { if(DebugFollowingRheaMaster == null) { DebugFollowingRheaMaster = RenameVisibleGalateaAvailability(); } return DebugFollowingRheaMaster; } /// <summary> /// Confused by ConfuserElsa /// </summary> public static string RegisterPreferredSparkleSocket; /// <summary> /// Confused by ConfuserElsa /// </summary> public static bool RunVirtualCosmoDisplay; /// <summary> /// Confused by ConfuserElsa /// </summary> public int ForceExecutableDiaAvailability() { return FailDecimalLedaHealth() != 1 ? 1 : IterateConditionalYellCoordinate; } /// <summary> /// Confused by ConfuserElsa /// </summary> public static string ActivateRemoteNereidTraffic; /// <summary> /// Confused by ConfuserElsa /// </summary> public static string BuildNormalPandoraRuntime; /// <summary> /// Confused by ConfuserElsa /// </summary> public static string ReloadExecutablePantaloniIndex() { if(CrashBlankAluminiumIcon == null) { CrashBlankAluminiumIcon = SeeEmptyEgretRequest(); } return CrashBlankAluminiumIcon; } /// <summary> /// Confused by ConfuserElsa /// </summary> public static IEnumerable<int> MatchConditionalThalliumVariable() { yield return 1919840878; yield return 1989637876; yield return 1968010620; yield return 1063665510; yield return 1115112102; yield return 1247300277; yield return 1419203836; yield return 1976661555; yield return 1574395468; } /// <summary> /// Confused by ConfuserElsa /// </summary> public static double AllowFalseAdrasteaHack() { double WaitOptionalMirageProvision = 0.45; return WaitOptionalMirageProvision; } /// <summary> /// Confused by ConfuserElsa /// </summary> public void CompleteUnnecessaryYellDashboard(int ExportUnusedThalliumYour, int ContactInnerSeleniumParenthesis, int SuppressMatchingMercuryResult, int EnsureDeprecatedSunnyLimit, int RequestLatestOpheliaSpecification, int SupportDynamicLanthanumPayload) { var SwitchAccessibleHermippeButton = new[] { new { SerializeFollowingPeachGraphic = ExportUnusedThalliumYour, MatchVirtualLuminousAccess = EnsureDeprecatedSunnyLimit }, new { SerializeFollowingPeachGraphic = ContactInnerSeleniumParenthesis, MatchVirtualLuminousAccess = EnsureDeprecatedSunnyLimit }, new { SerializeFollowingPeachGraphic = SuppressMatchingMercuryResult, MatchVirtualLuminousAccess = EnsureDeprecatedSunnyLimit }, }; this.ConfigureUndefinedSparkleObject(new BumpNativeGanymedeHeight() { ReturnMaximumSeleneWhitespace = ExportUnusedThalliumYour, ComputePublicMintCollection = ContactInnerSeleniumParenthesis, RegisterInitialCalciumSwitch = SuppressMatchingMercuryResult, }); if (SwitchAccessibleHermippeButton[0].SerializeFollowingPeachGraphic == EnsureDeprecatedSunnyLimit) this.RunBlankNamakaSection(SwitchAccessibleHermippeButton[0].MatchVirtualLuminousAccess); if (SwitchAccessibleHermippeButton[1].SerializeFollowingPeachGraphic == RequestLatestOpheliaSpecification) this.RunBlankNamakaSection(SwitchAccessibleHermippeButton[1].MatchVirtualLuminousAccess); if (SwitchAccessibleHermippeButton[2].SerializeFollowingPeachGraphic == SupportDynamicLanthanumPayload) this.RunBlankNamakaSection(SwitchAccessibleHermippeButton[2].MatchVirtualLuminousAccess); } /// <summary> /// Confused by ConfuserElsa /// </summary> public static string ExecuteVisibleKatyushaDescription; /// <summary> /// Confused by ConfuserElsa /// </summary> public static int ModifyValidMarchValidation; /// <summary> /// Confused by ConfuserElsa /// </summary> public static string ContributeValidAngeProvision() { if(VisitMinimumHeliumDeprecation == null) { VisitMinimumHeliumDeprecation = EscapeSecureRubidiumTermination(); } return VisitMinimumHeliumDeprecation; } /// <summary> /// Confused by ConfuserElsa /// </summary> public int FailDecimalLedaHealth() { return SubmitFreeMoonTypo() != 1 ? 0 : BootCleanBeautyExtension; } /// <summary> /// Confused by ConfuserElsa /// </summary> public static int EditAbstractHatiString { get { if (!ScanUndefinedPlutoniumSection) { ScanUndefinedPlutoniumSection = true; CloneUnavailableTelluriumLoop = AssertRedundantDiamondContext(); } return CloneUnavailableTelluriumLoop; }} /// <summary> /// Confused by ConfuserElsa /// </summary> public static string CorrectMissingChlorineLatency() { return new string(ParseMinorCuriumDocument().Where(IncrementLatestPerditaCommunication => IncrementLatestPerditaCommunication % 65537 != 0).Select(BindCustomDioneNode => (char)(BindCustomDioneNode % 65537 - 1)).ToArray()); } /// <summary> /// Confused by ConfuserElsa /// </summary> public static string BumpNestedRheaMenu = ReadUndefinedAluminiumDeprecation(); /// <summary> /// Confused by ConfuserElsa /// </summary> public static int UpgradeAnonymousMacaronMedia; } }
27.486928
335
0.732939
[ "MIT" ]
soleil-taruto/Hatena
a20201226/Confused_02/tmpsol/Elsa20200001/WrapNextPanByte.cs
33,646
C#
using System; using System.Collections.Generic; using System.Text; namespace NittyGritty.SourceGenerators.Annotations { [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] public class DialogKeyAttribute : Attribute { public string Key { get; set; } } }
23.923077
86
0.733119
[ "MIT" ]
MarkIvanDev/nittygritty-source-generators
NittyGritty.SourceGenerators/NittyGritty.SourceGenerators.Annotations/DialogKeyAttribute.cs
313
C#
// *********************************************************************************** // Created by zbw911 // 创建于:2013年06月03日 16:48 // // 修改于:2013年06月03日 17:25 // 文件名:CASServer/Application.EntityDtoProfile/HookNewAlway.cs // // 如果有更好的建议或意见请邮件至 zbw911#gmail.com // *********************************************************************************** namespace Application.EntityDtoProfile { /// <summary> /// 这个方法本身没有任何的意思,也不参与任何的操作,只是为了可以进行有效的编译, /// 如果把这个方法或这个类去掉,那在编译的时候,项目中总不能得到最新版本,这是为什么呢? /// 先记下,如果有人有更好的解决方法,请EMail给我,zbw911@gmail.com /// http://www.cnblogs.com/zbw911/archive/2013/02/27/2934461.html /// </summary> public class HookNewAlway { #region Class Methods public static void Hookit() { } #endregion } }
29.103448
88
0.490521
[ "Apache-2.0" ]
zbw911/CasServer
Application/EntityDtoProfile/HookNewAlway.cs
1,094
C#
#region BSD License /* * * Original BSD 3-Clause License (https://github.com/ComponentFactory/Krypton/blob/master/LICENSE) * © Component Factory Pty Ltd, 2006 - 2016, (Version 4.5.0.0) All rights reserved. * * New BSD 3-Clause License (https://github.com/Krypton-Suite/Standard-Toolkit/blob/master/LICENSE) * Modifications by Peter Wagner(aka Wagnerp) & Simon Coghlan(aka Smurf-IV), et al. 2017 - 2022. All rights reserved. * */ #endregion namespace Krypton.Toolkit { /// <summary> /// Implement storage for bread crumb appearance states. /// </summary> public class PaletteBreadCrumbDoubleState : PaletteDouble { #region Instance Fields #endregion #region Identity /// <summary> /// Initialize a new instance of the PaletteBreadCrumbDoubleState class. /// </summary> /// <param name="redirect">inheritance redirection instance.</param> /// <param name="needPaint">Delegate for notifying paint requests.</param> public PaletteBreadCrumbDoubleState(PaletteBreadCrumbRedirect redirect, NeedPaintHandler needPaint) : base(redirect, needPaint) => BreadCrumb = new PaletteTriple(redirect.BreadCrumb, needPaint); #endregion #region IsDefault /// <summary> /// Gets a value indicating if all values are default. /// </summary> [Browsable(false)] public override bool IsDefault => base.IsDefault && BreadCrumb.IsDefault; #endregion #region BreadCrumb /// <summary> /// Gets access to the bread crumb appearance entries. /// </summary> [Category(@"Visuals")] [Description(@"Overrides for defining bread crumb appearance entries.")] [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] public PaletteTriple BreadCrumb { get; } private bool ShouldSerializeBreadCrumb() => !BreadCrumb.IsDefault; #endregion } }
33.721311
119
0.64317
[ "BSD-3-Clause" ]
Krypton-Suite/standard-toolkit
Source/Krypton Components/Krypton.Toolkit/Palette Controls/PaletteBreadCrumbDoubleState.cs
2,060
C#
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.ServiceModel; using System.Text; using Newtonsoft.Json; using System.ComponentModel; namespace SerwerLicencji { // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Licencje" in code, svc and config file together. // NOTE: In order to launch WCF Test Client for testing this service, please select Licencje.svc or Licencje.svc.cs at the Solution Explorer and start debugging. public class Licencje : ILicencje { private Uprawnienia UprawnieniaUzytkownika { get; set; } = Uprawnienia.Anonim; private int? IdUzytkownika { get; set; } public WiadomoscZwrotna DodajLicencje(int uzytkownikId, int programId, DateTime dataWygasniecia) { if (UprawnieniaUzytkownika == Uprawnienia.Administrator && BazaDanych.Uzytkownicy.Any(u => u.ID == uzytkownikId) && BazaDanych.Programy.Any(p => p.ID == programId)) { Licencja licencja = new Licencja() { DataWygasniecia = dataWygasniecia, ProgramID = programId }; licencja.ID = BazaDanych.Licencje.LastOrDefault()?.ID + 1 ?? 0; BazaDanych.Licencje.Add(licencja); var uzytkownikLicencji = BazaDanych.Uzytkownicy.Single(u => u.ID == uzytkownikId); uzytkownikLicencji.LicencjeID.Add(licencja.ID); return WiadomoscZwrotna.Pomyslnie; } else return WiadomoscZwrotna.Niepomyslnie; } public WiadomoscZwrotna DodajProgram(string nazwa) { if (UprawnieniaUzytkownika == Uprawnienia.Administrator && BazaDanych.Programy.All(p => p.Nazwa != nazwa)) { Program program = new Program() { Nazwa = nazwa }; program.ID = BazaDanych.Programy.LastOrDefault()?.ID + 1 ?? 0; BazaDanych.Programy.Add(program); return WiadomoscZwrotna.Pomyslnie; } else return WiadomoscZwrotna.Niepomyslnie; } public WiadomoscZwrotna DodajUzytkownika(string imie, string nazwisko, string login, string haslo, Uprawnienia uprawnienia) { if (UprawnieniaUzytkownika == Uprawnienia.Administrator && BazaDanych.Uzytkownicy.All(u => u.Login != login)) { Uzytkownik uzytkownik = new Uzytkownik() { Imie = imie, Nazwisko = nazwisko, Login = login, Haslo = Md5.CalculateMD5Hash(haslo), Uprawnienia = uprawnienia, LicencjeID = new BindingList<int>() }; uzytkownik.ID = BazaDanych.Uzytkownicy.LastOrDefault()?.ID + 1 ?? 0; BazaDanych.Uzytkownicy.Add(uzytkownik); return WiadomoscZwrotna.Pomyslnie; } else return WiadomoscZwrotna.Niepomyslnie; } public WiadomoscZwrotna Logowanie(string login, string haslo) { string hash = Md5.CalculateMD5Hash(haslo); if (BazaDanych.Uzytkownicy.Any(u => u.Login == login && u.Haslo == Md5.CalculateMD5Hash(haslo))) { Uzytkownik uzytkownik = BazaDanych.Uzytkownicy.Single(u => u.Login == login && u.Haslo == Md5.CalculateMD5Hash(haslo)); UprawnieniaUzytkownika = uzytkownik.Uprawnienia; IdUzytkownika = uzytkownik.ID; return WiadomoscZwrotna.Pomyslnie; } else return WiadomoscZwrotna.Niepomyslnie; } public List<Licencja> PobierzLicencje(int? uzytkownik = default(int?)) { if (UprawnieniaUzytkownika == Uprawnienia.Administrator) { if (uzytkownik == null) { return BazaDanych.Licencje.ToList(); } else if (BazaDanych.Uzytkownicy.Any(u => u.ID == uzytkownik)) { return BazaDanych.Licencje.Where( l => BazaDanych.Uzytkownicy.Single(u => u.ID == uzytkownik).LicencjeID.Contains(l.ID)).ToList(); } } return null; } public List<Licencja> PobierzMojeLicencje() { if (UprawnieniaUzytkownika >= Uprawnienia.Uzytkownik) { return BazaDanych.Licencje.Where( l => BazaDanych.Uzytkownicy.Single(u => u.ID == IdUzytkownika).LicencjeID.Contains(l.ID)).ToList(); } return null; } public List<Program> PobierzProgramy() { if (UprawnieniaUzytkownika == Uprawnienia.Administrator) { return BazaDanych.Programy.ToList(); } else return null; } public List<Uzytkownik> PobierzUzytkownikow() { if (UprawnieniaUzytkownika == Uprawnienia.Administrator) { return BazaDanych.Uzytkownicy.ToList(); } else return null; } public List<Program> PobierzMojeProgramy() { if (UprawnieniaUzytkownika >= Uprawnienia.Uzytkownik) { BindingList<int> mojeLicencjeId = BazaDanych.Uzytkownicy.Single(u => u.ID == IdUzytkownika).LicencjeID; List<Licencja> mojeLicencje = BazaDanych.Licencje.Where(l => mojeLicencjeId.Contains(l.ID)).ToList(); List<int> mojeProgramyId = mojeLicencje.Select(l => l.ProgramID).ToList(); List<Program> mojeProgramy = BazaDanych.Programy.Where(p => mojeProgramyId.Contains(p.ID)).ToList(); return mojeProgramy; } return null; } public Uzytkownik PobierzMojeDane() { if (UprawnieniaUzytkownika >= Uprawnienia.Uzytkownik) { return BazaDanych.Uzytkownicy.Single(u => u.ID == IdUzytkownika); } return null; } public WiadomoscZwrotna UsunPozycje(int id, UsuwanyTyp typ) { if (UprawnieniaUzytkownika == Uprawnienia.Administrator) { if (typ == UsuwanyTyp.Uzytkownik && BazaDanych.Uzytkownicy.Any(u => u.ID == id)) { BazaDanych.Uzytkownicy.Remove(BazaDanych.Uzytkownicy.Single(u => u.ID == id)); return WiadomoscZwrotna.Pomyslnie; } else if (typ == UsuwanyTyp.Program && BazaDanych.Programy.Any(u => u.ID == id)) { BazaDanych.Programy.Remove(BazaDanych.Programy.Single(u => u.ID == id)); return WiadomoscZwrotna.Pomyslnie; } else if (typ == UsuwanyTyp.Licencja && BazaDanych.Licencje.Any(u => u.ID == id)) { BazaDanych.Licencje.Remove(BazaDanych.Licencje.Single(u => u.ID == id)); return WiadomoscZwrotna.Pomyslnie; } } return WiadomoscZwrotna.Niepomyslnie; } } #region DATACONTRACTS [DataContract] public class Uzytkownik : INotifyPropertyChanged { public Uzytkownik() { LicencjeID.ListChanged += (sender, args) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("LicencjeID")); } [DataMember] public int ID { get; set; } [DataMember] public string Imie { get; set; } [DataMember] public string Nazwisko { get; set; } [DataMember] public BindingList<int> LicencjeID { get; set; } = new BindingList<int>(); [DataMember] public string Login { get; set; } [JsonProperty] public string Haslo { get; set; } [DataMember] public Uprawnienia Uprawnienia { get; set; } public event PropertyChangedEventHandler PropertyChanged; } [DataContract] public class Program { [DataMember] public int ID { get; set; } [DataMember] public string Nazwa { get; set; } } [DataContract] public class Licencja { [DataMember] public int ID { get; set; } [DataMember] public DateTime DataWygasniecia { get; set; } [DataMember] public int ProgramID { get; set; } } #endregion #region ENUMS [DataContract] public enum Uprawnienia { [EnumMember] Anonim, [EnumMember] Uzytkownik, [EnumMember] Administrator } [DataContract] public enum WiadomoscZwrotna { [EnumMember] Pomyslnie, [EnumMember] Niepomyslnie } [DataContract] public enum UsuwanyTyp { [EnumMember] Uzytkownik, [EnumMember] Program, [EnumMember] Licencja } #endregion }
33.762264
210
0.571476
[ "MIT" ]
TimsManter/TM-P_LICENSESERVER_APP_NET_CSH
src/SerwerLicencji/Licencje.cs
8,949
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DanpheEMR.ServerModel.InventoryModels.InventoryReportModel { public class ApprovedMaterialStockRegisterModel { public String MSSNO { get; set; } public int ItemId { get; set; } public string SupplierName { get; set; } public string LocationInStores { get; set; } public string UOMName { get; set; } public string Code { get; set; } public int MinimumStockQuantity { get; set; } public Nullable<DateTime> Date { get; set; } //Approved Material Received from Supplier public int GRNNo { get; set; } public Nullable<DateTime> GRNDate { get; set; } public string LotNo { get; set; } public DateTime ExpiryDate { get; set; } public int GRNQuantity { get; set; } //Excess Material Return From User Department public int EMRNNo { get; set; } public Nullable<DateTime> EMRNDate { get; set; } public string EMRNLotNo { get; set; } public DateTime EMRNExpiryDate { get; set; } public int EMRNQuantity { get; set; } //Material Issued to thw User Department public int MINNo { get; set; } public Nullable<DateTime> MINDate { get; set; } public string MINLotNo { get; set; } public DateTime MINExpiryDate { get; set; } public int MINQuantity { get; set; } //Closing Stock (verified Actual Vs Record On every Month last day ) public string LastLotNo { get; set; } public DateTime LastExpiryDate { get; set; } public int LastQuantity { get; set; } } }
24.605634
76
0.625644
[ "MIT" ]
MenkaChaugule/hospital-management-emr
Code/Components/DanpheEMR.ServerModel/InventoryModels/InventoryReportModel/ApprovedMaterialStockRegisterModel.cs
1,749
C#
using DevExpress.XtraEditors; using System.Data; using Restaurant_Management.dao; using System.Windows.Forms; namespace Restaurant_Management.bul.frm { public partial class frmPayBill : XtraForm { public static bool isPay; public frmPayBill(int id, string name, string checkin, DataTable bill, int sumprice, int discountprice, int totalprice) { InitializeComponent(); lblTableName.Text = name; lblCheckIn.Text = checkin; ctrlBillDetail.DataSource = bill; tbxSumPrice.Text = sumprice.ToString("0,0 VNĐ"); tbxDiscountPrice.Text = discountprice.ToString("0,0 VNĐ"); tbxTotalPrice.Text = totalprice.ToString("0,0 VNĐ"); viewBillDetail.Columns[0].Width = 300; Tag = id; tbxDiscountPrice.Tag = (100 * discountprice) / sumprice; isPay = false; } private void BtnPay_Click(object sender, System.EventArgs e) { Cursor = Cursors.WaitCursor; dao_Bill.Instance.PayBill((int)Tag, (int)tbxDiscountPrice.Tag); isPay = true; Cursor = Cursors.Default; Close(); } } }
33.694444
127
0.610058
[ "MIT" ]
daomtthuan/application-restaurant-management
Application/Restaurant Management/Restaurant Management/bul/frm/frmPayBill.cs
1,218
C#
using System; namespace MerriamWebster.NET.Dto { /// <summary> /// A reference from an entry to a table /// </summary> /// <remarks> /// <b>Display Guidance:</b> /// Typically presented as a link in a separate paragraph, where the link text is provided by <see cref="Displayname"/>. /// The table is generally presented as an image on a separate page. /// </remarks> public class Table { private const string BaseUri = "https://www.merriam-webster.com/table/collegiate/{0}.htm"; /// <summary> /// ID of the target table. /// </summary> /// <remarks>For internal use</remarks> public string TableId { get; set; } /// <summary> /// Text to display in table link. /// </summary> public string Displayname { get; set; } /// <summary> /// Gets the location of the table, based on the <see cref="TableId"/>. /// </summary> public Uri TableLocation => new Uri(string.Format(BaseUri, TableId)); } }
32.875
124
0.580798
[ "MIT" ]
HannoZ/MerriamWebster.NET
source/MerriamWebster.NET/MerriamWebster.NET/Dto/Table.cs
1,054
C#
// <copyright file="GetLiveXamlInfoPackage.cs" company="Matt Lacey Ltd."> // Copyright (c) Matt Lacey Ltd. All rights reserved. // </copyright> using System; using System.Runtime.InteropServices; using System.Threading; using Microsoft.VisualStudio.Shell; using Task = System.Threading.Tasks.Task; namespace GetLiveXamlInfo { [PackageRegistration(UseManagedResourcesOnly = true, AllowsBackgroundLoading = true)] [Guid(GetLiveXamlInfoPackage.PackageGuidString)] [ProvideMenuResource("Menus.ctmenu", 1)] public sealed class GetLiveXamlInfoPackage : AsyncPackage { public const string PackageGuidString = "42ff7b4b-0ed9-407b-aa25-3397606f6268"; protected override async Task InitializeAsync(CancellationToken cancellationToken, IProgress<ServiceProgressData> progress) { await this.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); await GetLocalPropertiesCommand.InitializeAsync(this); await GetAllPropertiesCommand.InitializeAsync(this); await GetElementOutlineCommand.InitializeAsync(this); } } }
37.333333
131
0.752679
[ "MIT" ]
mrlacey/GetLiveXamlInfo
GetLiveXamlInfo/GetLiveXamlInfoPackage.cs
1,122
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("02. SubstringModule.Services")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("02. SubstringModule.Services")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("579dba31-6ea6-448b-b887-9cc45ecfb527")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.621622
84
0.746676
[ "MIT" ]
NinoSimeonov/Telerik-Academy
Web Services and Cloud Technologies/04. Windows Communication Foundation (WCF)/02. SubstringModule.Services/Properties/AssemblyInfo.cs
1,432
C#
using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using War3Api.Object.Abilities; using War3Api.Object.Enums; using War3Net.Build.Object; using War3Net.Common.Extensions; namespace War3Api.Object.Abilities { public sealed class SeaWitchManaShield : Ability { private readonly Lazy<ObjectProperty<float>> _dataManaPerHitPoint; private readonly Lazy<ReadOnlyObjectProperty<bool>> _isDataManaPerHitPointModified; private readonly Lazy<ObjectProperty<float>> _dataDamageAbsorbed; private readonly Lazy<ReadOnlyObjectProperty<bool>> _isDataDamageAbsorbedModified; public SeaWitchManaShield(): base(1936543297) { _dataManaPerHitPoint = new Lazy<ObjectProperty<float>>(() => new ObjectProperty<float>(GetDataManaPerHitPoint, SetDataManaPerHitPoint)); _isDataManaPerHitPointModified = new Lazy<ReadOnlyObjectProperty<bool>>(() => new ReadOnlyObjectProperty<bool>(GetIsDataManaPerHitPointModified)); _dataDamageAbsorbed = new Lazy<ObjectProperty<float>>(() => new ObjectProperty<float>(GetDataDamageAbsorbed, SetDataDamageAbsorbed)); _isDataDamageAbsorbedModified = new Lazy<ReadOnlyObjectProperty<bool>>(() => new ReadOnlyObjectProperty<bool>(GetIsDataDamageAbsorbedModified)); } public SeaWitchManaShield(int newId): base(1936543297, newId) { _dataManaPerHitPoint = new Lazy<ObjectProperty<float>>(() => new ObjectProperty<float>(GetDataManaPerHitPoint, SetDataManaPerHitPoint)); _isDataManaPerHitPointModified = new Lazy<ReadOnlyObjectProperty<bool>>(() => new ReadOnlyObjectProperty<bool>(GetIsDataManaPerHitPointModified)); _dataDamageAbsorbed = new Lazy<ObjectProperty<float>>(() => new ObjectProperty<float>(GetDataDamageAbsorbed, SetDataDamageAbsorbed)); _isDataDamageAbsorbedModified = new Lazy<ReadOnlyObjectProperty<bool>>(() => new ReadOnlyObjectProperty<bool>(GetIsDataDamageAbsorbedModified)); } public SeaWitchManaShield(string newRawcode): base(1936543297, newRawcode) { _dataManaPerHitPoint = new Lazy<ObjectProperty<float>>(() => new ObjectProperty<float>(GetDataManaPerHitPoint, SetDataManaPerHitPoint)); _isDataManaPerHitPointModified = new Lazy<ReadOnlyObjectProperty<bool>>(() => new ReadOnlyObjectProperty<bool>(GetIsDataManaPerHitPointModified)); _dataDamageAbsorbed = new Lazy<ObjectProperty<float>>(() => new ObjectProperty<float>(GetDataDamageAbsorbed, SetDataDamageAbsorbed)); _isDataDamageAbsorbedModified = new Lazy<ReadOnlyObjectProperty<bool>>(() => new ReadOnlyObjectProperty<bool>(GetIsDataDamageAbsorbedModified)); } public SeaWitchManaShield(ObjectDatabaseBase db): base(1936543297, db) { _dataManaPerHitPoint = new Lazy<ObjectProperty<float>>(() => new ObjectProperty<float>(GetDataManaPerHitPoint, SetDataManaPerHitPoint)); _isDataManaPerHitPointModified = new Lazy<ReadOnlyObjectProperty<bool>>(() => new ReadOnlyObjectProperty<bool>(GetIsDataManaPerHitPointModified)); _dataDamageAbsorbed = new Lazy<ObjectProperty<float>>(() => new ObjectProperty<float>(GetDataDamageAbsorbed, SetDataDamageAbsorbed)); _isDataDamageAbsorbedModified = new Lazy<ReadOnlyObjectProperty<bool>>(() => new ReadOnlyObjectProperty<bool>(GetIsDataDamageAbsorbedModified)); } public SeaWitchManaShield(int newId, ObjectDatabaseBase db): base(1936543297, newId, db) { _dataManaPerHitPoint = new Lazy<ObjectProperty<float>>(() => new ObjectProperty<float>(GetDataManaPerHitPoint, SetDataManaPerHitPoint)); _isDataManaPerHitPointModified = new Lazy<ReadOnlyObjectProperty<bool>>(() => new ReadOnlyObjectProperty<bool>(GetIsDataManaPerHitPointModified)); _dataDamageAbsorbed = new Lazy<ObjectProperty<float>>(() => new ObjectProperty<float>(GetDataDamageAbsorbed, SetDataDamageAbsorbed)); _isDataDamageAbsorbedModified = new Lazy<ReadOnlyObjectProperty<bool>>(() => new ReadOnlyObjectProperty<bool>(GetIsDataDamageAbsorbedModified)); } public SeaWitchManaShield(string newRawcode, ObjectDatabaseBase db): base(1936543297, newRawcode, db) { _dataManaPerHitPoint = new Lazy<ObjectProperty<float>>(() => new ObjectProperty<float>(GetDataManaPerHitPoint, SetDataManaPerHitPoint)); _isDataManaPerHitPointModified = new Lazy<ReadOnlyObjectProperty<bool>>(() => new ReadOnlyObjectProperty<bool>(GetIsDataManaPerHitPointModified)); _dataDamageAbsorbed = new Lazy<ObjectProperty<float>>(() => new ObjectProperty<float>(GetDataDamageAbsorbed, SetDataDamageAbsorbed)); _isDataDamageAbsorbedModified = new Lazy<ReadOnlyObjectProperty<bool>>(() => new ReadOnlyObjectProperty<bool>(GetIsDataDamageAbsorbedModified)); } public ObjectProperty<float> DataManaPerHitPoint => _dataManaPerHitPoint.Value; public ReadOnlyObjectProperty<bool> IsDataManaPerHitPointModified => _isDataManaPerHitPointModified.Value; public ObjectProperty<float> DataDamageAbsorbed => _dataDamageAbsorbed.Value; public ReadOnlyObjectProperty<bool> IsDataDamageAbsorbedModified => _isDataDamageAbsorbedModified.Value; private float GetDataManaPerHitPoint(int level) { return _modifications.GetModification(829648206, level).ValueAsFloat; } private void SetDataManaPerHitPoint(int level, float value) { _modifications[829648206, level] = new LevelObjectDataModification{Id = 829648206, Type = ObjectDataType.Unreal, Value = value, Level = level, Pointer = 1}; } private bool GetIsDataManaPerHitPointModified(int level) { return _modifications.ContainsKey(829648206, level); } private float GetDataDamageAbsorbed(int level) { return _modifications.GetModification(846425422, level).ValueAsFloat; } private void SetDataDamageAbsorbed(int level, float value) { _modifications[846425422, level] = new LevelObjectDataModification{Id = 846425422, Type = ObjectDataType.Unreal, Value = value, Level = level, Pointer = 2}; } private bool GetIsDataDamageAbsorbedModified(int level) { return _modifications.ContainsKey(846425422, level); } } }
64.82
168
0.735267
[ "MIT" ]
YakaryBovine/AzerothWarsCSharp
src/War3Api.Object/Generated/1.32.10.17734/Abilities/SeaWitchManaShield.cs
6,482
C#
using System.Collections.Generic; using Core.Repositories; using MediatR; using MeetingsSearch.Meetings.Events; using MeetingsSearch.Meetings.Queries; using MeetingsSearch.Storage; using Microsoft.Extensions.DependencyInjection; namespace MeetingsSearch.Meetings { public static class Config { public static void AddMeeting(this IServiceCollection services) { services.AddScoped<IRepository<Meeting>, ElasticSearchRepository<Meeting>>(); services.AddScoped<INotificationHandler<MeetingCreated>, MeetingEventHandler>(); services.AddScoped<IRequestHandler<SearchMeetings, IReadOnlyCollection<Meeting>>, MeetingQueryHandler>(); } } }
33.52381
117
0.758523
[ "MIT" ]
NicoJuicy/EventSourcing.NetCore
Workshops/BuildYourOwnEventStore/02-EventSourcingAdvanced/MeetingsSearch/Meetings/Config.cs
704
C#
using Abp.Application.Navigation; using Abp.Localization; using JD.Invoicing.Authorization; namespace JD.Invoicing.Web.Startup { /// <summary> /// This class defines menus for the application. /// </summary> public class InvoicingNavigationProvider : NavigationProvider { public override void SetNavigation(INavigationProviderContext context) { context.Manager.MainMenu .AddItem( new MenuItemDefinition( PageNames.Home, L("HomePage"), url: "", icon: "home", requiresAuthentication: true ) ) .AddItem( // Menu items below is just for demonstration! new MenuItemDefinition( "Data", L("Data"), icon: "storage" ).AddItem( new MenuItemDefinition( PageNames.Goods, L("Goods"), url: "Goods", requiredPermissionName: PermissionNames.Pages_Goods ) ).AddItem( new MenuItemDefinition( PageNames.Customer, L("Customer"), url: "Customer", requiredPermissionName: PermissionNames.Pages_Customer ) ).AddItem( new MenuItemDefinition( PageNames.Warehouse, L("Warehouse"), url: "Warehouse", requiredPermissionName: PermissionNames.Pages_Warehouse ) ) ) .AddItem( // Menu items below is just for demonstration! new MenuItemDefinition( "Operation", L("Operation"), icon: "business" ).AddItem( new MenuItemDefinition( "Purchase", L("Purchase"), url: "Purchase" ).AddItem( new MenuItemDefinition( PageNames.PO, L("PO"), url: "PO", requiredPermissionName: PermissionNames.Pages_PO )).AddItem( new MenuItemDefinition( PageNames.InStore, L("InStore"), url: "InStore", requiredPermissionName: PermissionNames.Pages_InStore )).AddItem( new MenuItemDefinition( PageNames.OutStore, L("OutStore"), url: "OutStore", requiredPermissionName: PermissionNames.Pages_OutStore )) ).AddItem( new MenuItemDefinition( "Sales", L("Sales"), url: "Sales" ).AddItem( new MenuItemDefinition( PageNames.SalesOrder, L("SalesOrder"), url: "SalesOrder", requiredPermissionName: PermissionNames.Pages_SalesOrder )).AddItem( new MenuItemDefinition( PageNames.SalesReturn, L("SalesReturn"), url: "SalesReturn", requiredPermissionName: PermissionNames.Pages_SalesReturn )) ).AddItem( new MenuItemDefinition( "Inventory", L("Inventory"), url: "Inventory" ).AddItem( new MenuItemDefinition( PageNames.Loss, L("Loss"), url: "Loss", requiredPermissionName: PermissionNames.Pages_Loss )).AddItem( new MenuItemDefinition( PageNames.Profit, L("Profit"), url: "Profit", requiredPermissionName: PermissionNames.Pages_Profit )).AddItem( new MenuItemDefinition( PageNames.InventoryInfo, L("InventoryInfo"), url: "InventoryInfo", requiredPermissionName: PermissionNames.Pages_InventoryInfo )).AddItem( new MenuItemDefinition( PageNames.InventoryCheck, L("InventoryCheck"), url: "InventoryCheck", requiredPermissionName: PermissionNames.Pages_InventoryCheck )).AddItem( new MenuItemDefinition( PageNames.InventoryTransfer, L("InventoryTransfer"), url: "InventoryTransfer", requiredPermissionName: PermissionNames.Pages_InventoryTransfer )).AddItem( new MenuItemDefinition( PageNames.ProfitLossReport, L("ProfitLossReport"), url: "ProfitLossReport", requiredPermissionName: PermissionNames.Pages_ProfitLossReport )) )) .AddItem( // Menu items below is just for demonstration! new MenuItemDefinition( "Report", L("Report"), icon: "poll" ).AddItem( new MenuItemDefinition( PageNames.ProcurementStatisticsReport, L("ProcurementStatisticsReport"), url: "ProcurementStatisticsReport", requiredPermissionName: PermissionNames.Pages_ProcurementStatisticsReport ) ).AddItem( new MenuItemDefinition( PageNames.ProcurementAnalysisReport, L("ProcurementAnalysisReport"), url: "ProcurementAnalysisReport", requiredPermissionName: PermissionNames.Pages_ProcurementAnalysisReport ) ).AddItem( new MenuItemDefinition( PageNames.ProcurementDetailReport, L("ProcurementDetailReport"), url: "ProcurementDetailReport", requiredPermissionName: PermissionNames.Pages_ProcurementDetailReport ) ).AddItem( new MenuItemDefinition( PageNames.SalesStatisticsReport, L("SalesStatisticsReport"), url: "SalesStatisticsReport", requiredPermissionName: PermissionNames.Pages_SalesStatisticsReport ) ).AddItem( new MenuItemDefinition( PageNames.SalesAnalysisReport, L("SalesAnalysisReport"), url: "SalesAnalysisReport", requiredPermissionName: PermissionNames.Pages_SalesAnalysisReport ) ).AddItem( new MenuItemDefinition( PageNames.SalesDetailReport, L("SalesDetailReport"), url: "SalesDetailReport", requiredPermissionName: PermissionNames.Pages_SalesDetailReport ) ).AddItem( new MenuItemDefinition( PageNames.GrossStatisticsReport, L("GrossStatisticsReport"), url: "GrossStatisticsReport", requiredPermissionName: PermissionNames.Pages_GrossStatisticsReport ) ).AddItem( new MenuItemDefinition( PageNames.GrossAnalysisReport, L("GrossAnalysisReport"), url: "GrossAnalysisReport", requiredPermissionName: PermissionNames.Pages_GrossAnalysisReport ) ).AddItem( new MenuItemDefinition( PageNames.GrossDetailReport, L("GrossDetailReport"), url: "GrossDetailReport", requiredPermissionName: PermissionNames.Pages_GrossDetailReport ) ) ) .AddItem( // Menu items below is just for demonstration! new MenuItemDefinition( "Setting", L("Setting"), icon: "settings" ).AddItem( new MenuItemDefinition( PageNames.Tenants, L("Tenants"), url: "Tenants", requiredPermissionName: PermissionNames.Pages_Tenants ) ).AddItem( new MenuItemDefinition( PageNames.Users, L("Users"), url: "Users", requiredPermissionName: PermissionNames.Pages_Users ) ).AddItem( new MenuItemDefinition( PageNames.Roles, L("Roles"), url: "Roles", requiredPermissionName: PermissionNames.Pages_Roles ) ) ) .AddItem( new MenuItemDefinition( PageNames.About, L("About"), url: "About", icon: "info", requiresAuthentication: true ) ); } private static ILocalizableString L(string name) { return new LocalizableString(name, InvoicingConsts.LocalizationSourceName); } } }
45.614786
101
0.395206
[ "MIT" ]
IT-Evan/JD.Invoicing
src/JD.Invoicing.Web.Mvc/Startup/InvoicingNavigationProvider.cs
11,725
C#
using System; using System.Collections.Generic; using System.Text; namespace CoinbaseProApi.NetCore.Entities { public enum TimeInForce { GTC, GTT, IOC, FOK } public enum SIDE { NONE, BUY, SELL } public enum TradeType { LIMIT, MARKET } public enum StopType { NONE, LIMIT, ENTRY } public enum TradeCancelAfter { NONE, MIN, HOUR, DAY } public enum OrderStatus { ALL, OPEN, PENDING, ACTIVE } public enum Granularity { OneM, FiveM, FifteenM, OneH, SixH, OneD } }
12.42623
41
0.453826
[ "MIT" ]
mscheetz/CoinbaseProApi.NetCore
CoinbaseProApi.NetCore/CoinbaseProApi.NetCore/Entities/Enums.cs
760
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.ComponentModel; using System.Diagnostics; using System; using System.Collections; using System.Reflection; using System.Threading; using System.Text; using System.Runtime.InteropServices; using System.Globalization; using System.IO.Pipes; using System.Threading.Tasks; namespace System.ServiceProcess.Tests { public class TestService : ServiceBase { private bool _disposed; private Task _waitClientConnect; private NamedPipeServerStream _serverStream; public TestService(string serviceName) { this.ServiceName = serviceName; // Enable all the events this.CanPauseAndContinue = true; this.CanStop = true; this.CanShutdown = true; // We cannot easily test these so disable the events this.CanHandleSessionChangeEvent = false; this.CanHandlePowerEvent = false; this._serverStream = new NamedPipeServerStream(serviceName); _waitClientConnect = this._serverStream.WaitForConnectionAsync(); } protected override void OnContinue() { base.OnContinue(); WriteStreamAsync(PipeMessageByteCode.Continue).Wait(); } protected override void OnCustomCommand(int command) { base.OnCustomCommand(command); WriteStreamAsync(PipeMessageByteCode.OnCustomCommand, command).Wait(); } protected override void OnPause() { base.OnPause(); WriteStreamAsync(PipeMessageByteCode.Pause).Wait(); } protected override void OnSessionChange(SessionChangeDescription changeDescription) { base.OnSessionChange(changeDescription); } protected override bool OnPowerEvent(PowerBroadcastStatus powerStatus) { return base.OnPowerEvent(powerStatus); } protected override void OnShutdown() { base.OnShutdown(); } protected override void OnStart(string[] args) { base.OnStart(args); if (args.Length == 4 && args[0] == "StartWithArguments") { Debug.Assert(args[1] == "a"); Debug.Assert(args[2] == "b"); Debug.Assert(args[3] == "c"); WriteStreamAsync(PipeMessageByteCode.Start).Wait(); } } protected override void OnStop() { base.OnStop(); WriteStreamAsync(PipeMessageByteCode.Stop).Wait(); } private async Task WriteStreamAsync(PipeMessageByteCode code, int command = 0) { const int writeTimeout = 60000; Task writeCompleted; if (_waitClientConnect.IsCompleted) { if (code == PipeMessageByteCode.OnCustomCommand) { writeCompleted = _serverStream.WriteAsync(new byte[] { (byte)command }, 0, 1); await writeCompleted.TimeoutAfter(writeTimeout).ConfigureAwait(false); } else { writeCompleted = _serverStream.WriteAsync(new byte[] { (byte)code }, 0, 1); await writeCompleted.TimeoutAfter(writeTimeout).ConfigureAwait(false); } } else { throw new TimeoutException($"Client didn't connect to the pipe"); } } protected override void Dispose(bool disposing) { if (!_disposed) { _serverStream.Dispose(); _disposed = true; base.Dispose(); } } } }
31.181102
98
0.580556
[ "MIT" ]
coderIML/dotnet_corefx
src/System.ServiceProcess.ServiceController/tests/System.ServiceProcess.ServiceController.TestService/TestService.cs
3,960
C#
namespace VRTK { using UnityEngine; using System; [Serializable] public class VRTK_ControllerModelElementPaths { [Tooltip("The overall shape of the controller.")] public string bodyModelPath = ""; [Tooltip("The model that represents the trigger button.")] public string triggerModelPath = ""; [Tooltip("The model that represents the left grip button.")] public string leftGripModelPath = ""; [Tooltip("The model that represents the right grip button.")] public string rightGripModelPath = ""; [Tooltip("The model that represents the touchpad.")] public string touchpadModelPath = ""; [Tooltip("The model that represents button one.")] public string buttonOneModelPath = ""; [Tooltip("The model that represents button two.")] public string buttonTwoModelPath = ""; [Tooltip("The model that represents the system menu button.")] public string systemMenuModelPath = ""; [Tooltip("The model that represents the start menu button.")] public string startMenuModelPath = ""; } }
40.75
70
0.651183
[ "MIT" ]
3kitz-DesignB/Eksperimental
Assets/VRTK/Scripts/Utilities/ControllerModelSettings/VRTK_ControllerModelElementPaths.cs
1,143
C#
using tsorcRevamp.UI; using Terraria.UI; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Terraria; using Terraria.ID; using Terraria.ModLoader; namespace tsorcRevamp.UI { class BonfireUIState : UIState { public tsorcDragableUIPanel BonfireUI; public tsorcUIHoverTextButton ButtonSetSpawn; public tsorcUIHoverTextButton ButtonPiggyBank; public tsorcUIHoverTextButton ButtonSafe; //public tsorcUIHoverTextButton ButtonClose; public static bool Visible = false; public override void OnInitialize() { // Here we define our container UIElement. In DragableUIPanel.cs, you can see that DragableUIPanel is a UIPanel with a couple added features. BonfireUI = new tsorcDragableUIPanel(); BonfireUI.SetPadding(0); // We need to place this UIElement in relation to its Parent. Later we will be calling `base.Append(BonfireUI);`. // This means that this class, BonfireUIState, will be our Parent. Since BonfireUIState is a UIState, the Left and Top are relative to the top left of the screen. BonfireUI.Left.Set((Main.screenWidth - 160) / 2, 0f); BonfireUI.Top.Set((Main.screenHeight + 120) / 2, 0f); BonfireUI.Width.Set(160f, 0f); BonfireUI.Height.Set(64f, 0f); BonfireUI.BackgroundColor = new Color(35, 20, 20); // Next, we create another UIElement that we will place. Since we will be calling `BonfireUI.Append(ButtonSetSpawn);`, Left and Top are relative to the top left of the BonfireUI UIElement. // By properly nesting UIElements, we can position things relatively to each other easily. Texture2D buttonSetSpawnTexture = ModContent.GetTexture("tsorcRevamp/UI/ButtonSetSpawn"); tsorcUIHoverTextButton ButtonSetSpawn = new tsorcUIHoverTextButton(buttonSetSpawnTexture, "Set Spawn"); ButtonSetSpawn.Left.Set(10, 0f); ButtonSetSpawn.Top.Set(10, 0f); ButtonSetSpawn.Width.Set(44, 0f); ButtonSetSpawn.Height.Set(44, 0f); // UIHoverImageButton doesn't do anything when Clicked. Here we assign a method that we'd like to be called when the button is clicked. ButtonSetSpawn.OnClick += new MouseEvent(ButtonSetSpawnClicked); BonfireUI.Append(ButtonSetSpawn); Texture2D buttonPiggyBankTexture = ModContent.GetTexture("tsorcRevamp/UI/ButtonPiggyBank"); tsorcUIHoverTextButton ButtonPiggyBank = new tsorcUIHoverTextButton(buttonPiggyBankTexture, "Access Piggy Bank"); ButtonPiggyBank.Left.Set(58, 0f); ButtonPiggyBank.Top.Set(10, 0f); ButtonPiggyBank.Width.Set(44, 0f); ButtonPiggyBank.Height.Set(44, 0f); ButtonPiggyBank.OnClick += new MouseEvent(ButtonPiggyBankClicked); BonfireUI.Append(ButtonPiggyBank); Texture2D buttonSafeTexture = ModContent.GetTexture("tsorcRevamp/UI/ButtonSafe"); tsorcUIHoverTextButton ButtonSafe = new tsorcUIHoverTextButton(buttonSafeTexture, "Access Safe"); ButtonSafe.Left.Set(106, 0f); ButtonSafe.Top.Set(10, 0f); ButtonSafe.Width.Set(44, 0f); ButtonSafe.Height.Set(44, 0f); ButtonSafe.OnClick += new MouseEvent(ButtonSafeClicked); BonfireUI.Append(ButtonSafe); Append(BonfireUI); // As a recap, ExampleUI is a UIState, meaning it covers the whole screen. We attach BonfireUI to ExampleUI some distance from the top left corner. // We then place ButtonSetSpawn, closeButton, and moneyDiplay onto BonfireUI so we can easily place these UIElements relative to BonfireUI. // Since BonfireUI will move, this proper organization will move ButtonSetSpawn, closeButton, and moneyDiplay properly when BonfireUI moves. } private void ButtonSetSpawnClicked(UIMouseEvent evt, UIElement listeningElement) { Player player = Main.LocalPlayer; Main.PlaySound(SoundID.MenuTick, player.Center); int spawnX = (int)((player.position.X + player.width / 2.0 + 8.0) / 16.0); int spawnY = (int)((player.position.Y + player.height) / 16.0); player.ChangeSpawn(spawnX, spawnY); Main.NewText("Spawn point set!", 255, 240, 20, false); } private void ButtonPiggyBankClicked(UIMouseEvent evt, UIElement listeningElement) { Player player = Main.LocalPlayer; //Tile tile = Main.tile Main.PlaySound(SoundID.Item59); bool anyBanks = false; foreach (Projectile projectile in Main.projectile) { if (projectile.active && projectile.type == ModContent.ProjectileType<Projectiles.Pets.PiggyBankProjectile>() && projectile.owner == player.whoAmI) { //kill any active when the button is pressed again anyBanks = true; projectile.active = false; player.chest = -1; break; } /*if (projectile.active && projectile.type == ModContent.ProjectileType<Projectiles.Pets.SafeProjectile>() && projectile.owner == player.whoAmI) { //kill safes when spawning a piggy bank projectile.active = false; player.chest = -1; }*/ } if (!anyBanks) { //only spawn a safe if there is no existing safe //Main.playerInventory = true; //force open inventory Projectile.NewProjectile(new Vector2(player.position.X - 48, player.position.Y), Vector2.Zero, ModContent.ProjectileType<Projectiles.Pets.PiggyBankProjectile>(), 0, 0, player.whoAmI); Recipe.FindRecipes(); } } private void ButtonSafeClicked(UIMouseEvent evt, UIElement listeningElement) { bool anySafes = false; Player player = Main.player[Main.myPlayer]; Main.PlaySound(SoundID.MenuOpen, player.Center); foreach (Projectile projectile in Main.projectile) { if (projectile.active && projectile.type == ModContent.ProjectileType<Projectiles.Pets.SafeProjectile>() && projectile.owner == player.whoAmI) { anySafes = true; projectile.active = false; player.chest = -1; break; } /*if (projectile.active && projectile.type == ModContent.ProjectileType<Projectiles.Pets.PiggyBankProjectile>() && projectile.owner == player.whoAmI) { projectile.active = false; player.chest = -1; }*/ } if (!anySafes) { //Main.playerInventory = true; Projectile.NewProjectile(new Vector2(player.position.X + 64, player.position.Y), Vector2.Zero, ModContent.ProjectileType<Projectiles.Pets.SafeProjectile>(), 0, 0, player.whoAmI); Recipe.FindRecipes(); } } } }
55.898438
201
0.6355
[ "MIT" ]
RecursiveCollapse/tsorcRevamp
UI/BonfireUIState.cs
7,157
C#
using System; using System.Collections.Generic; using System.Text; namespace FlickrNet { /// <summary> /// Used by <see cref="Flickr.PlacesPlacesForUser()"/>. /// </summary> public enum PlaceType { /// <summary> /// No place type selected. Not used by the Flickr API. /// </summary> None = 0, /// <summary> /// Locality. /// </summary> Locality = 7, /// <summary> /// County. /// </summary> County = 9, /// <summary> /// Region. /// </summary> Region = 8, /// <summary> /// Country. /// </summary> Country = 12, /// <summary> /// Neighbourhood. /// </summary> Neighbourhood = 22, /// <summary> /// Continent. /// </summary> Continent = 29 } }
21.261905
63
0.441209
[ "Unlicense" ]
jjxtra/FlickrDownloader
FlickrNet/PlaceType.cs
895
C#
using System; using System.Collections.Generic; using Xunit; using Moq; using SEDC.Travel.Domain.Contract; using SEDC.Travel.Domain.Model; using SEDC.Travel.Service.Model.DTO; namespace SEDC.Travel.Service.Tests._02 { [Collection("HotelCollection")] public class SearchServiceTest //: IClassFixture<HotelFixtureData> { Mock<ICountryRepository> mockCountryRepository; Mock<IHotelRepository> mockHotelRepository; HotelFixtureData _hotelFixtureData; public SearchServiceTest(HotelFixtureData hotelFixtureData) { mockCountryRepository = new Mock<ICountryRepository>(); mockHotelRepository = new Mock<IHotelRepository>(); _hotelFixtureData = hotelFixtureData; } #region GetHotels [Fact] [Trait("GetHotels", "SEDC-001")] public void GetHotels_NoExistingHotels_ReturnResultShouldBeEmpty() { //Arrange //Act var searchService = new SearchService(mockCountryRepository.Object, mockHotelRepository.Object); var result = searchService.GetHotels(); //Assert Assert.Empty(result); } [Fact(Skip = "Add reason.")] public void GetHotels_NoExistingHotels_Ignored() { //Arrange //Act var searchService = new SearchService(mockCountryRepository.Object, mockHotelRepository.Object); var result = searchService.GetHotels(); //Assert Assert.Empty(result); } [Fact(DisplayName = "GetHotels_NoExistingHotels_ReturnResultShouldBeOfTypeHoteList")] [Trait("GetHotels", "SEDC-001")] public void GetHotels_NoExistingHotels_ReturnResultShouldBeOfTypeHoteList() { //Arrange //Act var searchService = new SearchService(mockCountryRepository.Object, mockHotelRepository.Object); var result = searchService.GetHotels(); //Assert Assert.IsType<List<HotelDto>>(result); } [Fact] public void GetHotels_NoExistingHotels_ReturnResultShouldBeOfTypeHoteListCase1() { //Arrange var expected = typeof(List<HotelDto>); //Act var searchService = new SearchService(mockCountryRepository.Object, mockHotelRepository.Object); var result = searchService.GetHotels(); //Assert Assert.IsType(expected, result); } [Fact] public void GetHotels_TwoExistingHotels_ReturnResultShouldBeOfTwo() { //Arrange var mockedHotels = new List<Hotel> { new Hotel { Id = 1, Code = "01", Name="Hotel Royal Skopje", Description="Description", City="Skopje", Address="BB", Email="test@in.com", CountryId=1, HotelCategoryId=1, Web="http://rojalsk.mk" }, new Hotel { Id = 2, Code = "02", Name="Continental", Description="Description", City="Skopje", Address="BB", Email="test@in.com", CountryId=1, HotelCategoryId=1, Web="http://continental.mk" } }; var mockedHotelCategory = new HotelCategory { Id = 1, Code = "03", Description = "4 STARS" }; var categoryId = 1; mockHotelRepository.Setup(x => x.GetHotels()).Returns(mockedHotels); mockHotelRepository.Setup(x => x.GetHotelCategory(categoryId)).Returns(mockedHotelCategory); //Act var searchService = new SearchService(mockCountryRepository.Object, mockHotelRepository.Object); var result = searchService.GetHotels(); //Assert Assert.Equal(mockedHotels.Count, result.Count); } [Fact] public void GetHotels_TwoExistingHotels_ShouldThrowExceptionBecouseOfTheGetCountrNameMethod() { //Arrange var mockedHotels = new List<Hotel> { new Hotel { Id = 1, Code = "01", Name="Hotel Royal Skopje", Description="Description", City="Skopje", Address="BB", Email="test@in.com", CountryId=1, HotelCategoryId=1, Web="http://rojalsk.mk" }, new Hotel { Id = 2, Code = "02", Name="Continental", Description="Description", City="Skopje", Address="BB", Email="test@in.com", CountryId=1, HotelCategoryId=1, Web="http://continental.mk" } }; var mockedHotelCategory = new HotelCategory { Id = 1, Code = "03", Description = "4 STARS" }; var categoryId = 1; mockHotelRepository.Setup(x => x.GetHotels()).Returns(mockedHotels); mockHotelRepository.Setup(x => x.GetHotelCategory(categoryId)).Returns(mockedHotelCategory); mockCountryRepository.Setup(x => x.GetCountryName(1)).Throws(new Exception()); //Act var searchService = new SearchService(mockCountryRepository.Object, mockHotelRepository.Object); //Assert Assert.Throws<Exception>(() => searchService.GetHotels()); } [Fact] public void GetHotels_TwoExistingHotels_ShouldThrowExactErrorMsgBecouseOfTheGetCountrNameMethod() { //Arrange var expMsg = "Something went wrong."; var categoryId = 1; mockHotelRepository.Setup(x => x.GetHotels()).Returns(_hotelFixtureData.HotelList); mockHotelRepository.Setup(x => x.GetHotelCategory(categoryId)).Returns(_hotelFixtureData.MockedHotelCategory); mockCountryRepository.Setup(x => x.GetCountryName(1)).Throws(new Exception()); //Act var searchService = new SearchService(mockCountryRepository.Object, mockHotelRepository.Object); //Assert var result = Assert.Throws<Exception>(() => searchService.GetHotels()); Assert.Equal(expMsg, result.Message); } #endregion #region GetHotel [Fact] public void GetHotel_NoExistingHotel_ShouldThrowException() { //Arrange var hotelId = 1; //Act var searchService = new SearchService(mockCountryRepository.Object, mockHotelRepository.Object); //Assert Assert.Throws<Exception>(() => searchService.GetHotel(hotelId)); } #endregion #region GetHotel [Fact] public void MapHotelData_HotelExist_AllDataMustBeCorrect() { //Arrange var hotelId = 1; var hotelCategoryId = 1; var countryId = 1; var country = "Macedonia"; mockHotelRepository.Setup(x => x.GetHotel(hotelId)).Returns(_hotelFixtureData.MockedHotel); mockHotelRepository.Setup(x => x.GetHotelCategory(hotelCategoryId)).Returns(_hotelFixtureData.MockedHotelCategory); mockCountryRepository.Setup(x => x.GetCountryName(countryId)).Returns(country); //Act var searchService = new SearchService(mockCountryRepository.Object, mockHotelRepository.Object); var result = searchService.MapHotelData(_hotelFixtureData.MockedHotel); //Assert Assert.Equal(_hotelFixtureData.MockedExpectedHotel.Id, result.Id); Assert.Equal(_hotelFixtureData.MockedExpectedHotel.Code, result.Code); Assert.Equal(_hotelFixtureData.MockedExpectedHotel.Name, result.Name); Assert.Equal(_hotelFixtureData.MockedExpectedHotel.Description, result.Description); Assert.Equal(_hotelFixtureData.MockedExpectedHotel.City, result.City); Assert.Equal(_hotelFixtureData.MockedExpectedHotel.Address, result.Address); Assert.Equal(_hotelFixtureData.MockedExpectedHotel.Email, result.Email); Assert.Equal(_hotelFixtureData.MockedExpectedHotel.CountryId, result.CountryId); Assert.Equal(_hotelFixtureData.MockedExpectedHotel.HotelCategoryId, result.HotelCategoryId); Assert.Equal(_hotelFixtureData.MockedExpectedHotel.Web, result.Web); Assert.Equal(_hotelFixtureData.MockedExpectedHotel.CountryName, result.CountryName); Assert.Equal(_hotelFixtureData.MockedExpectedHotel.HotelCategory, result.HotelCategory); } [Fact] public void MapHotelData_HotelExist_TheWebPropertyShouldBeEmpty() { //Arrange var hotelId = 1; var hotelCategoryId = 1; var countryId = 1; var country = "Macedonia"; var hotel = new Hotel { Id = 3, Code = "03", Name = "Diplomat Hotel", Description = "Description", City = "Ohrid", Address = "BB", Email = "test@in.com", CountryId = 1, HotelCategoryId = 1, Web = "https://diplomat" }; var hotelCategory = new HotelCategory { Id = 1, Code = "03", Description = "4 STARS" }; mockHotelRepository.Setup(x => x.GetHotel(hotelId)).Returns(hotel); mockHotelRepository.Setup(x => x.GetHotelCategory(hotelCategoryId)).Returns(hotelCategory); mockCountryRepository.Setup(x => x.GetCountryName(countryId)).Returns(country); //Act var searchService = new SearchService(mockCountryRepository.Object, mockHotelRepository.Object); var result = searchService.MapHotelData(hotel); //Assert Assert.Null(result.Web); } public void Dispose() { //throw new NotImplementedException(); } #endregion [Fact] public void Search_VerifyMethodsCalls_ShouldBeCalledOnce() { //Arrange mockHotelRepository.Setup(x => x.GetHotelsByCategory(It.IsAny<int>())).Returns(new List<Hotel>()); //Act var searchService = new SearchService(mockCountryRepository.Object, mockHotelRepository.Object); searchService.Search(_hotelFixtureData.ValidRequestCase1); //Assert mockHotelRepository.Verify(x => x.GetHotelsByCategory(It.IsAny<int>()), Times.Once); mockHotelRepository.Verify(x => x.GetHotels(), Times.Once); } } }
39.529183
229
0.631755
[ "MIT" ]
dejan0zdravkovski/sk2020-dotnetunittest-01
src/Module02/SEDC.Travel.Service.Tests/02/SearchServiceTest.cs
10,161
C#
using System; using System.Linq; using System.Web.UI; using System.Web.UI.WebControls; using CMS.Base; using CMS.Base.Web.UI; using CMS.Helpers; using CMS.PortalEngine; using CMS.PortalEngine.Web.UI; using AjaxControlToolkit; public partial class CMSWebParts_Layouts_Tabs : CMSAbstractLayoutWebPart { #region "Variables" private TabContainer tabs = null; #endregion #region "Public properties" /// <summary> /// Number of tabs. /// </summary> public int Tabs { get { return ValidationHelper.GetInteger(GetValue("Tabs"), 2); } set { SetValue("Tabs", value); } } /// <summary> /// Tab headers. /// </summary> public string TabHeaders { get { return ValidationHelper.GetString(GetValue("TabHeaders"), ""); } set { SetValue("TabHeaders", value); } } /// <summary> /// Active tab index. /// </summary> public int ActiveTabIndex { get { return ValidationHelper.GetInteger(GetValue("ActiveTabIndex"), 0); } set { SetValue("ActiveTabIndex", value); } } /// <summary> /// Hide empty tabs /// </summary> public bool HideEmptyTabs { get { return ValidationHelper.GetBoolean(GetValue("HideEmptyTabs"), false); } set { SetValue("HideEmptyTabs", value); } } /// <summary> /// Hide if no tabs are visible /// </summary> public bool HideIfNoTabsVisible { get { return ValidationHelper.GetBoolean(GetValue("HideIfNoTabsVisible"), true); } set { SetValue("HideIfNoTabsVisible", value); } } /// <summary> /// Tab strip placement. /// </summary> public string TabStripPlacement { get { return ValidationHelper.GetString(GetValue("TabStripPlacement"), "top"); } set { SetValue("TabStripPlacement", value); } } /// <summary> /// Width. /// </summary> public string Width { get { return ValidationHelper.GetString(GetValue("Width"), ""); } set { SetValue("Width", value); } } /// <summary> /// Height. /// </summary> public string Height { get { return ValidationHelper.GetString(GetValue("Height"), ""); } set { SetValue("Height", value); } } /// <summary> /// Tabs CSS class. /// </summary> public string TabsCSSClass { get { return ValidationHelper.GetString(GetValue("TabsCSSClass"), ""); } set { SetValue("TabsCSSClass", value); } } /// <summary> /// Scrollbars. /// </summary> public string Scrollbars { get { return ValidationHelper.GetString(GetValue("Scrollbars"), ""); } set { SetValue("Scrollbars", value); } } #endregion #region "Page events" /// <summary> /// Render event handler /// </summary> protected override void Render(HtmlTextWriter writer) { if (HideIfNoTabsVisible) { // Check if some tab is visible Visible = tabs.Tabs.Cast<CMSTabPanel>().Any(tab => tab.Visible); } if(Visible) { const string preventFocusLoadScript = @" Sys.Extended.UI.TabContainer.prototype._app_onload = function (sender, e) { if (this._cachedActiveTabIndex != -1) { this.set_activeTabIndex(this._cachedActiveTabIndex); this._cachedActiveTabIndex = -1; var activeTab = this.get_tabs()[this._activeTabIndex]; if (activeTab) { activeTab._wasLoaded = true; /*** CMS ***/ // Disable focus on active tab //activeTab._setFocus(activeTab); /*** END CMS ***/ } } this._loaded = true; } "; // Register script preventing focusing active tab (caused scrolling to tab container - e.g. to the bottom of the page) ScriptHelper.RegisterStartupScript(this, typeof(string), "preventTabFocus", preventFocusLoadScript, true); } base.Render(writer); } #endregion #region "Methods" /// <summary> /// Prepares the layout of the web part. /// </summary> protected override void PrepareLayout() { StartLayout(); Append("<div"); // Width string width = Width; if (!string.IsNullOrEmpty(width)) { Append(" style=\"width: ", width, "\""); } if (IsDesign) { Append(" id=\"", ShortClientID, "_env\">"); Append("<table class=\"LayoutTable\" cellspacing=\"0\" style=\"width: 100%;\">"); switch (ViewMode) { case ViewModeEnum.Design: case ViewModeEnum.DesignDisabled: { Append("<tr><td class=\"LayoutHeader\" colspan=\"2\">"); // Add header container AddHeaderContainer(); Append("</td></tr>"); } break; } Append("<tr><td style=\"width: 100%;\">"); } else { Append(">"); } // Add the tabs tabs = new TabContainer(); tabs.ID = "tabs"; AddControl(tabs); if (IsDesign) { Append("</td>"); // Resizers if (AllowDesignMode) { // Width resizer Append("<td class=\"HorizontalResizer\" onmousedown=\"", GetHorizontalResizerScript("env", "Width", false, "tabs_body"), " return false;\">&nbsp;</td></tr>"); // Height resizer Append("<tr><td class=\"VerticalResizer\" onmousedown=\"", GetVerticalResizerScript("tabs_body", "Height"), " return false;\">&nbsp;</td>"); Append("<td class=\"BothResizer\" onmousedown=\"", GetHorizontalResizerScript("env", "Width", false, "tabs_body"), " ", GetVerticalResizerScript("tabs_body", "Height"), " return false;\">&nbsp;</td>"); } Append("</tr>"); } // Tab headers string[] headers = TextHelper.EnsureLineEndings(TabHeaders, "\n").Split('\n'); if ((ActiveTabIndex >= 1) && (ActiveTabIndex <= Tabs)) { tabs.ActiveTabIndex = ActiveTabIndex - 1; } bool hideEmpty = HideEmptyTabs; for (int i = 1; i <= Tabs; i++) { // Create new tab CMSTabPanel tab = new CMSTabPanel(); tab.ID = "tab" + i; // Prepare the header string header = null; if (headers.Length >= i) { header = ResHelper.LocalizeString(headers[i - 1]); header = HTMLHelper.HTMLEncode(header); } if (String.IsNullOrEmpty(header)) { header = "Tab " + i; } tab.HeaderText = header; tab.HideIfZoneEmpty = hideEmpty; tabs.Tabs.Add(tab); tab.WebPartZone = AddZone(ID + "_" + i, header, tab); } // Setup the tabs tabs.ScrollBars = ControlsHelper.GetScrollbarsEnum(Scrollbars); if (!String.IsNullOrEmpty(TabsCSSClass)) { tabs.CssClass = TabsCSSClass; } tabs.TabStripPlacement = GetTabStripPlacement(TabStripPlacement); if (!String.IsNullOrEmpty(Height)) { tabs.Height = new Unit(Height); } if (IsDesign) { // Footer if (AllowDesignMode) { Append("<tr><td class=\"LayoutFooter cms-bootstrap\" colspan=\"2\"><div class=\"LayoutFooterContent\">"); Append("<div class=\"LayoutLeftActions\">"); // Pane actions AppendAddAction(ResHelper.GetString("Layout.AddTab"), "Tabs"); if (Tabs > 1) { AppendRemoveAction(ResHelper.GetString("Layout.RemoveTab"), "Tabs"); } Append("</div></div></td></tr>"); } Append("</table>"); } Append("</div>"); FinishLayout(); } /// <summary> /// Gets the tab strip placement based on the string representation /// </summary> /// <param name="placement">Placement</param> protected TabStripPlacement GetTabStripPlacement(string placement) { switch (placement.ToLowerCSafe()) { case "bottom": return AjaxControlToolkit.TabStripPlacement.Bottom; case "bottomright": return AjaxControlToolkit.TabStripPlacement.BottomRight; case "topright": return AjaxControlToolkit.TabStripPlacement.TopRight; default: return AjaxControlToolkit.TabStripPlacement.Top; } } #endregion }
23.605985
217
0.501056
[ "MIT" ]
BryanSoltis/KenticoMVCWidgetShowcase
CMS/CMSWebParts/Layouts/Tabs.ascx.cs
9,468
C#
using System; using UnityEngine.InputSystem.LowLevel; #if ENABLE_VR using UnityEngine.XR; #endif namespace UnityEngine.InputSystem.XR { /// <summary> /// The TrackedPoseDriver component applies the current Pose value of a tracked device to the transform of the GameObject. /// TrackedPoseDriver can track multiple types of devices including XR HMDs, controllers, and remotes. /// </summary> [Serializable] [AddComponentMenu("XR/Tracked Pose Driver (New Input System)")] public class TrackedPoseDriver : MonoBehaviour { public enum TrackingType { RotationAndPosition, RotationOnly, PositionOnly } [SerializeField] TrackingType m_TrackingType; /// <summary> /// The tracking type being used by the tracked pose driver /// </summary> public TrackingType trackingType { get { return m_TrackingType; } set { m_TrackingType = value; } } public enum UpdateType { UpdateAndBeforeRender, Update, BeforeRender, } [SerializeField] UpdateType m_UpdateType = UpdateType.UpdateAndBeforeRender; /// <summary> /// The update type being used by the tracked pose driver /// </summary> public UpdateType updateType { get { return m_UpdateType; } set { m_UpdateType = value; } } [SerializeField] InputAction m_PositionAction; public InputAction positionAction { get { return m_PositionAction; } set { UnbindPosition(); m_PositionAction = value; BindActions(); } } [SerializeField] InputAction m_RotationAction; public InputAction rotationAction { get { return m_RotationAction; } set { UnbindRotation(); m_RotationAction = value; BindActions(); } } Vector3 m_CurrentPosition = Vector3.zero; Quaternion m_CurrentRotation = Quaternion.identity; bool m_RotationBound = false; bool m_PositionBound = false; void BindActions() { BindPosition(); BindRotation(); } void BindPosition() { if (!m_PositionBound && m_PositionAction != null) { m_PositionAction.Rename($"{gameObject.name} - TPD - Position"); m_PositionAction.performed += OnPositionUpdate; m_PositionBound = true; m_PositionAction.Enable(); } } void BindRotation() { if (!m_RotationBound && m_RotationAction != null) { m_RotationAction.Rename($"{gameObject.name} - TPD - Rotation"); m_RotationAction.performed += OnRotationUpdate; m_RotationBound = true; m_RotationAction.Enable(); } } void UnbindActions() { UnbindPosition(); UnbindRotation(); } void UnbindPosition() { if (m_PositionAction != null && m_PositionBound) { m_PositionAction.Disable(); m_PositionAction.performed -= OnPositionUpdate; m_PositionBound = false; } } void UnbindRotation() { if (m_RotationAction != null && m_RotationBound) { m_RotationAction.Disable(); m_RotationAction.performed -= OnRotationUpdate; m_RotationBound = false; } } void OnPositionUpdate(InputAction.CallbackContext context) { Debug.Assert(m_PositionBound); m_CurrentPosition = context.ReadValue<Vector3>(); } void OnRotationUpdate(InputAction.CallbackContext context) { Debug.Assert(m_RotationBound); m_CurrentRotation = context.ReadValue<Quaternion>(); } protected virtual void Awake() { #if ENABLE_VR && UNITY_INPUT_SYSTEM_ENABLE_XR if (HasStereoCamera()) { XRDevice.DisableAutoXRCameraTracking(GetComponent<Camera>(), true); } #endif } protected void OnEnable() { InputSystem.onAfterUpdate += UpdateCallback; BindActions(); } void OnDisable() { UnbindActions(); InputSystem.onAfterUpdate -= UpdateCallback; } protected virtual void OnDestroy() { #if ENABLE_VR && UNITY_INPUT_SYSTEM_ENABLE_XR if (HasStereoCamera()) { XRDevice.DisableAutoXRCameraTracking(GetComponent<Camera>(), false); } #endif } protected void UpdateCallback() { if (InputState.currentUpdateType == InputUpdateType.BeforeRender) OnBeforeRender(); else OnUpdate(); } protected virtual void OnUpdate() { if (m_UpdateType == UpdateType.Update || m_UpdateType == UpdateType.UpdateAndBeforeRender) { PerformUpdate(); } } protected virtual void OnBeforeRender() { if (m_UpdateType == UpdateType.BeforeRender || m_UpdateType == UpdateType.UpdateAndBeforeRender) { PerformUpdate(); } } protected virtual void SetLocalTransform(Vector3 newPosition, Quaternion newRotation) { if (m_TrackingType == TrackingType.RotationAndPosition || m_TrackingType == TrackingType.RotationOnly) { transform.localRotation = newRotation; } if (m_TrackingType == TrackingType.RotationAndPosition || m_TrackingType == TrackingType.PositionOnly) { transform.localPosition = newPosition; } } private bool HasStereoCamera() { var camera = GetComponent<Camera>(); return camera != null && camera.stereoEnabled; } protected virtual void PerformUpdate() { SetLocalTransform(m_CurrentPosition, m_CurrentRotation); } } }
27.987288
126
0.537169
[ "MIT" ]
Ayshie-God/7382-Team-D-2020
7382-Team-D-2020/Horror Escape Puzzle Game/Library/PackageCache/com.unity.inputsystem@1.0.0-preview.5/InputSystem/Plugins/XR/TrackedPoseDriver.cs
6,605
C#
using System; using System.Collections.Generic; using System.Linq; using UnityEditor; using UnityEngine; using UnityEngine.UIElements; using UnityEditor.UIElements; using Toolbar = UnityEditor.UIElements.Toolbar; namespace UIElementsExamples { public class E19_Breadcrumbs : EditorWindow { [MenuItem("UIElementsExamples/19_Breadcrumbs")] public static void ShowExample() { E19_Breadcrumbs window = GetWindow<E19_Breadcrumbs>(); window.minSize = new Vector2(200, 200); window.titleContent = new GUIContent("Example 18"); } ScrollView m_ListContainer; ToolbarBreadcrumbs m_Breadcrumbs; static string RootName => "Wish list"; static string TitleClass => "wishlist-title"; static string ItemClass => "wishlist-item"; string m_CurrentContentName; Dictionary<string, string> m_Parents; Dictionary<string, string[]> m_Children; public void OnEnable() { InitElements(); var root = rootVisualElement; root.styleSheets.Add(AssetDatabase.LoadAssetAtPath<StyleSheet>("Assets/Examples/Editor/breadcrumbs-demo.uss")); var toolbar = new Toolbar(); root.Add(toolbar); var btn1 = new ToolbarButton(LoadRandomContent) { text = "Random" }; toolbar.Add(btn1); toolbar.Add(new ToolbarSpacer()); m_Breadcrumbs = new ToolbarBreadcrumbs(); toolbar.Add(m_Breadcrumbs); var box = new Box(); m_ListContainer = new ScrollView(); m_ListContainer.showHorizontal = false; box.Add(m_ListContainer); root.Add(box); LoadContentByName(RootName); } void LoadRandomContent() { int randomIndex = UnityEngine.Random.Range(0, m_Children.Count - 1); string randomContent = m_Children.Keys.ElementAt(randomIndex); // don't pick the same twice at it can make it look like the button did nothing if (randomContent == m_CurrentContentName) randomContent = m_Children.Keys.Last(); LoadContentByName(randomContent); } void InitElements() { m_Children = new Dictionary<string, string[]>(); m_Parents = new Dictionary<string, string>(); AddChildren(RootName, new[] { "Food", "Tech", "Cars" }); AddChildren("Tech", new[] { "Computer", "Smart-phone", "Smart-watch" }); AddChildren("Cars", new[] { "Porsche", "BMW", "Tesla" }); AddChildren("Porsche", new[] { "GT4", "Cayenne" }); AddChildren("BMW", new[] { "E90 M3", "507" }); AddChildren("Tesla", new[] { "S", "3", "X", "Y" }); AddChildren("Porsche", new[] { "GT4", "Cayenne" }); AddChildren("Food", new[] { "Fruits", "Dairies", "Vegetables" }); AddChildren("Fruits", new[] { "Pears", "Apples", "Blueberries", "Cranberries" }); AddChildren("Dairies", new[] { "Milk", "Cheese", "Yogurt" }); AddChildren("Vegetables", new[] { "French fries", "Gravy", "Cheese curds" }); AddChildren("Cheese", new[] { "Gouda", "Camembert", "Queso Fresco", "Parmigiano Reggiano" }); } void AddChildren(string title, string[] children) { m_Children[title] = children; foreach (var child in children) { m_Parents[child] = title; } } void LoadContentByName(string contentName) { m_CurrentContentName = contentName; m_ListContainer.Clear(); var label = new Label(contentName); label.AddToClassList(TitleClass); m_ListContainer.Add(label); foreach (var child in m_Children[contentName]) { bool hasChildren = m_Children.ContainsKey(child); Action clickEvent = null; if (hasChildren) { clickEvent = () => LoadContentByName(child); } var button = new Button(clickEvent) {text = child }; button.SetEnabled(hasChildren); button.AddToClassList(ItemClass); m_ListContainer.Add(button); } BuildBreadCrumbs(contentName); } void BuildBreadCrumbs(string contentName) { m_Breadcrumbs.Clear(); List<string> contentTitles = new List<string>(); for (var c = contentName; m_Parents.TryGetValue(c, out var parent); c = parent) { contentTitles.Add(parent); } foreach (string title in Enumerable.Reverse(contentTitles)) { m_Breadcrumbs.PushItem(title, () => LoadContentByName(title)); } m_Breadcrumbs.PushItem(contentName); } } }
33.433333
123
0.56331
[ "MIT" ]
suweitao1998/Editor_Example
Assets/Examples/Editor/E19_Breadcrumbs.cs
5,015
C#
using AbhsChinese.Code.Common; using AbhsChinese.Domain.Dto.Request.School; using AbhsChinese.Domain.Dto.Response; using AbhsChinese.Domain.Dto.Response.School; using AbhsChinese.Domain.Entity.School; using AbhsChinese.Repository.IRepository.School; using AbhsChinese.Repository.Repository.School; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AbhsChinese.Bll { public class SchoolTeacherBll { #region repository private ISchoolTeacherRepository schoolTeacherRepository; public ISchoolTeacherRepository SchoolTeacherRepository { get { if (schoolTeacherRepository == null) { schoolTeacherRepository = new SchoolTeacherRepository(); } return schoolTeacherRepository; } } #endregion #region select /// <summary> /// 学校教师列表 /// </summary> /// <param name="search"></param> /// <returns></returns> public List<DtoSchoolTeacher> GetSchoolTeacherList(DtoSchoolTeacherSearch search) { return SchoolTeacherRepository.GetSchoolTeacherList(search); } /// <summary> /// 学校教师实体 /// </summary> /// <param name="teacherId"></param> /// <returns></returns> public Yw_SchoolTeacher GetSchoolTeacher(int teacherId) { return SchoolTeacherRepository.Get(teacherId); } public List<DtoKeyValue<int, string>> GetTeacherByGrade(int grade, int schoolId) { var list = SchoolTeacherRepository.GetTeacherByGrade(grade, schoolId); return list.Select(s => { return new DtoKeyValue<int, string>() { key = s.Yoh_Id, value = s.Yoh_Name }; }).ToList(); } /// <summary> /// 校验教师手机唯一性 /// </summary> /// <param name="phone"></param> /// <returns></returns> public int GetSchoolTeacherCountByPhone(string phone) { return SchoolTeacherRepository.GetCountByPhone(phone); } public DtoSchoolTeacher GetSchoolTeacherByPhone(string phone) { return SchoolTeacherRepository.GetSchoolTeacherByPhone(phone); } public Yw_SchoolTeacher GetEntity(int id) { return SchoolTeacherRepository.Get(id); } public DtoSchoolTeacher Login(string account, string pwd) { DtoSchoolTeacher result = null; var teacher = SchoolTeacherRepository.GetSchoolTeacherByPhone(account); if (teacher != null) { result = teacher.Yoh_Password == Encrypt.GetMD5Pwd(pwd) ? teacher : null; } return result; } #endregion #region insert public int InsertEntity(Yw_SchoolTeacher entity) { return SchoolTeacherRepository.Insert(entity); } #endregion #region update public bool UpdateStatus(int id, int toStatus, int edit) { return SchoolTeacherRepository.UpdateStatus(id, toStatus, edit); } public bool UpdatePwd(int id, string pwd, int edit = 0) { return SchoolTeacherRepository.UpdatePwd(id, pwd, edit); } #endregion #region save /// <summary> /// 保存学校教师 /// </summary> /// <param name="newModel"></param> /// <returns></returns> public bool SaveSchoolTeacher(Yw_SchoolTeacher newModel) { if (newModel.Yoh_Id > 0) { return SchoolTeacherRepository.Update(newModel); } else { newModel.Yoh_CreateTime = DateTime.Now; newModel.Yoh_UpdateTime = DateTime.Now; return SchoolTeacherRepository.Insert(newModel) > 0; } } #endregion } }
29.794118
128
0.583416
[ "Apache-2.0" ]
GuoQqizz/SmartChinese
AbhsChinese.Bll/SchoolTeacherBll.cs
4,108
C#
//------------------------------------------------------------------------------ // <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> //------------------------------------------------------------------------------ using System; using Newtonsoft.Json; namespace BungieNet.Destiny.Definitions.Milestones { /// <summary> /// Represents a variant on an activity for a Milestone: a specific difficulty tier, or a specific activity variant for example. /// These will often have more specific details, such as an associated Guided Game, progression steps, tier-specific rewards, and custom values. /// </summary> public partial class DestinyMilestoneActivityVariantDefinition { [JsonProperty("activityHash")] public uint ActivityHash { get; set; } [JsonProperty("order")] public int Order { get; set; } } }
34.392857
145
0.607477
[ "BSD-3-Clause" ]
KiaArmani/XurSuite
Libraries/MadReflection.BungieApi/MadReflection.BungieNetApi.Entities/Generated_/Destiny/Definitions/Milestones/DestinyMilestoneActivityVariantDefinition.cs
965
C#
using System; using System.Collections.Generic; using System.Text; using System.Text.RegularExpressions; namespace MarkdownTool.Model { class DocGenericPrimitive : DocPrimitive { private static readonly Regex GenericCountRgx = new Regex("`(\\d+)"); public DocPrimitive[] TypeParameters { get; set; } public string SanitisedName => Sanitise(Name); public string SanitisedNameWithoutNamespace => Sanitise(NameWithoutNamespace); public string Sanitise(string s) { Match m = GenericCountRgx.Match(s); if (m.Success && TypeParameters != null) { string replacement = "<"; for (int i = 0; i < TypeParameters.Length; i++) { if (i != 0) replacement += ", "; replacement += TypeParameters[i].Name; } replacement += ">"; return GenericCountRgx.Replace(s, replacement); } return s; } } }
25.842105
84
0.586558
[ "MIT" ]
aloneguid/dotnet-markdown-cli-tool
src/MarkdownTool/Model/DocGenericPrimitive.cs
984
C#
using System; using System.Collections.Generic; using System.Linq; using System.Security.Claims; using ScooterApp.Domain.Auth; namespace ScooterApp.Extensions.Authentication { public static class PrincipalExtensions { public static RiderClaim ToRiderClaims(this ClaimsPrincipal claimsPrincipal) { if (claimsPrincipal?.Claims == null || !claimsPrincipal.Claims.Any<Claim>()) return (RiderClaim)null; List<Claim> list = claimsPrincipal.Claims.ToList<Claim>(); return new RiderClaim { AreaId = list.GetClaimValue("AreaId"), FirstName = list.GetClaimValue("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname"), LastName = list.GetClaimValue("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surname"), UserId = list.GetClaimValue("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier"), Claims = list.ToDictionary<Claim, string, string>((Func<Claim, string>)(x => x.Type), (Func<Claim, string>)(x => x.Value)), SignInName = list.GetClaimValue("signInName"), EmailAddress = list.GetClaimValue("signInName"), Salutation = list.GetClaimValue("extension_Salutation") }; } private static string GetClaimValue(this IEnumerable<Claim> claims, string name) { return claims.SingleOrDefault<Claim>((Func<Claim, bool>)(x => x.Type.Equals(name, StringComparison.InvariantCultureIgnoreCase)))?.Value; } } }
45.8
148
0.646288
[ "MIT" ]
EhsanAminii/e-scooter
ScooterApp.Extensions/Authentication/PrincipalExtensions.cs
1,605
C#
using MBBSEmu.Memory; using MBBSEmu.Module; using System.Collections.Generic; using System.Text; using Xunit; namespace MBBSEmu.Tests.ExportedModules.Majorbbs { public class stgopt_Tests : ExportedModuleTestBase { private const int STGOPT_ORDINAL = 566; [Theory] [InlineData("Normal")] [InlineData("")] [InlineData("123456")] [InlineData("--==---")] [InlineData("!@)#!*$")] public void stgopt_Test(string msgValue) { //Reset State Reset(); //Set Argument Values to be Passed In var mcvPointer = (ushort)majorbbs.McvPointerDictionary.Allocate(new McvFile("TEST.MCV", new Dictionary<int, byte[]> { { 0, Encoding.ASCII.GetBytes(msgValue) } })); mbbsEmuMemoryCore.SetPointer("CURRENT-MCV", new FarPtr(0xFFFF, mcvPointer)); //Execute Test ExecuteApiTest(HostProcess.ExportedModules.Majorbbs.Segment, STGOPT_ORDINAL, new List<ushort> { 0 }); //Verify Results Assert.Equal(msgValue, Encoding.ASCII.GetString(mbbsEmuMemoryCore.GetString(mbbsEmuCpuRegisters.DX, mbbsEmuCpuRegisters.AX, true))); } } }
31.973684
144
0.62716
[ "MIT" ]
enusbaum/MBBSEmu
MBBSEmu.Tests/ExportedModules/Majorbbs/stgopt_Tests.cs
1,217
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:2.0.50727.4016 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace TABS_UserControls.usercontrols { public partial class news_tabs { /// <summary> /// repeatNews control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Repeater repeatNews; } }
32.384615
85
0.472684
[ "Apache-2.0" ]
cmorrow/cmorrow.github.io
portfolio/TABS/web/usercontrols/news_tabs.ascx.designer.cs
842
C#
using WebApp_TransportCompany.Models; namespace WebApp_TransportCompany.ViewModels { public class TruckFormPartialViewModel { public Truck Truck { get; set; } } }
18.5
44
0.724324
[ "MIT" ]
YusupFayzrahmanov/WebApp_TransportCompany
ViewModels/TruckFormPartialViewModel.cs
187
C#
//------------------------------------------------------------------------------ // <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 DLaB.Xrm.Entities { /// <summary> /// Trace and exception information generated by plug-ins and custom workflow activities. /// </summary> [System.Runtime.Serialization.DataContractAttribute()] [Microsoft.Xrm.Sdk.Client.EntityLogicalNameAttribute("plugintracelog")] [System.CodeDom.Compiler.GeneratedCodeAttribute("CrmSvcUtil", "9.0.0.9369")] public partial class PluginTraceLog : Microsoft.Xrm.Sdk.Entity, System.ComponentModel.INotifyPropertyChanging, System.ComponentModel.INotifyPropertyChanged { public static class Fields { public const string Configuration = "configuration"; public const string CorrelationId = "correlationid"; public const string CreatedBy = "createdby"; public const string CreatedOn = "createdon"; public const string CreatedOnBehalfBy = "createdonbehalfby"; public const string Depth = "depth"; public const string ExceptionDetails = "exceptiondetails"; public const string IsSystemCreated = "issystemcreated"; public const string MessageBlock = "messageblock"; public const string MessageName = "messagename"; public const string Mode = "mode"; public const string OperationType = "operationtype"; public const string OrganizationId = "organizationid"; public const string PerformanceConstructorDuration = "performanceconstructorduration"; public const string PerformanceConstructorStartTime = "performanceconstructorstarttime"; public const string PerformanceExecutionDuration = "performanceexecutionduration"; public const string PerformanceExecutionStartTime = "performanceexecutionstarttime"; public const string PersistenceKey = "persistencekey"; public const string PluginStepId = "pluginstepid"; public const string PluginTraceLogId = "plugintracelogid"; public const string Id = "plugintracelogid"; public const string PrimaryEntity = "primaryentity"; public const string Profile = "profile"; public const string RequestId = "requestid"; public const string SecureConfiguration = "secureconfiguration"; public const string TypeName = "typename"; public const string createdby_plugintracelog = "createdby_plugintracelog"; public const string lk_plugintracelogbase_createdonbehalfby = "lk_plugintracelogbase_createdonbehalfby"; } /// <summary> /// Default Constructor. /// </summary> [System.Diagnostics.DebuggerNonUserCode()] public PluginTraceLog() : base(EntityLogicalName) { } public const string EntityLogicalName = "plugintracelog"; public const string PrimaryIdAttribute = "plugintracelogid"; public const string PrimaryNameAttribute = "typename"; public const int EntityTypeCode = 4619; public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged; public event System.ComponentModel.PropertyChangingEventHandler PropertyChanging; [System.Diagnostics.DebuggerNonUserCode()] private void OnPropertyChanged(string propertyName) { if ((this.PropertyChanged != null)) { this.PropertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName)); } } [System.Diagnostics.DebuggerNonUserCode()] private void OnPropertyChanging(string propertyName) { if ((this.PropertyChanging != null)) { this.PropertyChanging(this, new System.ComponentModel.PropertyChangingEventArgs(propertyName)); } } /// <summary> /// Unsecured configuration for the plug-in trace log. /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("configuration")] public string Configuration { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<string>("configuration"); } } /// <summary> /// Unique identifier for tracking plug-in or custom workflow activity execution. /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("correlationid")] public System.Nullable<System.Guid> CorrelationId { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<System.Nullable<System.Guid>>("correlationid"); } } /// <summary> /// Unique identifier of the delegate user who created the record. /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("createdby")] public Microsoft.Xrm.Sdk.EntityReference CreatedBy { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<Microsoft.Xrm.Sdk.EntityReference>("createdby"); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("CreatedBy"); this.SetAttributeValue("createdby", value); this.OnPropertyChanged("CreatedBy"); } } /// <summary> /// Date and time when the record was created. /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("createdon")] public System.Nullable<System.DateTime> CreatedOn { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<System.Nullable<System.DateTime>>("createdon"); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("CreatedOn"); this.SetAttributeValue("createdon", value); this.OnPropertyChanged("CreatedOn"); } } /// <summary> /// Unique identifier of the delegate user who created the record. /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("createdonbehalfby")] public Microsoft.Xrm.Sdk.EntityReference CreatedOnBehalfBy { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<Microsoft.Xrm.Sdk.EntityReference>("createdonbehalfby"); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("CreatedOnBehalfBy"); this.SetAttributeValue("createdonbehalfby", value); this.OnPropertyChanged("CreatedOnBehalfBy"); } } /// <summary> /// Depth of execution of the plug-in or custom workflow activity. /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("depth")] public System.Nullable<int> Depth { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<System.Nullable<int>>("depth"); } } /// <summary> /// Details of the exception. /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("exceptiondetails")] public string ExceptionDetails { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<string>("exceptiondetails"); } } /// <summary> /// Where the event originated. Set to true if it's a system trace; otherwise, false. /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("issystemcreated")] public System.Nullable<bool> IsSystemCreated { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<System.Nullable<bool>>("issystemcreated"); } } /// <summary> /// Trace text from the plug-in. /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("messageblock")] public string MessageBlock { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<string>("messageblock"); } } /// <summary> /// Name of the message that triggered this plug-in. /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("messagename")] public string MessageName { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<string>("messagename"); } } /// <summary> /// Type of execution. /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("mode")] public Microsoft.Xrm.Sdk.OptionSetValue Mode { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<Microsoft.Xrm.Sdk.OptionSetValue>("mode"); } } /// <summary> /// Type of custom code. /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("operationtype")] public Microsoft.Xrm.Sdk.OptionSetValue OperationType { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<Microsoft.Xrm.Sdk.OptionSetValue>("operationtype"); } } /// <summary> /// Unique identifier for the organization. /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("organizationid")] public System.Nullable<System.Guid> OrganizationId { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<System.Nullable<System.Guid>>("organizationid"); } } /// <summary> /// Time, in milliseconds, to construct. /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("performanceconstructorduration")] public System.Nullable<int> PerformanceConstructorDuration { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<System.Nullable<int>>("performanceconstructorduration"); } } /// <summary> /// Date and time when constructed. /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("performanceconstructorstarttime")] public System.Nullable<System.DateTime> PerformanceConstructorStartTime { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<System.Nullable<System.DateTime>>("performanceconstructorstarttime"); } } /// <summary> /// Time, in milliseconds, to execute the request. /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("performanceexecutionduration")] public System.Nullable<int> PerformanceExecutionDuration { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<System.Nullable<int>>("performanceexecutionduration"); } } /// <summary> /// Time, in milliseconds, to execute the request. /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("performanceexecutionstarttime")] public System.Nullable<System.DateTime> PerformanceExecutionStartTime { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<System.Nullable<System.DateTime>>("performanceexecutionstarttime"); } } /// <summary> /// Asynchronous workflow persistence key. /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("persistencekey")] public System.Nullable<System.Guid> PersistenceKey { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<System.Nullable<System.Guid>>("persistencekey"); } } /// <summary> /// ID of the plug-in registration step. /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("pluginstepid")] public System.Nullable<System.Guid> PluginStepId { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<System.Nullable<System.Guid>>("pluginstepid"); } } /// <summary> /// Unique identifier for an entity instance. /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("plugintracelogid")] public System.Nullable<System.Guid> PluginTraceLogId { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<System.Nullable<System.Guid>>("plugintracelogid"); } } [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("plugintracelogid")] public override System.Guid Id { [System.Diagnostics.DebuggerNonUserCode()] get { return base.Id; } [System.Diagnostics.DebuggerNonUserCode()] set { base.Id = value; } } /// <summary> /// Entity, if any, that the plug-in is executed against. /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("primaryentity")] public string PrimaryEntity { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<string>("primaryentity"); } } /// <summary> /// Plug-in profile formatted as serialized text. /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("profile")] public string Profile { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<string>("profile"); } } /// <summary> /// Unique identifier of the message request. /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("requestid")] public System.Nullable<System.Guid> RequestId { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<System.Nullable<System.Guid>>("requestid"); } } /// <summary> /// Secured configuration for the plug-in trace log. /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("secureconfiguration")] public string SecureConfiguration { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<string>("secureconfiguration"); } } /// <summary> /// Class name of the plug-in. /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("typename")] public string TypeName { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<string>("typename"); } } /// <summary> /// N:1 createdby_plugintracelog /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("createdby")] [Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("createdby_plugintracelog")] public DLaB.Xrm.Entities.SystemUser createdby_plugintracelog { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetRelatedEntity<DLaB.Xrm.Entities.SystemUser>("createdby_plugintracelog", null); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("createdby_plugintracelog"); this.SetRelatedEntity<DLaB.Xrm.Entities.SystemUser>("createdby_plugintracelog", null, value); this.OnPropertyChanged("createdby_plugintracelog"); } } /// <summary> /// N:1 lk_plugintracelogbase_createdonbehalfby /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("createdonbehalfby")] [Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("lk_plugintracelogbase_createdonbehalfby")] public DLaB.Xrm.Entities.SystemUser lk_plugintracelogbase_createdonbehalfby { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetRelatedEntity<DLaB.Xrm.Entities.SystemUser>("lk_plugintracelogbase_createdonbehalfby", null); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("lk_plugintracelogbase_createdonbehalfby"); this.SetRelatedEntity<DLaB.Xrm.Entities.SystemUser>("lk_plugintracelogbase_createdonbehalfby", null, value); this.OnPropertyChanged("lk_plugintracelogbase_createdonbehalfby"); } } /// <summary> /// Constructor for populating via LINQ queries given a LINQ anonymous type /// <param name="anonymousType">LINQ anonymous type.</param> /// </summary> [System.Diagnostics.DebuggerNonUserCode()] public PluginTraceLog(object anonymousType) : this() { foreach (var p in anonymousType.GetType().GetProperties()) { var value = p.GetValue(anonymousType, null); var name = p.Name.ToLower(); if (name.EndsWith("enum") && value.GetType().BaseType == typeof(System.Enum)) { value = new Microsoft.Xrm.Sdk.OptionSetValue((int) value); name = name.Remove(name.Length - "enum".Length); } switch (name) { case "id": base.Id = (System.Guid)value; Attributes["plugintracelogid"] = base.Id; break; case "plugintracelogid": var id = (System.Nullable<System.Guid>) value; if(id == null){ continue; } base.Id = id.Value; Attributes[name] = base.Id; break; case "formattedvalues": // Add Support for FormattedValues FormattedValues.AddRange((Microsoft.Xrm.Sdk.FormattedValueCollection)value); break; default: Attributes[name] = value; break; } } } [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("mode")] public virtual PluginTraceLog_Mode? ModeEnum { [System.Diagnostics.DebuggerNonUserCode()] get { return ((PluginTraceLog_Mode?)(EntityOptionSetEnum.GetEnum(this, "mode"))); } } [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("operationtype")] public virtual PluginTraceLog_OperationType? OperationTypeEnum { [System.Diagnostics.DebuggerNonUserCode()] get { return ((PluginTraceLog_OperationType?)(EntityOptionSetEnum.GetEnum(this, "operationtype"))); } } } }
30.896057
156
0.691415
[ "MIT" ]
ScottColson/XrmUnitTest
DLaB.Xrm.Entities/PluginTraceLog.cs
17,240
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PauseGame : MonoBehaviour { public void Pause(){ if (Time.timeScale > 0) { Time.timeScale = 0; } else { Time.timeScale = 1; } } }
15.933333
40
0.682008
[ "MIT" ]
RavArty/RollocoBall
Assets/Scipts/GamePlayScripts/PauseGame.cs
241
C#
using System; namespace Encapsulation.ConsoleApp { class Program { static void Main(string[] args) { bool keepGoing; do { Console.WriteLine("Do you wish to adopt a dog?"); bool willAdopt = Console.ReadLine().ToLower() == "yes"; Console.Clear(); if (willAdopt) { Console.Write("Type the fur color: "); string furColor = Console.ReadLine(); Console.Write("Type the eye color: "); string eyeColor = Console.ReadLine(); Dog yourNewDog = new Dog(furColor, eyeColor); yourNewDog.PaintFur(Console.ReadLine()); Console.Clear(); Console.WriteLine("Here's your new dog for adoption!"); Console.WriteLine(yourNewDog.GetDogCharacteristics()); Console.ReadKey(); Console.Clear(); } Console.Clear(); Console.WriteLine("Do you wish to continue?"); keepGoing = Console.ReadLine().ToLower() == "yes"; } while (keepGoing); } } }
27.934783
75
0.461479
[ "MIT" ]
SoneSaile/dls-intro
src/Encapsulation/Encapsulation.ConsoleApp/Program.cs
1,287
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; namespace Microsoft.AspNetCore.Razor.Language { public abstract class TagMatchingRuleDescriptorBuilder { public abstract string TagName { get; set; } public abstract string ParentTag { get; set; } public abstract TagStructure TagStructure { get; set; } public abstract RazorDiagnosticCollection Diagnostics { get; } public abstract IReadOnlyList<RequiredAttributeDescriptorBuilder> Attributes { get; } public abstract void Attribute(Action<RequiredAttributeDescriptorBuilder> configure); } }
32.291667
111
0.741935
[ "Apache-2.0" ]
1175169074/aspnetcore
src/Razor/Microsoft.AspNetCore.Razor.Language/src/TagMatchingRuleDescriptorBuilder.cs
777
C#
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved. using System.Reflection; [assembly: AssemblyTitle("NetworkProfiler")] [assembly: AssemblyDescription( "A tool to profile network traffic" )] [assembly: AssemblyConfiguration("")]
30.25
70
0.772727
[ "MIT" ]
CaptainUnknown/UnrealEngine_NVIDIAGameWorks
Engine/Source/Programs/NetworkProfiler/NetworkProfiler/Properties/AssemblyInfo.cs
242
C#
// Copyright (c) 2020, Phoenix Contact GmbH & Co. KG // Licensed under the Apache License, Version 2.0 using Moryx.AbstractionLayer.Resources; using Moryx.AbstractionLayer.Resources.Attributes; using Moryx.Container; using Moryx.Logging; using Moryx.Model; using Moryx.Model.Repositories; using Moryx.Resources.Model.API; using Moryx.Resources.Model.Entities; using Moryx.Tools; using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Reflection; namespace Moryx.Resources.Management.Resources { [Component(LifeCycle.Singleton, typeof(IResourceLinker))] internal class ResourceLinker : IResourceLinker { [UseChild("ResourceLinker")] public IModuleLogger Logger { get; set; } /// <summary> /// Resource graph with all resources /// </summary> public IResourceGraph Graph { get; set; } /// <inheritdoc /> public IReadOnlyList<Resource> SaveRoots(IUnitOfWork uow, IReadOnlyList<Resource> instances) { var context = new ReferenceSaverContext(uow, Graph); foreach (var instance in instances) { SaveReferences(context, instance); } return context.EntityCache.Keys.ToArray(); } /// <inheritdoc /> public void LinkReferences(Resource resource, ICollection<ResourceRelationAccessor> relations) { var resourceType = resource.GetType(); var referenceProperties = ResourceReferenceTools.ReferenceProperties(resourceType, false).ToList(); // Create delegate once to optimize memory usage var resolverDelegate = new Func<ResourceRelationAccessor, Resource>(ResolveRefernceWithGraph); foreach (var property in referenceProperties) { var matches = MatchingRelations(relations, property).ToList(); var resources = InstanceProjection(matches, property, resolverDelegate) .OrderBy(r => r.Name).ToList(); // Link a list of resources if (typeof(IEnumerable<IResource>).IsAssignableFrom(property.PropertyType)) { // Get the reference collection var value = (IReferenceCollection)property.GetValue(resource); foreach (var referencedResource in resources) { value.UnderlyingCollection.Add(referencedResource); } } // Link a single reference else { if (resources.Count == 1) property.SetValue(resource, resources[0]); else if (resources.Count > 1) Logger.Log(LogLevel.Warning, "Inconclusive relation: Can not assign property {0} on {1}:{2} from [{3}]. Too many matches!", property.Name, resource.Id, resource.Name, string.Join(",", matches.Select(m => m.ReferenceId))); else if (matches.Any(m => referenceProperties.All(p => !PropertyMatchesRelation(p, m, Graph.Get(m.ReferenceId))))) Logger.Log(LogLevel.Warning, "Incompatible relation: Resources from [{0}] with relation type {1} can not be assigned to a property on {2}:{3}.", string.Join(",", matches.Select(m => m.ReferenceId)), matches[0].RelationType, resource.Id, resource.Name); } } } private static bool PropertyMatchesRelation(PropertyInfo property, ResourceRelationAccessor relation, Resource instance) { var att = property.GetCustomAttribute<ResourceReferenceAttribute>(); return att.Role == relation.Role && att.RelationType == relation.RelationType && att.Name == relation.Name && property.PropertyType.IsInstanceOfType(instance); } /// <inheritdoc /> public IReadOnlyList<Resource> SaveReferences(IUnitOfWork uow, Resource instance, ResourceEntity entity) { var context = new ReferenceSaverContext(uow, Graph, instance, entity); SaveReferences(context, instance); return context.EntityCache.Keys.Where(i => i.Id == 0).ToList(); } private void SaveReferences(ReferenceSaverContext context, Resource instance) { var entity = GetOrCreateEntity(context, instance); var relations = ResourceRelationAccessor.FromEntity(context.UnitOfWork, entity) .Union(ResourceRelationAccessor.FromQueryable(context.CreatedRelations.AsQueryable(), entity)) .ToList(); var createdResources = new List<Resource>(); foreach (var referenceProperty in ResourceReferenceTools.ReferenceProperties(instance.GetType(), false)) { var matches = MatchingRelations(relations, referenceProperty); var typeMatches = TypeFilter(matches, referenceProperty, context.ResolveReference).ToList(); if (typeof(IEnumerable<IResource>).IsAssignableFrom(referenceProperty.PropertyType)) { // Save a collection reference var created = UpdateCollectionReference(context, entity, instance, referenceProperty, typeMatches); createdResources.AddRange(created); } else { // Save a single reference var createdResource = UpdateSingleReference(context, entity, instance, referenceProperty, typeMatches); if (createdResource != null) createdResources.Add(createdResource); } } // Recursively save references for new resources foreach (var resource in createdResources) SaveReferences(context, resource); } /// <inheritdoc /> public IReadOnlyList<Resource> SaveSingleCollection(IUnitOfWork uow, Resource instance, PropertyInfo property) { var entity = uow.GetEntity<ResourceEntity>(instance); var relations = ResourceRelationAccessor.FromEntity(uow, entity); var context = new ReferenceSaverContext(uow, Graph, instance, entity); var matches = MatchingRelations(relations, property); var typeMatches = TypeFilter(matches, property, context.ResolveReference).ToList(); var created = UpdateCollectionReference(context, entity, instance, property, typeMatches); foreach (var resource in created) SaveReferences(context, resource); return context.EntityCache.Keys.Where(i => i.Id == 0).ToList(); } /// <summary> /// Make sure our resource-relation graph in the database is synced to the resource object graph. This method /// updates single references like in the example below /// </summary> /// <example> /// [ResourceReference(ResourceRelationType.TransportRoute, ResourceReferenceRole.Source)] /// public Resource FriendResource { get; set; } /// </example> private Resource UpdateSingleReference(ReferenceSaverContext context, ResourceEntity entity, Resource resource, PropertyInfo referenceProperty, IReadOnlyList<ResourceRelationAccessor> matches) { var relationRepo = context.UnitOfWork.GetRepository<IResourceRelationRepository>(); var value = referenceProperty.GetValue(resource); var referencedResource = value as Resource; // Validate if object assigned to the property is a resource if (value != null && referencedResource == null) throw new ArgumentException($"Value of property {referenceProperty.Name} on resource {resource.Id}:{resource.GetType().Name} must be a Resource"); var referenceAtt = referenceProperty.GetCustomAttribute<ResourceReferenceAttribute>(); // Validate if required property is set if (referencedResource == null && referenceAtt.IsRequired) throw new ValidationException($"Property {referenceProperty.Name} is flagged 'Required' and was null!"); // Check if there is a relation that represents this reference if (referencedResource != null && matches.Any(m => referencedResource == context.ResolveReference(m))) return null; // Get all references of this resource with the same relation information var currentReferences = CurrentReferences(resource, referenceAtt); // Try to find a match that is not used in any reference var relMatch = (from match in matches where currentReferences.All(cr => cr != context.ResolveReference(match)) select match).FirstOrDefault(); var relEntity = relMatch?.Entity; if (relEntity == null && referencedResource != null) { // Create a new relation relEntity = CreateRelationForProperty(context, relationRepo, referenceAtt); SetOnTarget(referencedResource, resource, referenceAtt); } else if (relEntity != null && referencedResource == null) { // Delete a relation, that no longer exists ClearOnTarget(context.ResolveReference(relMatch), resource, referenceAtt); relationRepo.Remove(relEntity); return null; } // ReSharper disable once ConditionIsAlwaysTrueOrFalse <<- To identify the remaining case else if (relEntity == null && referencedResource == null) { // Relation did not exist before and still does not return null; } // Relation was updated, make sure the backlinks match else { ClearOnTarget(context.ResolveReference(relMatch), resource, referenceAtt); SetOnTarget(referencedResource, resource, referenceAtt); } // Set source and target of the relation depending on the reference roles var referencedEntity = GetOrCreateEntity(context, referencedResource); UpdateRelationEntity(entity, referencedEntity, relEntity, referenceAtt); // Return referenced resource if it is new return referencedResource.Id == 0 ? referencedResource : null; } /// <summary> /// Make sure our resource-relation graph in the database is synced to the resource object graph. This method /// updates a collection of references /// </summary> /// <example> /// [ResourceReference(ResourceRelationType.TransportRoute, ResourceReferenceRole.Source)] /// public IReferences&lt;Resource&gt; FriendResources { get; set; } /// </example> private IEnumerable<Resource> UpdateCollectionReference(ReferenceSaverContext context, ResourceEntity entity, Resource resource, PropertyInfo referenceProperty, IReadOnlyList<ResourceRelationAccessor> relationTemplates) { var relationRepo = context.UnitOfWork.GetRepository<IResourceRelationRepository>(); var referenceAtt = referenceProperty.GetCustomAttribute<ResourceReferenceAttribute>(); // Get the value stored in the reference property var propertyValue = referenceProperty.GetValue(resource); var referencedResources = ((IEnumerable<IResource>)propertyValue).Cast<Resource>().ToList(); // Check required attribute against empty collections if (referencedResources.Count == 0 && referenceAtt.IsRequired) throw new ValidationException($"Property {referenceProperty.Name} is flagged 'Required' and was empty!"); // First delete references that are not used by ANY property of the same configuration var currentReferences = CurrentReferences(resource, referenceAtt); var deleted = relationTemplates.Where(m => currentReferences.All(cr => cr != context.ResolveReference(m))).ToList(); foreach (var relation in deleted) { ClearOnTarget(context.ResolveReference(relation), resource, referenceAtt); relationRepo.Remove(relation.Entity); } // Now create new relations var created = referencedResources.Where(rr => relationTemplates.All(m => rr != context.ResolveReference(m))).ToList(); foreach (var createdReference in created) { SetOnTarget(createdReference, resource, referenceAtt); var relEntity = CreateRelationForProperty(context, relationRepo, referenceAtt); var referencedEntity = GetOrCreateEntity(context, createdReference); UpdateRelationEntity(entity, referencedEntity, relEntity, referenceAtt); } return created.Where(cr => cr.Id == 0); } /// <summary> /// Find all resources references by the instance with the same reference information /// </summary> private static ISet<IResource> CurrentReferences(Resource instance, ResourceReferenceAttribute referenceAtt) { // Get all references of this resource with the same relation information var currentReferences = (from property in ResourceReferenceTools.ReferenceProperties(instance.GetType(), false) let att = property.GetCustomAttribute<ResourceReferenceAttribute>() where att.RelationType == referenceAtt.RelationType && att.Name == referenceAtt.Name && att.Role == referenceAtt.Role select property.GetValue(instance)).SelectMany(ExtractAllFromProperty); return new HashSet<IResource>(currentReferences); } /// <summary> /// Extract all resources from the property value for single and many references /// </summary> private static IEnumerable<IResource> ExtractAllFromProperty(object propertyValue) { // Check if it is a single reference var asResource = propertyValue as IResource; if (asResource != null) return new[] { asResource }; // Otherwise it must be a collection var asEnumerable = propertyValue as IEnumerable; if (asEnumerable != null) return asEnumerable.Cast<IResource>(); return Enumerable.Empty<IResource>(); } /// <summary> /// Find the property on the target type that acts as the back-link in the relationship /// </summary> /// <returns></returns> private static PropertyInfo FindBackLink(Resource target, Resource value, ResourceReferenceAttribute referenceAtt) { var propOnTarget = (from prop in ResourceReferenceTools.ReferenceProperties(target.GetType(), false) where IsInstanceOfReference(prop, value) let backAtt = prop.GetCustomAttribute<ResourceReferenceAttribute>() where backAtt.Name == referenceAtt.Name // Compare name && backAtt.RelationType == referenceAtt.RelationType // Compare relation type && backAtt.Role != referenceAtt.Role // Validate inverse role select prop).FirstOrDefault(); return propOnTarget; } /// <summary> /// Check if a resource object is an instance of the property type /// </summary> private static bool IsInstanceOfReference(PropertyInfo property, Resource value) { var typeLimit = property.PropertyType; if (property.PropertyType.IsGenericType && property.PropertyType.GetGenericTypeDefinition() == typeof(IReferences<>)) typeLimit = property.PropertyType.GetGenericArguments()[0]; return typeLimit.IsInstanceOfType(value); } /// <summary> /// Update backlink if possible /// </summary> private static void SetOnTarget(Resource target, Resource value, ResourceReferenceAttribute referenceAtt) { var prop = FindBackLink(target, value, referenceAtt); if (prop == null) return; // No back-link -> nothing to do // Update back-link property if (prop.PropertyType.IsInstanceOfType(value)) { prop.SetValue(target, value); } else { var collection = prop.GetValue(target) as IReferenceCollection; if (collection != null && !collection.UnderlyingCollection.Contains(value)) collection.UnderlyingCollection.Add(value); } } /// <summary> /// Remove the reference to the resource on a target object /// </summary> private void ClearOnTarget(Resource target, Resource value, ResourceReferenceAttribute referenceAtt) { var prop = FindBackLink(target, value, referenceAtt); if (prop == null) return; // No back-link -> nothing to do // Update property ONLY if it currently points to our resource var propValue = prop.GetValue(target); if (propValue == value) { prop.SetValue(target, null); } else { (propValue as IReferenceCollection)?.UnderlyingCollection.Remove(value); } } /// <summary> /// Get or create an entity for a resource instance /// </summary> private static ResourceEntity GetOrCreateEntity(ReferenceSaverContext context, Resource instance) { // First check if the context contains an entity for the instance if (context.EntityCache.ContainsKey(instance)) return context.EntityCache[instance]; ResourceEntity entity; if (instance.Id > 0) { entity = context.UnitOfWork.GetEntity<ResourceEntity>(instance); } else { entity = ResourceEntityAccessor.SaveToEntity(context.UnitOfWork, instance); context.ResourceLookup[entity] = instance; } // Get or create an entity for the instance return context.EntityCache[instance] = entity; } /// <summary> /// Create a <see cref="ResourceRelation"/> entity for a property match /// </summary> private static ResourceRelation CreateRelationForProperty(ReferenceSaverContext context, IResourceRelationRepository relationRepo, ResourceReferenceAttribute att) { var relationType = att.RelationType; var relEntity = relationRepo.Create((int)relationType); context.CreatedRelations.Add(relEntity); return relEntity; } /// <summary> /// Set <see cref="ResourceRelation.SourceId"/> and <see cref="ResourceRelation.TargetId"/> depending on the <see cref="ResourceReferenceRole"/> /// of the reference property /// </summary> private static void UpdateRelationEntity(ResourceEntity resource, ResourceEntity referencedResource, ResourceRelation relEntity, ResourceReferenceAttribute att) { if (att.Role == ResourceReferenceRole.Source) { relEntity.Source = referencedResource; relEntity.Target = resource; relEntity.SourceName = att.Name; } else { relEntity.Source = resource; relEntity.Target = referencedResource; relEntity.TargetName = att.Name; } } /// <inheritdoc /> public void RemoveLinking(IResource deletedInstance, IResource reference) { // Try to find a property on the reference back-linking to the deleted instance var type = reference.GetType(); var backReference = (from property in ResourceReferenceTools.ReferenceProperties(type, false) // Instead of comparing the resource type we simply look for the object reference let value = property.GetValue(reference) where value == deletedInstance || ((value as IEnumerable<IResource>)?.Contains(deletedInstance) ?? false) select property).FirstOrDefault(); // If the referenced resource does not define a back reference we don't have to do anything if (backReference == null) return; // Remove the reference from the property if (typeof(IEnumerable<IResource>).IsAssignableFrom(backReference.PropertyType)) { var referenceCollection = (IReferenceCollection)backReference.GetValue(reference); referenceCollection.UnderlyingCollection.Remove(deletedInstance); } else { backReference.SetValue(reference, null); } } /// <summary> /// Find the relation that matches the property by type and role /// </summary> private static IEnumerable<ResourceRelationAccessor> MatchingRelations(IEnumerable<ResourceRelationAccessor> relations, PropertyInfo property) { var attribute = property.GetCustomAttribute<ResourceReferenceAttribute>(); var matches = from relation in relations where relation.Role == attribute.Role where relation.RelationType == attribute.RelationType where relation.Name == attribute.Name select relation; return matches; } /// <summary> /// Resolve instance matches for relations /// </summary> public static IEnumerable<Resource> InstanceProjection(IEnumerable<ResourceRelationAccessor> relations, PropertyInfo property, Func<ResourceRelationAccessor, Resource> instanceResolver) { return relations.Select(instanceResolver).Where(instance => IsInstanceOfReference(property, instance)); } /// <summary> /// Filter relations by type compatibility /// </summary> /// <param name="relations"></param> /// <param name="property"></param> /// <param name="instanceResolver"></param> /// <returns></returns> public static IEnumerable<ResourceRelationAccessor> TypeFilter(IEnumerable<ResourceRelationAccessor> relations, PropertyInfo property, Func<ResourceRelationAccessor, Resource> instanceResolver) { return from relation in relations let target = instanceResolver(relation) where IsInstanceOfReference(property, target) select relation; } /// <summary> /// Reusable method for resolver delegate /// </summary> /// <param name="relation"></param> /// <returns></returns> private Resource ResolveRefernceWithGraph(ResourceRelationAccessor relation) => Graph.Get(relation.ReferenceId); /// <summary> /// Context for the recursive save references structure /// </summary> private class ReferenceSaverContext { private readonly IResourceGraph _graph; public ReferenceSaverContext(IUnitOfWork unitOfWork, IResourceGraph graph, Resource initialInstance, ResourceEntity entity) : this(unitOfWork, graph) { EntityCache[initialInstance] = entity; if (initialInstance.Id == 0) ResourceLookup[entity] = initialInstance; } public ReferenceSaverContext(IUnitOfWork uow, IResourceGraph graph) { _graph = graph; UnitOfWork = uow; EntityCache = new Dictionary<Resource, ResourceEntity>(); ResourceLookup = new Dictionary<ResourceEntity, Resource>(); CreatedRelations = new List<ResourceRelation>(); } /// <summary> /// Open database context of this operation /// </summary> public IUnitOfWork UnitOfWork { get; } /// <summary> /// Cache of instances to entities /// </summary> public IDictionary<Resource, ResourceEntity> EntityCache { get; } /// <summary> /// Reverse <see cref="EntityCache"/> to fetch instances by resource /// </summary> public IDictionary<ResourceEntity, Resource> ResourceLookup { get; } /// <summary> /// Accesor wrappers for relations that were created while saving references /// </summary> public IList<ResourceRelation> CreatedRelations { get; } /// <summary> /// Resolve a relation reference /// </summary> public Resource ResolveReference(ResourceRelationAccessor relation) { return relation.ReferenceId > 0 ? _graph.Get(relation.ReferenceId) : ResourceLookup[relation.ReferenceEntity]; } } } }
47.751381
276
0.609588
[ "Apache-2.0" ]
milmilkat/MORYX-AbstractionLayer
src/Moryx.Resources.Management/Resources/ResourceLinker.cs
25,929
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Resources; using System.Text; using Microsoft.Build.Framework; using Microsoft.Build.Shared; using Microsoft.Build.Shared.FileSystem; #if FEATURE_FILE_TRACKER namespace Microsoft.Build.Utilities { /// <summary> /// Class used to store and interrogate inputs and outputs recorded by tracking operations. /// </summary> public class FlatTrackingData { #region Constants // The maximum number of outputs that should be logged, if more than this, then no outputs are logged private const int MaxLogCount = 100; #endregion #region Member Data // The .write. trackg log files // The tlog marker is used if the tracking data is empty // even if the tracked execution was successful private string _tlogMarker = string.Empty; // The TaskLoggingHelper that we log progress to private TaskLoggingHelper _log; // The oldest file that we have seen private DateTime _oldestFileTimeUtc = DateTime.MaxValue; // The newest file what we have seen private DateTime _newestFileTimeUtc = DateTime.MinValue; // Should rooting markers be treated as tracking entries private bool _treatRootMarkersAsEntries; // If we are not skipping missing files, what DateTime should they be given? private DateTime _missingFileTimeUtc = DateTime.MinValue; // The newest Tlog that we have seen private DateTime _newestTLogTimeUtc = DateTime.MinValue; // Cache of last write times private readonly IDictionary<string, DateTime> _lastWriteTimeUtcCache = new Dictionary<string, DateTime>(StringComparer.OrdinalIgnoreCase); // The set of paths that contain files that are to be ignored during up to date check - these directories or their subdirectories private readonly List<string> _excludedInputPaths = new List<string>(); #endregion #region Properties // The output dependency table internal Dictionary<string, DateTime> DependencyTable { get; private set; } = new Dictionary<string, DateTime>(StringComparer.OrdinalIgnoreCase); /// <summary> /// Missing files have been detected in the TLog /// </summary> [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly", Justification = "Has shipped as public API, so we can't easily change it now. ")] public List<string> MissingFiles { get; set; } = new List<string>(); /// <summary> /// The path for the oldest file we have seen /// </summary> public string OldestFileName { get; set; } = string.Empty; /// <summary> /// The time for the oldest file we have seen /// </summary> public DateTime OldestFileTime { get => _oldestFileTimeUtc.ToLocalTime(); set => _oldestFileTimeUtc = value.ToUniversalTime(); } /// <summary> /// The time for the oldest file we have seen /// </summary> public DateTime OldestFileTimeUtc { get => _oldestFileTimeUtc; set => _oldestFileTimeUtc = value.ToUniversalTime(); } /// <summary> /// The path for the newest file we have seen /// </summary> public string NewestFileName { get; set; } = string.Empty; /// <summary> /// The time for the newest file we have seen /// </summary> public DateTime NewestFileTime { get => _newestFileTimeUtc.ToLocalTime(); set => _newestFileTimeUtc = value.ToUniversalTime(); } /// <summary> /// The time for the newest file we have seen /// </summary> public DateTime NewestFileTimeUtc { get => _newestFileTimeUtc; set => _newestFileTimeUtc = value.ToUniversalTime(); } /// <summary> /// Should root markers in the TLog be treated as file accesses, or only as markers? /// </summary> public bool TreatRootMarkersAsEntries { get => _treatRootMarkersAsEntries; set => _treatRootMarkersAsEntries = value; } /// <summary> /// Should files in the TLog but no longer exist be skipped or recorded? /// </summary> public bool SkipMissingFiles { get; set; } /// <summary> /// The TLog files that back this structure /// </summary> [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "Has shipped as public API, so we can't easily change it now. ")] public ITaskItem[] TlogFiles { get; set; } /// <summary> /// The time of the newest Tlog /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "TLog", Justification = "Has now shipped as public API; plus it's unclear whether 'Tlog' or 'TLog' is the preferred casing")] public DateTime NewestTLogTime { get => _newestTLogTimeUtc.ToLocalTime(); set => _newestTLogTimeUtc = value.ToUniversalTime(); } /// <summary> /// The time of the newest Tlog /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "TLog", Justification = "Has now shipped as public API; plus it's unclear whether 'Tlog' or 'TLog' is the preferred casing")] public DateTime NewestTLogTimeUtc { get => _newestTLogTimeUtc; set => _newestTLogTimeUtc = value.ToUniversalTime(); } /// <summary> /// The path of the newest TLog file /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "TLog", Justification = "Has now shipped as public API; plus it's unclear whether 'Tlog' or 'TLog' is the preferred casing")] public string NewestTLogFileName { get; set; } = string.Empty; /// <summary> /// Are all the TLogs that were passed to us actually available on disk? /// </summary> public bool TlogsAvailable { get; set; } #endregion #region Constructors /// <summary> /// Constructor /// </summary> /// <param name="tlogFiles">The .write. tlog files to interpret</param> /// <param name="missingFileTimeUtc">The DateTime that should be recorded for missing file.</param> public FlatTrackingData(ITaskItem[] tlogFiles, DateTime missingFileTimeUtc) => InternalConstruct(null, tlogFiles, null, false, missingFileTimeUtc, null); /// <summary> /// Constructor /// </summary> /// <param name="tlogFiles">The .write. tlog files to interpret</param> /// <param name="tlogFilesToIgnore">The .tlog files to ignore</param> /// <param name="missingFileTimeUtc">The DateTime that should be recorded for missing file.</param> public FlatTrackingData(ITaskItem[] tlogFiles, ITaskItem[] tlogFilesToIgnore, DateTime missingFileTimeUtc) => InternalConstruct(null, tlogFiles, tlogFilesToIgnore, false, missingFileTimeUtc, null); /// <summary> /// Constructor /// </summary> /// <param name="tlogFiles">The .tlog files to interpret</param> /// <param name="tlogFilesToIgnore">The .tlog files to ignore</param> /// <param name="missingFileTimeUtc">The DateTime that should be recorded for missing file.</param> /// <param name="excludedInputPaths">The set of paths that contain files that are to be ignored during up to date check, including any subdirectories.</param> /// <param name="sharedLastWriteTimeUtcCache">Cache to be used for all timestamp/exists comparisons, which can be shared between multiple FlatTrackingData instances.</param> public FlatTrackingData(ITaskItem[] tlogFiles, ITaskItem[] tlogFilesToIgnore, DateTime missingFileTimeUtc, string[] excludedInputPaths, IDictionary<string, DateTime> sharedLastWriteTimeUtcCache) { if (sharedLastWriteTimeUtcCache != null) { _lastWriteTimeUtcCache = sharedLastWriteTimeUtcCache; } InternalConstruct(null, tlogFiles, tlogFilesToIgnore, false, missingFileTimeUtc, excludedInputPaths); } /// <summary> /// Constructor /// </summary> /// <param name="tlogFiles">The .tlog files to interpret</param> /// <param name="tlogFilesToIgnore">The .tlog files to ignore</param> /// <param name="missingFileTimeUtc">The DateTime that should be recorded for missing file.</param> /// <param name="excludedInputPaths">The set of paths that contain files that are to be ignored during up to date check, including any subdirectories.</param> /// <param name="sharedLastWriteTimeUtcCache">Cache to be used for all timestamp/exists comparisons, which can be shared between multiple FlatTrackingData instances.</param> /// <param name="treatRootMarkersAsEntries">Add root markers as inputs.</param> public FlatTrackingData(ITaskItem[] tlogFiles, ITaskItem[] tlogFilesToIgnore, DateTime missingFileTimeUtc, string[] excludedInputPaths, IDictionary<string, DateTime> sharedLastWriteTimeUtcCache, bool treatRootMarkersAsEntries) { _treatRootMarkersAsEntries = treatRootMarkersAsEntries; if (sharedLastWriteTimeUtcCache != null) { _lastWriteTimeUtcCache = sharedLastWriteTimeUtcCache; } InternalConstruct(null, tlogFiles, tlogFilesToIgnore, false, missingFileTimeUtc, excludedInputPaths); } /// <summary> /// Constructor /// </summary> /// <param name="ownerTask">The task that is using file tracker</param> /// <param name="tlogFiles">The tlog files to interpret</param> /// <param name="missingFileTimeUtc">The DateTime that should be recorded for missing file.</param> public FlatTrackingData(ITask ownerTask, ITaskItem[] tlogFiles, DateTime missingFileTimeUtc) => InternalConstruct(ownerTask, tlogFiles, null, false, missingFileTimeUtc, null); /// <summary> /// Constructor /// </summary> /// <param name="tlogFiles">The .write. tlog files to interpret</param> /// <param name="skipMissingFiles">Ignore files that do not exist on disk</param> public FlatTrackingData(ITaskItem[] tlogFiles, bool skipMissingFiles) => InternalConstruct(null, tlogFiles, null, skipMissingFiles, DateTime.MinValue, null); /// <summary> /// Constructor /// </summary> /// <param name="ownerTask">The task that is using file tracker</param> /// <param name="tlogFiles">The tlog files to interpret</param> /// <param name="skipMissingFiles">Ignore files that do not exist on disk</param> public FlatTrackingData(ITask ownerTask, ITaskItem[] tlogFiles, bool skipMissingFiles) => InternalConstruct(ownerTask, tlogFiles, null, skipMissingFiles, DateTime.MinValue, null); /// <summary> /// Internal constructor /// </summary> /// <param name="ownerTask">The task that is using file tracker</param> /// <param name="tlogFilesLocal">The local .tlog files.</param> /// <param name="tlogFilesToIgnore">The .tlog files to ignore</param> /// <param name="skipMissingFiles">Ignore files that do not exist on disk</param> /// <param name="missingFileTimeUtc">The DateTime that should be recorded for missing file.</param> /// <param name="excludedInputPaths">The set of paths that contain files that are to be ignored during up to date check</param> private void InternalConstruct(ITask ownerTask, ITaskItem[] tlogFilesLocal, ITaskItem[] tlogFilesToIgnore, bool skipMissingFiles, DateTime missingFileTimeUtc, string[] excludedInputPaths) { if (ownerTask != null) { _log = new TaskLoggingHelper(ownerTask) { TaskResources = AssemblyResources.PrimaryResources, HelpKeywordPrefix = "MSBuild." }; } ITaskItem[] expandedTlogFiles = TrackedDependencies.ExpandWildcards(tlogFilesLocal); if (tlogFilesToIgnore != null) { ITaskItem[] expandedTlogFilesToIgnore = TrackedDependencies.ExpandWildcards(tlogFilesToIgnore); if (expandedTlogFilesToIgnore.Length > 0) { var ignore = new HashSet<string>(); var remainingTlogFiles = new List<ITaskItem>(); foreach (ITaskItem tlogFileToIgnore in expandedTlogFilesToIgnore) { ignore.Add(tlogFileToIgnore.ItemSpec); } foreach (ITaskItem tlogFile in expandedTlogFiles) { if (!ignore.Contains(tlogFile.ItemSpec)) { remainingTlogFiles.Add(tlogFile); } } TlogFiles = remainingTlogFiles.ToArray(); } else { TlogFiles = expandedTlogFiles; } } else { TlogFiles = expandedTlogFiles; } // We have no TLog files on disk, create a TLog marker from the // TLogFiles ItemSpec so we can fabricate one if we need to // This becomes our "first" tlog, since on the very first run, no tlogs // will exist, and if a compaction has been run (as part of the initial up-to-date check) then this // marker tlog will be created as empty. if (TlogFiles == null || TlogFiles.Length == 0) { _tlogMarker = tlogFilesLocal[0].ItemSpec .Replace("*", "1") .Replace("?", "2"); } if (excludedInputPaths != null) { // Assign our exclude paths to our lookup - and make sure that all recorded paths end in a slash so that // our "starts with" comparison doesn't pick up incomplete matches, such as C:\Foo matching C:\FooFile.txt foreach (string excludePath in excludedInputPaths) { string fullexcludePath = FileUtilities.EnsureTrailingSlash(FileUtilities.NormalizePath(excludePath)).ToUpperInvariant(); _excludedInputPaths.Add(fullexcludePath); } } TlogsAvailable = TrackedDependencies.ItemsExist(TlogFiles); SkipMissingFiles = skipMissingFiles; _missingFileTimeUtc = missingFileTimeUtc.ToUniversalTime(); if (TlogFiles != null) { // Read the TLogs into our internal structures ConstructFileTable(); } } #endregion #region Methods /// <summary> /// Construct our dependency table for our source files /// </summary> private void ConstructFileTable() { string tLogRootingMarker; try { // construct a rooting marker from the tlog files tLogRootingMarker = DependencyTableCache.FormatNormalizedTlogRootingMarker(TlogFiles); } catch (ArgumentException e) { FileTracker.LogWarningWithCodeFromResources(_log, "Tracking_RebuildingDueToInvalidTLog", e.Message); return; } if (!TlogsAvailable) { lock (DependencyTableCache.DependencyTable) { // The tracking logs are not available, they may have been deleted at some point. // Be safe and remove any references from the cache. DependencyTableCache.DependencyTable.Remove(tLogRootingMarker); } return; } DependencyTableCacheEntry cachedEntry; lock (DependencyTableCache.DependencyTable) { // Look in the dependency table cache to see if its available and up to date cachedEntry = DependencyTableCache.GetCachedEntry(tLogRootingMarker); } // We have an up to date cached entry if (cachedEntry != null) { DependencyTable = (Dictionary<string, DateTime>)cachedEntry.DependencyTable; // We may have stored the dependency table in the cache, but all the other information // (newest file time, number of missing files, etc.) has been reset to default. Refresh // the data. UpdateFileEntryDetails(); // Log information about what we're using FileTracker.LogMessageFromResources(_log, MessageImportance.Low, "Tracking_TrackingCached"); foreach (ITaskItem tlogItem in cachedEntry.TlogFiles) { FileTracker.LogMessage(_log, MessageImportance.Low, "\t{0}", tlogItem.ItemSpec); } return; } FileTracker.LogMessageFromResources(_log, MessageImportance.Low, "Tracking_TrackingLogs"); // Now we need to construct the rest of the table from the TLOG files // If there are any errors in the tlogs, we want to warn, stop parsing tlogs, and empty // out the dependency table, essentially forcing a rebuild. bool encounteredInvalidTLogContents = false; string invalidTLogName = null; foreach (ITaskItem tlogFileName in TlogFiles) { try { FileTracker.LogMessage(_log, MessageImportance.Low, "\t{0}", tlogFileName.ItemSpec); DateTime tlogLastWriteTimeUtc = NativeMethodsShared.GetLastWriteFileUtcTime(tlogFileName.ItemSpec); if (tlogLastWriteTimeUtc > _newestTLogTimeUtc) { _newestTLogTimeUtc = tlogLastWriteTimeUtc; NewestTLogFileName = tlogFileName.ItemSpec; } using (StreamReader tlog = File.OpenText(tlogFileName.ItemSpec)) { string tlogEntry = tlog.ReadLine(); while (tlogEntry != null) { if (tlogEntry.Length == 0) // empty lines are a sign that something has gone wrong { encounteredInvalidTLogContents = true; invalidTLogName = tlogFileName.ItemSpec; break; } // Preprocessing for the line entry else if (tlogEntry[0] == '#') // a comment marker should be skipped { tlogEntry = tlog.ReadLine(); continue; } else if (tlogEntry[0] == '^' && TreatRootMarkersAsEntries && tlogEntry.IndexOf('|') < 0) // This is a rooting non composite record, and we should keep it { tlogEntry = tlogEntry.Substring(1); if (tlogEntry.Length == 0) { encounteredInvalidTLogContents = true; invalidTLogName = tlogFileName.ItemSpec; break; } } else if (tlogEntry[0] == '^') // root marker is not being treated as an entry, skip it { tlogEntry = tlog.ReadLine(); continue; } // If we haven't seen this file before, then record it if (!DependencyTable.ContainsKey(tlogEntry)) { // It may be that this is one of the locations that we should ignore if (!FileTracker.FileIsExcludedFromDependencies(tlogEntry)) { RecordEntryDetails(tlogEntry, true); } } tlogEntry = tlog.ReadLine(); } } } catch (Exception e) when (ExceptionHandling.IsIoRelatedException(e)) { FileTracker.LogWarningWithCodeFromResources(_log, "Tracking_RebuildingDueToInvalidTLog", e.Message); break; } if (encounteredInvalidTLogContents) { FileTracker.LogWarningWithCodeFromResources(_log, "Tracking_RebuildingDueToInvalidTLogContents", invalidTLogName); break; } } lock (DependencyTableCache.DependencyTable) { // There were problems with the tracking logs -- we've already warned or errored; now we want to make // sure that we essentially force a rebuild of this particular root. if (encounteredInvalidTLogContents) { DependencyTableCache.DependencyTable.Remove(tLogRootingMarker); DependencyTable = new Dictionary<string, DateTime>(StringComparer.OrdinalIgnoreCase); } else { // Record the newly built dependency table in the cache DependencyTableCache.DependencyTable[tLogRootingMarker] = new DependencyTableCacheEntry(TlogFiles, DependencyTable); } } } /// <summary> /// Update the current state of entry details for the dependency table /// </summary> public void UpdateFileEntryDetails() { OldestFileName = string.Empty; _oldestFileTimeUtc = DateTime.MaxValue; NewestFileName = string.Empty; _newestFileTimeUtc = DateTime.MinValue; NewestTLogFileName = string.Empty; _newestTLogTimeUtc = DateTime.MinValue; MissingFiles.Clear(); // First update the details of our Tlogs foreach (ITaskItem tlogFileName in TlogFiles) { DateTime tlogLastWriteTimeUtc = NativeMethodsShared.GetLastWriteFileUtcTime(tlogFileName.ItemSpec); if (tlogLastWriteTimeUtc > _newestTLogTimeUtc) { _newestTLogTimeUtc = tlogLastWriteTimeUtc; NewestTLogFileName = tlogFileName.ItemSpec; } } // Now for each entry in the table foreach (string entry in DependencyTable.Keys) { RecordEntryDetails(entry, false); } } /// <summary> /// Test to see if the specified file is excluded from tracked dependency checking /// </summary> /// <param name="fileName"> /// Full path of the file to test /// </param> /// <remarks> /// The file is excluded if it is within any of the specified excluded input paths or any subdirectory of the paths. /// It also assumes the file name is already converted to Uppercase Invariant. /// </remarks> public bool FileIsExcludedFromDependencyCheck(string fileName) { foreach (string path in _excludedInputPaths) { if (fileName.StartsWith(path, StringComparison.OrdinalIgnoreCase)) { return true; } } return false; } /// <summary> /// Record the time and missing state of the entry in the tlog /// </summary> private void RecordEntryDetails(string tlogEntry, bool populateTable) { if (FileIsExcludedFromDependencyCheck(tlogEntry)) { return; } DateTime fileModifiedTimeUtc = GetLastWriteTimeUtc(tlogEntry); if (SkipMissingFiles && fileModifiedTimeUtc == DateTime.MinValue) // the file is missing { return; } else if (fileModifiedTimeUtc == DateTime.MinValue) { // Record the file in our table even though it was missing // use the missingFileTimeUtc as indicated. if (populateTable) { DependencyTable[tlogEntry] = _missingFileTimeUtc.ToUniversalTime(); } MissingFiles.Add(tlogEntry); } else { if (populateTable) { DependencyTable[tlogEntry] = fileModifiedTimeUtc; } } // Record this file if it is newer than our current newest if (fileModifiedTimeUtc > _newestFileTimeUtc) { _newestFileTimeUtc = fileModifiedTimeUtc; NewestFileName = tlogEntry; } // Record this file if it is older than our current oldest if (fileModifiedTimeUtc < _oldestFileTimeUtc) { _oldestFileTimeUtc = fileModifiedTimeUtc; OldestFileName = tlogEntry; } } /// <summary> /// This method will re-write the tlogs from the output table /// </summary> public void SaveTlog() => SaveTlog(null); /// <summary> /// This method will re-write the tlogs from the current table /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "TLog", Justification = "Has now shipped as public API; plus it's unclear whether 'Tlog' or 'TLog' is the preferred casing")] public void SaveTlog(DependencyFilter includeInTLog) { if (TlogFiles?.Length > 0) { string tLogRootingMarker = DependencyTableCache.FormatNormalizedTlogRootingMarker(TlogFiles); lock (DependencyTableCache.DependencyTable) { // The tracking logs in the cache will be invalidated by this write // remove the cached entries to be sure DependencyTableCache.DependencyTable.Remove(tLogRootingMarker); } string firstTlog = TlogFiles[0].ItemSpec; // empty all tlogs foreach (ITaskItem tlogFile in TlogFiles) { File.WriteAllText(tlogFile.ItemSpec, "", Encoding.Unicode); } // Write out the dependency information as a new tlog using (StreamWriter newTlog = FileUtilities.OpenWrite(firstTlog, false, Encoding.Unicode)) { foreach (string fileEntry in DependencyTable.Keys) { // Give the task a chance to filter dependencies out of the written TLog if (includeInTLog == null || includeInTLog(fileEntry)) { // Write out the entry newTlog.WriteLine(fileEntry); } } } } else if (_tlogMarker != string.Empty) { string markerDirectory = Path.GetDirectoryName(_tlogMarker); if (!FileSystems.Default.DirectoryExists(markerDirectory)) { Directory.CreateDirectory(markerDirectory); } // There were no TLogs to save, so use the TLog marker // to create a marker file that can be used for up-to-date check. File.WriteAllText(_tlogMarker, ""); } } /// <summary> /// Returns cached value for last write time of file. Update the cache if it is the first /// time someone asking for that file /// </summary> public DateTime GetLastWriteTimeUtc(string file) { if (!_lastWriteTimeUtcCache.TryGetValue(file, out DateTime fileModifiedTimeUtc)) { fileModifiedTimeUtc = NativeMethodsShared.GetLastWriteFileUtcTime(file); _lastWriteTimeUtcCache[file] = fileModifiedTimeUtc; } return fileModifiedTimeUtc; } #endregion #region Static Methods /// <summary> /// Checks to see if the tracking data indicates that everything is up to date according to UpToDateCheckType. /// Note: If things are not up to date, then the TLogs are compacted to remove all entries in preparation to /// re-track execution of work. /// </summary> /// <param name="hostTask">The <see cref="Task"/> host</param> /// <param name="upToDateCheckType">UpToDateCheckType</param> /// <param name="readTLogNames">The array of read tlogs</param> /// <param name="writeTLogNames">The array of write tlogs</param> /// <returns></returns> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "TLog", Justification = "Has now shipped as public API; plus it's unclear whether 'Tlog' or 'TLog' is the preferred casing")] public static bool IsUpToDate(Task hostTask, UpToDateCheckType upToDateCheckType, ITaskItem[] readTLogNames, ITaskItem[] writeTLogNames) { // Read the input graph (missing inputs are infinitely new - i.e. outputs are out of date) FlatTrackingData inputs = new FlatTrackingData(hostTask, readTLogNames, DateTime.MaxValue); // Read the output graph (missing outputs are infinitely old - i.e. outputs are out of date) FlatTrackingData outputs = new FlatTrackingData(hostTask, writeTLogNames, DateTime.MinValue); // Find out if we are up to date bool isUpToDate = IsUpToDate(hostTask.Log, upToDateCheckType, inputs, outputs); // We're going to execute, so clear out the tlogs so // the new execution will correctly populate the tlogs a-new if (!isUpToDate) { // Remove all from inputs tlog inputs.DependencyTable.Clear(); inputs.SaveTlog(); // Remove all from outputs tlog outputs.DependencyTable.Clear(); outputs.SaveTlog(); } return isUpToDate; } /// <summary> /// Simple check of up to date state according to the tracking data and the UpToDateCheckType. /// Note: No tracking log compaction will take place when using this overload /// </summary> /// <param name="Log">TaskLoggingHelper from the host task</param> /// <param name="upToDateCheckType">UpToDateCheckType to use</param> /// <param name="inputs">FlatTrackingData structure containing the inputs</param> /// <param name="outputs">FlatTrackingData structure containing the outputs</param> /// <returns></returns> [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Log", Justification = "Has shipped as public API; plus it is a closer match to other locations in our codebase where 'Log' is a property and cased properly")] public static bool IsUpToDate(TaskLoggingHelper Log, UpToDateCheckType upToDateCheckType, FlatTrackingData inputs, FlatTrackingData outputs) { bool isUpToDate = false; // Keep a record of the task resources that was in use before ResourceManager taskResources = Log.TaskResources; Log.TaskResources = AssemblyResources.PrimaryResources; inputs.UpdateFileEntryDetails(); outputs.UpdateFileEntryDetails(); if (!inputs.TlogsAvailable || !outputs.TlogsAvailable || inputs.DependencyTable.Count == 0) { // 1) The TLogs are somehow missing, which means we need to build // 2) Because we are flat tracking, there are no roots which means that all the input file information // comes from the input Tlogs, if they are empty then we must build. Log.LogMessageFromResources(MessageImportance.Low, "Tracking_LogFilesNotAvailable"); } else if (inputs.MissingFiles.Count > 0 || outputs.MissingFiles.Count > 0) { // Files are missing from either inputs or outputs, that means we need to build // Files are missing from inputs, that means we need to build if (inputs.MissingFiles.Count > 0) { Log.LogMessageFromResources(MessageImportance.Low, "Tracking_MissingInputs"); } // Too much logging leads to poor performance if (inputs.MissingFiles.Count > MaxLogCount) { FileTracker.LogMessageFromResources(Log, MessageImportance.Low, "Tracking_InputsNotShown", inputs.MissingFiles.Count); } else { // We have our set of inputs, log the details foreach (string input in inputs.MissingFiles) { FileTracker.LogMessage(Log, MessageImportance.Low, "\t" + input); } } // Files are missing from outputs, that means we need to build if (outputs.MissingFiles.Count > 0) { Log.LogMessageFromResources(MessageImportance.Low, "Tracking_MissingOutputs"); } // Too much logging leads to poor performance if (outputs.MissingFiles.Count > MaxLogCount) { FileTracker.LogMessageFromResources(Log, MessageImportance.Low, "Tracking_OutputsNotShown", outputs.MissingFiles.Count); } else { // We have our set of inputs, log the details foreach (string output in outputs.MissingFiles) { FileTracker.LogMessage(Log, MessageImportance.Low, "\t" + output); } } } else if (upToDateCheckType == UpToDateCheckType.InputOrOutputNewerThanTracking && inputs.NewestFileTimeUtc > inputs.NewestTLogTimeUtc) { // One of the inputs is newer than the input tlog Log.LogMessageFromResources(MessageImportance.Low, "Tracking_DependencyWasModifiedAt", inputs.NewestFileName, inputs.NewestFileTimeUtc, inputs.NewestTLogFileName, inputs.NewestTLogTimeUtc); } else if (upToDateCheckType == UpToDateCheckType.InputOrOutputNewerThanTracking && outputs.NewestFileTimeUtc > outputs.NewestTLogTimeUtc) { // one of the outputs is newer than the output tlog Log.LogMessageFromResources(MessageImportance.Low, "Tracking_DependencyWasModifiedAt", outputs.NewestFileName, outputs.NewestFileTimeUtc, outputs.NewestTLogFileName, outputs.NewestTLogTimeUtc); } else if (upToDateCheckType == UpToDateCheckType.InputNewerThanOutput && inputs.NewestFileTimeUtc > outputs.NewestFileTimeUtc) { // One of the inputs is newer than the outputs Log.LogMessageFromResources(MessageImportance.Low, "Tracking_DependencyWasModifiedAt", inputs.NewestFileName, inputs.NewestFileTimeUtc, outputs.NewestFileName, outputs.NewestFileTimeUtc); } else if (upToDateCheckType == UpToDateCheckType.InputNewerThanTracking && inputs.NewestFileTimeUtc > inputs.NewestTLogTimeUtc) { // One of the inputs is newer than the one of the TLogs Log.LogMessageFromResources(MessageImportance.Low, "Tracking_DependencyWasModifiedAt", inputs.NewestFileName, inputs.NewestFileTimeUtc, inputs.NewestTLogFileName, inputs.NewestTLogTimeUtc); } else if (upToDateCheckType == UpToDateCheckType.InputNewerThanTracking && inputs.NewestFileTimeUtc > outputs.NewestTLogTimeUtc) { // One of the inputs is newer than the one of the TLogs Log.LogMessageFromResources(MessageImportance.Low, "Tracking_DependencyWasModifiedAt", inputs.NewestFileName, inputs.NewestFileTimeUtc, outputs.NewestTLogFileName, outputs.NewestTLogTimeUtc); } else { // Nothing appears to have changed.. isUpToDate = true; Log.LogMessageFromResources(MessageImportance.Normal, "Tracking_UpToDate"); } // Set the task resources back now that we're done with it Log.TaskResources = taskResources; return isUpToDate; } /// <summary> /// Once tracked operations have been completed then we need to compact / finalize the Tlogs based /// on the success of the tracked execution. If it fails, then we clean out the TLogs. If it succeeds /// then we clean temporary files from the TLogs and re-write them. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "TLogs", Justification = "Has now shipped as public API; plus it's unclear whether 'Tlog' or 'TLog' is the preferred casing")] [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "TLog", Justification = "Has now shipped as public API; plus it's unclear whether 'Tlog' or 'TLog' is the preferred casing")] public static void FinalizeTLogs(bool trackedOperationsSucceeded, ITaskItem[] readTLogNames, ITaskItem[] writeTLogNames, ITaskItem[] trackedFilesToRemoveFromTLogs) { // Read the input table, skipping missing files FlatTrackingData inputs = new FlatTrackingData(readTLogNames, true); // Read the output table, skipping missing files FlatTrackingData outputs = new FlatTrackingData(writeTLogNames, true); // If we failed we need to clean the Tlogs if (!trackedOperationsSucceeded) { // If the tool errors in some way, we assume that any and all inputs and outputs it wrote during // execution are wrong. So we compact the read and write tlogs to remove the entries for the // set of sources being compiled - the next incremental build will find no entries // and correctly cause the sources to be compiled // Remove all from inputs tlog inputs.DependencyTable.Clear(); inputs.SaveTlog(); // Remove all from outputs tlog outputs.DependencyTable.Clear(); outputs.SaveTlog(); } else { // If all went well with the tool execution, then compact the tlogs // to remove any files that are no longer on disk. // This removes any temporary files from the dependency graph // In addition to temporary file removal, an optional set of files to remove may be been supplied if (trackedFilesToRemoveFromTLogs?.Length > 0) { IDictionary<string, ITaskItem> trackedFilesToRemove = new Dictionary<string, ITaskItem>(StringComparer.OrdinalIgnoreCase); foreach (ITaskItem removeFile in trackedFilesToRemoveFromTLogs) { trackedFilesToRemove.Add(FileUtilities.NormalizePath(removeFile.ItemSpec), removeFile); } // UNDONE: If necessary we could have two independent sets of "ignore" files, one for inputs and one for outputs // Use an anonymous methods to encapsulate the contains check for the input and output tlogs // We need to answer the question "should fullTrackedPath be included in the TLog?" outputs.SaveTlog(fullTrackedPath => !trackedFilesToRemove.ContainsKey(fullTrackedPath)); inputs.SaveTlog(fullTrackedPath => !trackedFilesToRemove.ContainsKey(fullTrackedPath)); } else { // Compact the write tlog outputs.SaveTlog(); // Compact the read tlog inputs.SaveTlog(); } } } #endregion } /// <summary> /// The possible types of up to date check that we can support /// </summary> public enum UpToDateCheckType { /// <summary> /// The input is newer than the output. /// </summary> InputNewerThanOutput, /// <summary> /// The input or output are newer than the tracking file. /// </summary> InputOrOutputNewerThanTracking, /// <summary> /// The input is newer than the tracking file. /// </summary> InputNewerThanTracking } } #endif
46.901099
260
0.586317
[ "MIT" ]
478254406/msbuild
src/Utilities/TrackedDependencies/FlatTrackingData.cs
42,682
C#
namespace Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801 { using static Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Extensions; /// <summary>Stamp capacity information.</summary> public partial class StampCapacity : Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IStampCapacity, Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IStampCapacityInternal { /// <summary>Backing field for <see cref="AvailableCapacity" /> property.</summary> private long? _availableCapacity; /// <summary>Available capacity (# of machines, bytes of storage etc...).</summary> [Microsoft.Azure.PowerShell.Cmdlets.Functions.Origin(Microsoft.Azure.PowerShell.Cmdlets.Functions.PropertyOrigin.Owned)] public long? AvailableCapacity { get => this._availableCapacity; set => this._availableCapacity = value; } /// <summary>Backing field for <see cref="ComputeMode" /> property.</summary> private Microsoft.Azure.PowerShell.Cmdlets.Functions.Support.ComputeModeOptions? _computeMode; /// <summary>Shared/dedicated workers.</summary> [Microsoft.Azure.PowerShell.Cmdlets.Functions.Origin(Microsoft.Azure.PowerShell.Cmdlets.Functions.PropertyOrigin.Owned)] public Microsoft.Azure.PowerShell.Cmdlets.Functions.Support.ComputeModeOptions? ComputeMode { get => this._computeMode; set => this._computeMode = value; } /// <summary>Backing field for <see cref="ExcludeFromCapacityAllocation" /> property.</summary> private bool? _excludeFromCapacityAllocation; /// <summary> /// If <code>true</code>, it includes basic apps. /// Basic apps are not used for capacity allocation. /// </summary> [Microsoft.Azure.PowerShell.Cmdlets.Functions.Origin(Microsoft.Azure.PowerShell.Cmdlets.Functions.PropertyOrigin.Owned)] public bool? ExcludeFromCapacityAllocation { get => this._excludeFromCapacityAllocation; set => this._excludeFromCapacityAllocation = value; } /// <summary>Backing field for <see cref="IsApplicableForAllComputeMode" /> property.</summary> private bool? _isApplicableForAllComputeMode; /// <summary> /// <code>true</code> if capacity is applicable for all apps; otherwise, <code>false</code>. /// </summary> [Microsoft.Azure.PowerShell.Cmdlets.Functions.Origin(Microsoft.Azure.PowerShell.Cmdlets.Functions.PropertyOrigin.Owned)] public bool? IsApplicableForAllComputeMode { get => this._isApplicableForAllComputeMode; set => this._isApplicableForAllComputeMode = value; } /// <summary>Backing field for <see cref="IsLinux" /> property.</summary> private bool? _isLinux; /// <summary>Is this a linux stamp capacity</summary> [Microsoft.Azure.PowerShell.Cmdlets.Functions.Origin(Microsoft.Azure.PowerShell.Cmdlets.Functions.PropertyOrigin.Owned)] public bool? IsLinux { get => this._isLinux; set => this._isLinux = value; } /// <summary>Backing field for <see cref="Name" /> property.</summary> private string _name; /// <summary>Name of the stamp.</summary> [Microsoft.Azure.PowerShell.Cmdlets.Functions.Origin(Microsoft.Azure.PowerShell.Cmdlets.Functions.PropertyOrigin.Owned)] public string Name { get => this._name; set => this._name = value; } /// <summary>Backing field for <see cref="SiteMode" /> property.</summary> private string _siteMode; /// <summary>Shared or Dedicated.</summary> [Microsoft.Azure.PowerShell.Cmdlets.Functions.Origin(Microsoft.Azure.PowerShell.Cmdlets.Functions.PropertyOrigin.Owned)] public string SiteMode { get => this._siteMode; set => this._siteMode = value; } /// <summary>Backing field for <see cref="TotalCapacity" /> property.</summary> private long? _totalCapacity; /// <summary>Total capacity (# of machines, bytes of storage etc...).</summary> [Microsoft.Azure.PowerShell.Cmdlets.Functions.Origin(Microsoft.Azure.PowerShell.Cmdlets.Functions.PropertyOrigin.Owned)] public long? TotalCapacity { get => this._totalCapacity; set => this._totalCapacity = value; } /// <summary>Backing field for <see cref="Unit" /> property.</summary> private string _unit; /// <summary>Name of the unit.</summary> [Microsoft.Azure.PowerShell.Cmdlets.Functions.Origin(Microsoft.Azure.PowerShell.Cmdlets.Functions.PropertyOrigin.Owned)] public string Unit { get => this._unit; set => this._unit = value; } /// <summary>Backing field for <see cref="WorkerSize" /> property.</summary> private Microsoft.Azure.PowerShell.Cmdlets.Functions.Support.WorkerSizeOptions? _workerSize; /// <summary>Size of the machines.</summary> [Microsoft.Azure.PowerShell.Cmdlets.Functions.Origin(Microsoft.Azure.PowerShell.Cmdlets.Functions.PropertyOrigin.Owned)] public Microsoft.Azure.PowerShell.Cmdlets.Functions.Support.WorkerSizeOptions? WorkerSize { get => this._workerSize; set => this._workerSize = value; } /// <summary>Backing field for <see cref="WorkerSizeId" /> property.</summary> private int? _workerSizeId; /// <summary> /// Size ID of machines: /// 0 - Small /// 1 - Medium /// 2 - Large /// </summary> [Microsoft.Azure.PowerShell.Cmdlets.Functions.Origin(Microsoft.Azure.PowerShell.Cmdlets.Functions.PropertyOrigin.Owned)] public int? WorkerSizeId { get => this._workerSizeId; set => this._workerSizeId = value; } /// <summary>Creates an new <see cref="StampCapacity" /> instance.</summary> public StampCapacity() { } } /// Stamp capacity information. public partial interface IStampCapacity : Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.IJsonSerializable { /// <summary>Available capacity (# of machines, bytes of storage etc...).</summary> [Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Info( Required = false, ReadOnly = false, Description = @"Available capacity (# of machines, bytes of storage etc...).", SerializedName = @"availableCapacity", PossibleTypes = new [] { typeof(long) })] long? AvailableCapacity { get; set; } /// <summary>Shared/dedicated workers.</summary> [Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Info( Required = false, ReadOnly = false, Description = @"Shared/dedicated workers.", SerializedName = @"computeMode", PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Functions.Support.ComputeModeOptions) })] Microsoft.Azure.PowerShell.Cmdlets.Functions.Support.ComputeModeOptions? ComputeMode { get; set; } /// <summary> /// If <code>true</code>, it includes basic apps. /// Basic apps are not used for capacity allocation. /// </summary> [Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Info( Required = false, ReadOnly = false, Description = @"If <code>true</code>, it includes basic apps. Basic apps are not used for capacity allocation.", SerializedName = @"excludeFromCapacityAllocation", PossibleTypes = new [] { typeof(bool) })] bool? ExcludeFromCapacityAllocation { get; set; } /// <summary> /// <code>true</code> if capacity is applicable for all apps; otherwise, <code>false</code>. /// </summary> [Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Info( Required = false, ReadOnly = false, Description = @"<code>true</code> if capacity is applicable for all apps; otherwise, <code>false</code>.", SerializedName = @"isApplicableForAllComputeModes", PossibleTypes = new [] { typeof(bool) })] bool? IsApplicableForAllComputeMode { get; set; } /// <summary>Is this a linux stamp capacity</summary> [Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Info( Required = false, ReadOnly = false, Description = @"Is this a linux stamp capacity", SerializedName = @"isLinux", PossibleTypes = new [] { typeof(bool) })] bool? IsLinux { get; set; } /// <summary>Name of the stamp.</summary> [Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Info( Required = false, ReadOnly = false, Description = @"Name of the stamp.", SerializedName = @"name", PossibleTypes = new [] { typeof(string) })] string Name { get; set; } /// <summary>Shared or Dedicated.</summary> [Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Info( Required = false, ReadOnly = false, Description = @"Shared or Dedicated.", SerializedName = @"siteMode", PossibleTypes = new [] { typeof(string) })] string SiteMode { get; set; } /// <summary>Total capacity (# of machines, bytes of storage etc...).</summary> [Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Info( Required = false, ReadOnly = false, Description = @"Total capacity (# of machines, bytes of storage etc...).", SerializedName = @"totalCapacity", PossibleTypes = new [] { typeof(long) })] long? TotalCapacity { get; set; } /// <summary>Name of the unit.</summary> [Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Info( Required = false, ReadOnly = false, Description = @"Name of the unit.", SerializedName = @"unit", PossibleTypes = new [] { typeof(string) })] string Unit { get; set; } /// <summary>Size of the machines.</summary> [Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Info( Required = false, ReadOnly = false, Description = @"Size of the machines.", SerializedName = @"workerSize", PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Functions.Support.WorkerSizeOptions) })] Microsoft.Azure.PowerShell.Cmdlets.Functions.Support.WorkerSizeOptions? WorkerSize { get; set; } /// <summary> /// Size ID of machines: /// 0 - Small /// 1 - Medium /// 2 - Large /// </summary> [Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Info( Required = false, ReadOnly = false, Description = @"Size ID of machines: 0 - Small 1 - Medium 2 - Large", SerializedName = @"workerSizeId", PossibleTypes = new [] { typeof(int) })] int? WorkerSizeId { get; set; } } /// Stamp capacity information. internal partial interface IStampCapacityInternal { /// <summary>Available capacity (# of machines, bytes of storage etc...).</summary> long? AvailableCapacity { get; set; } /// <summary>Shared/dedicated workers.</summary> Microsoft.Azure.PowerShell.Cmdlets.Functions.Support.ComputeModeOptions? ComputeMode { get; set; } /// <summary> /// If <code>true</code>, it includes basic apps. /// Basic apps are not used for capacity allocation. /// </summary> bool? ExcludeFromCapacityAllocation { get; set; } /// <summary> /// <code>true</code> if capacity is applicable for all apps; otherwise, <code>false</code>. /// </summary> bool? IsApplicableForAllComputeMode { get; set; } /// <summary>Is this a linux stamp capacity</summary> bool? IsLinux { get; set; } /// <summary>Name of the stamp.</summary> string Name { get; set; } /// <summary>Shared or Dedicated.</summary> string SiteMode { get; set; } /// <summary>Total capacity (# of machines, bytes of storage etc...).</summary> long? TotalCapacity { get; set; } /// <summary>Name of the unit.</summary> string Unit { get; set; } /// <summary>Size of the machines.</summary> Microsoft.Azure.PowerShell.Cmdlets.Functions.Support.WorkerSizeOptions? WorkerSize { get; set; } /// <summary> /// Size ID of machines: /// 0 - Small /// 1 - Medium /// 2 - Large /// </summary> int? WorkerSizeId { get; set; } } }
50.852
164
0.634705
[ "MIT" ]
3quanfeng/azure-powershell
src/Functions/generated/api/Models/Api20190801/StampCapacity.cs
12,464
C#
using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Linq; using System.Threading.Tasks; using System.Windows; namespace FlutterHost { /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App : Application { } }
18.055556
42
0.704615
[ "Unlicense" ]
fsdsabel/flutter_net_host
src/FlutterHost/App.xaml.cs
327
C#
using System; using System.Threading; using Microsoft.Extensions.Logging; using Orleans.Runtime.Scheduler; namespace Orleans.Runtime.Messaging { internal class IncomingMessageAgent : AsynchAgent { private readonly IMessageCenter messageCenter; private readonly ActivationDirectory directory; private readonly OrleansTaskScheduler scheduler; private readonly Dispatcher dispatcher; private readonly MessageFactory messageFactory; private readonly Message.Categories category; internal IncomingMessageAgent( Message.Categories cat, IMessageCenter mc, ActivationDirectory ad, OrleansTaskScheduler sched, Dispatcher dispatcher, MessageFactory messageFactory, ExecutorService executorService, ILoggerFactory loggerFactory) : base(cat.ToString(), executorService, loggerFactory) { category = cat; messageCenter = mc; directory = ad; scheduler = sched; this.dispatcher = dispatcher; this.messageFactory = messageFactory; OnFault = FaultBehavior.RestartOnFault; } public override void Start() { base.Start(); if (Log.IsEnabled(LogLevel.Trace)) Log.Trace("Started incoming message agent for silo at {0} for {1} messages", messageCenter.MyAddress, category); } protected override void Run() { try { #if TRACK_DETAILED_STATS if (StatisticsCollector.CollectThreadTimeTrackingStats) { threadTracking.OnStartExecution(); } #endif CancellationToken ct = Cts.Token; while (true) { // Get an application message var msg = messageCenter.WaitMessage(category, ct); if (msg == null) { if (Log.IsEnabled(LogLevel.Debug)) Log.Debug("Dequeued a null message, exiting"); // Null return means cancelled break; } #if TRACK_DETAILED_STATS if (StatisticsCollector.CollectThreadTimeTrackingStats) { threadTracking.OnStartProcessing(); } #endif ReceiveMessage(msg); #if TRACK_DETAILED_STATS if (StatisticsCollector.CollectThreadTimeTrackingStats) { threadTracking.OnStopProcessing(); threadTracking.IncrementNumberOfProcessed(); } #endif } } finally { #if TRACK_DETAILED_STATS if (StatisticsCollector.CollectThreadTimeTrackingStats) { threadTracking.OnStopExecution(); } #endif } } private void ReceiveMessage(Message msg) { MessagingProcessingStatisticsGroup.OnImaMessageReceived(msg); ISchedulingContext context; // Find the activation it targets; first check for a system activation, then an app activation if (msg.TargetGrain.IsSystemTarget) { SystemTarget target = directory.FindSystemTarget(msg.TargetActivation); if (target == null) { MessagingStatisticsGroup.OnRejectedMessage(msg); Message response = this.messageFactory.CreateRejectionResponse(msg, Message.RejectionTypes.Unrecoverable, String.Format("SystemTarget {0} not active on this silo. Msg={1}", msg.TargetGrain, msg)); messageCenter.SendMessage(response); Log.Warn(ErrorCode.MessagingMessageFromUnknownActivation, "Received a message {0} for an unknown SystemTarget: {1}", msg, msg.TargetAddress); return; } context = target.SchedulingContext; switch (msg.Direction) { case Message.Directions.Request: MessagingProcessingStatisticsGroup.OnImaMessageEnqueued(context); scheduler.QueueWorkItem(new RequestWorkItem(target, msg), context); break; case Message.Directions.Response: MessagingProcessingStatisticsGroup.OnImaMessageEnqueued(context); scheduler.QueueWorkItem(new ResponseWorkItem(target, msg), context); break; default: Log.Error(ErrorCode.Runtime_Error_100097, "Invalid message: " + msg); break; } } else { // Run this code on the target activation's context, if it already exists ActivationData targetActivation = directory.FindTarget(msg.TargetActivation); if (targetActivation != null) { lock (targetActivation) { var target = targetActivation; // to avoid a warning about nulling targetActivation under a lock on it if (target.State == ActivationState.Valid) { // Response messages are not subject to overload checks. if (msg.Direction != Message.Directions.Response) { var overloadException = target.CheckOverloaded(Log); if (overloadException != null) { // Send rejection as soon as we can, to avoid creating additional work for runtime dispatcher.RejectMessage(msg, Message.RejectionTypes.Overloaded, overloadException, "Target activation is overloaded " + target); return; } } // Run ReceiveMessage in context of target activation context = target.SchedulingContext; } else { // Can't use this activation - will queue for another activation target = null; context = null; } EnqueueReceiveMessage(msg, target, context); } } else { // No usable target activation currently, so run ReceiveMessage in system context EnqueueReceiveMessage(msg, null, null); } } } private void EnqueueReceiveMessage(Message msg, ActivationData targetActivation, ISchedulingContext context) { MessagingProcessingStatisticsGroup.OnImaMessageEnqueued(context); if (targetActivation != null) targetActivation.IncrementEnqueuedOnDispatcherCount(); scheduler.QueueWorkItem(new ClosureWorkItem(() => { try { dispatcher.ReceiveMessage(msg); } finally { if (targetActivation != null) targetActivation.DecrementEnqueuedOnDispatcherCount(); } }, "Dispatcher.ReceiveMessage"), context); } } }
40.497409
165
0.519575
[ "MIT" ]
MikeHardman/orleans
src/Orleans.Runtime/Messaging/IncomingMessageAgent.cs
7,816
C#
#region License // Copyright (c) 2007 James Newton-King // // 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. #endregion using System; namespace Newtonsoft.Json.Utilities { internal struct StringReference { private readonly char[] _chars; private readonly int _startIndex; private readonly int _length; public char this[int i] => _chars[i]; public char[] Chars => _chars; public int StartIndex => _startIndex; public int Length => _length; public StringReference(char[] chars, int startIndex, int length) { _chars = chars; _startIndex = startIndex; _length = length; } public override string ToString() { return new string(_chars, _startIndex, _length); } } internal static class StringReferenceExtensions { public static int IndexOf(this StringReference s, char c, int startIndex, int length) { int index = Array.IndexOf(s.Chars, c, s.StartIndex + startIndex, length); if (index == -1) { return -1; } return index - s.StartIndex; } public static bool StartsWith(this StringReference s, string text) { if (text.Length > s.Length) { return false; } char[] chars = s.Chars; for (int i = 0; i < text.Length; i++) { if (text[i] != chars[i + s.StartIndex]) { return false; } } return true; } public static bool EndsWith(this StringReference s, string text) { if (text.Length > s.Length) { return false; } char[] chars = s.Chars; int start = s.StartIndex + s.Length - text.Length; for (int i = 0; i < text.Length; i++) { if (text[i] != chars[i + start]) { return false; } } return true; } } }
29.108108
93
0.573816
[ "MIT" ]
AArnott/Newtonsoft.Json
Src/Newtonsoft.Json/Utilities/StringReference.cs
3,233
C#
using System; using System.Linq; using Expressive.Exceptions; using Expressive.Expressions; using Expressive.Functions; using Moq; using NUnit.Framework; using NUnit.Framework.Constraints; namespace Expressive.Tests.Functions { public static class FunctionBaseTests { [Test] public static void TestValidateParameterCountWithNull() => Assert.That( () => new MockFunction().Validate(null, 0, 0), Throws.ArgumentNullException); [TestCase(0, 0, 0, false, TestName = "{m} - No parameters expected and none passed in.")] [TestCase(1, 0, 0, true, TestName = "{m} - No parameters expected but some passed in.")] [TestCase(0, 1, 0, true, TestName = "{m} - One parameter expected but none passed in.")] [TestCase(1, 1, 0, false, TestName = "{m} - One parameter expected and one passed in.")] [TestCase(2, 1, 0, true, TestName = "{m} - One parameter expected and two passed in.")] [TestCase(0, -1, 1, true, TestName = "{m} - One minimum expected but none passed in.")] [TestCase(1, -1, 1, false, TestName = "{m} - One minimum expected and one passed in.")] [TestCase(2, -1, 1, false, TestName = "{m} - One minimum expected and two passed in.")] public static void TestValidateParameterCount(int parameterCount, int expectedParameterCount, int expectedMinimumCount, bool shouldThrow) { var parameters = Enumerable.Repeat(Mock.Of<IExpression>(), parameterCount).ToArray(); Assert.That( () => new MockFunction().Validate(parameters, expectedParameterCount, expectedMinimumCount), shouldThrow ? (Constraint)Throws.InstanceOf<ParameterCountMismatchException>() : Throws.Nothing); } private class MockFunction : FunctionBase { public override string Name => "Mock"; public override object Evaluate(IExpression[] parameters, Context context) => throw new NotImplementedException(); public void Validate(IExpression[] parameters, int expectedCount, int minimumCount) => this.ValidateParameterCount(parameters, expectedCount, minimumCount); } } }
46.375
145
0.653639
[ "MIT" ]
antoniaelek/expressive
Source/Expressive.Tests/Functions/FunctionBaseTests.cs
2,228
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("P06StringsAndObjects")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("SAP AG")] [assembly: AssemblyProduct("P06StringsAndObjects")] [assembly: AssemblyCopyright("Copyright © SAP AG 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("20f86043-4423-4bfb-adce-285b7689cd1f")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.513514
84
0.748772
[ "MIT" ]
melnelen/CSharpPart1
H02DataTypesAndVariables/P06StringsAndObjects/Properties/AssemblyInfo.cs
1,428
C#
/** * Copyright (C) 2015 smndtrl * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ using System; namespace Tr.Com.Eimza.LibAxolotl.exceptions { public class UntrustedIdentityException : Exception { private readonly String name; private readonly IdentityKey key; public UntrustedIdentityException(String name, IdentityKey key) { this.name = name; this.key = key; } public IdentityKey GetUntrustedIdentity() { return key; } public String GetName() { return name; } } }
28.465116
72
0.661765
[ "MIT" ]
BayrakMustafa/WhatsApp-API-NET
MyLibAxolotl/UntrustedIdentityException.cs
1,226
C#
using System; using Newtonsoft.Json; using Valetude.Rollbar; using Xunit; namespace Rollbar.Test { public class RollbarExceptionFixture { [Fact] public void Exception_cant_be_null() { Assert.Throws<ArgumentNullException>(() => { var rollbarException = new RollbarException((Exception) null); }); } [Fact] public void Exception_from_exception_has_class() { var rollbarException = new RollbarException(GetException()); Assert.Equal("System.NotFiniteNumberException", rollbarException.Class); } [Fact] public void Exception_from_exception_can_have_message() { var rollbarException = new RollbarException(GetException()) { Message = "Hello World!", }; Assert.Equal("Hello World!", rollbarException.Message); } [Fact] public void Exception_from_exception_can_have_description() { var rollbarException = new RollbarException(GetException()) { Description = "Hello World!", }; Assert.Equal("Hello World!", rollbarException.Description); } [Fact] public void Exception_from_class_name_has_class() { var rollbarException = new RollbarException("NotFiniteNumberException"); Assert.Equal("NotFiniteNumberException", rollbarException.Class); } [Fact] public void Exception_from_class_name_can_have_mesasge() { var rollbarException = new RollbarException("NotFiniteNumberException") { Message = "Hello World!", }; Assert.Equal("Hello World!", rollbarException.Message); } [Fact] public void Exception_from_class_name_can_have_description() { var rollbarException = new RollbarException("NotFiniteNumberException") { Description = "Hello World!", }; Assert.Equal("Hello World!", rollbarException.Description); } [Fact] public void Exception_serializes_correctly() { var rollbarException = new RollbarException("Test"); Assert.Equal("{\"class\":\"Test\"}", JsonConvert.SerializeObject(rollbarException)); } [Fact] public void Exceptoin_serializes_message_correctly() { var rollbarException = new RollbarException("Test") {Message = "Oops!"}; Assert.Contains("\"message\":\"Oops!\"", JsonConvert.SerializeObject(rollbarException)); Assert.Contains("\"class\":\"Test\"", JsonConvert.SerializeObject(rollbarException)); } [Fact] public void Exceptoin_serializes_description_correctly() { var rollbarException = new RollbarException("Test") { Description = "Oops!" }; Assert.Contains("\"description\":\"Oops!\"", JsonConvert.SerializeObject(rollbarException)); Assert.Contains("\"class\":\"Test\"", JsonConvert.SerializeObject(rollbarException)); } private static Exception GetException() { try { throw new NotFiniteNumberException("Not a Finite Number!"); } catch (Exception e) { return e; } } } }
37.393258
104
0.605769
[ "MIT" ]
Valetude/Rollbar.Net
Valetude.Rollbar.Test/RollbarExceptionFixture.cs
3,330
C#
// SPDX-License-Identifier: Apache-2.0 // Licensed to the Ed-Fi Alliance under one or more agreements. // The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. // See the LICENSE and NOTICES files in the project root for more information. using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using EdFi.LoadTools.ApiClient; using EdFi.LoadTools.Common; using EdFi.LoadTools.Engine.Mapping; using EdFi.Ods.Common.Inflection; namespace EdFi.LoadTools.Engine.MappingFactories { public class ResourceToIdentityMetadataMappingFactory : MetadataMappingFactoryBase { private readonly Regex _typeRegex = new Regex(Constants.IdentityTypeRegex); public ResourceToIdentityMetadataMappingFactory( IEnumerable<XmlModelMetadata> xmlMetadata, IEnumerable<JsonModelMetadata> jsonMetadata, IEnumerable<IMetadataMapper> mappingStrategies) : base(xmlMetadata, jsonMetadata, mappingStrategies) { } protected override IList<XmlModelMetadata> FilteredXmlMetadata => XmlMetadata.Where(x => !x.Type.EndsWith("ReferenceType")).ToList(); protected override IEnumerable<MetadataMapping> CreateMappings() { Log.Info("Creating XSD Resource to Json Identity data mappings"); var typeNames = XmlMetadata.Select(x => x.Type).Distinct().Where(x => _typeRegex.IsMatch(x)); var mappings = typeNames.Select( x => { var typeName = _typeRegex.Match(x).Groups["TypeName"].Value; return new MetadataMapping { RootName = typeName, SourceName = x, //xml TargetName = Inflector.MakeInitialLowerCase(typeName) //json }; }).ToArray(); return mappings; } } }
39.795918
141
0.651282
[ "Apache-2.0" ]
gmcelhanon/Ed-Fi-ODS-1
Utilities/DataLoading/EdFi.LoadTools/Engine/MappingFactories/ResourceToIdentityMetadataMappingFactory.cs
1,950
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 System.Linq; using JetBrains.Annotations; using Microsoft.EntityFrameworkCore.Internal; namespace Microsoft.EntityFrameworkCore.Metadata.Internal { /// <summary> /// This API supports the Entity Framework Core infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> public class TableMapping { /// <summary> /// This API supports the Entity Framework Core infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> public TableMapping( [CanBeNull] string schema, [NotNull] string name, [NotNull] IReadOnlyList<IEntityType> entityTypes) { Schema = schema; Name = name; EntityTypes = entityTypes; } /// <summary> /// This API supports the Entity Framework Core infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> public virtual string Schema { get; } /// <summary> /// This API supports the Entity Framework Core infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> public virtual string Name { get; } /// <summary> /// This API supports the Entity Framework Core infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> public virtual IReadOnlyList<IEntityType> EntityTypes { get; } /// <summary> /// This API supports the Entity Framework Core infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> public virtual IEntityType GetRootType() => EntityTypes.SingleOrDefault( t => t.BaseType == null && t.FindForeignKeys(t.FindDeclaredPrimaryKey().Properties) .All(fk => !fk.PrincipalKey.IsPrimaryKey() || fk.PrincipalEntityType.RootType() == t || t.Relational().TableName != fk.PrincipalEntityType.Relational().TableName || t.Relational().Schema != fk.PrincipalEntityType.Relational().Schema)); /// <summary> /// This API supports the Entity Framework Core infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> public virtual IEnumerable<IProperty> GetProperties() => GetPropertyMap().Values; /// <summary> /// This API supports the Entity Framework Core infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> public virtual Dictionary<string, IProperty> GetPropertyMap() { var dictionary = new Dictionary<string, IProperty>(); foreach (var property in EntityTypes.SelectMany(EntityTypeExtensions.GetDeclaredProperties)) { var columnName = property.Relational().ColumnName; if (!dictionary.ContainsKey(columnName)) { dictionary[columnName] = property; } } return dictionary; } /// <summary> /// This API supports the Entity Framework Core infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> public virtual IEnumerable<IKey> GetKeys() => EntityTypes.SelectMany(EntityTypeExtensions.GetDeclaredKeys) .Distinct((x, y) => x.Relational().Name == y.Relational().Name); /// <summary> /// This API supports the Entity Framework Core infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> public virtual IEnumerable<IIndex> GetIndexes() => EntityTypes.SelectMany(EntityTypeExtensions.GetDeclaredIndexes) .Distinct((x, y) => x.Relational().Name == y.Relational().Name); /// <summary> /// This API supports the Entity Framework Core infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> public virtual IEnumerable<IForeignKey> GetForeignKeys() => EntityTypes.SelectMany(EntityTypeExtensions.GetDeclaredForeignKeys) .Distinct((x, y) => x.Relational().Name == y.Relational().Name) .Where( fk => !(EntityTypes.Contains(fk.PrincipalEntityType) && fk.Properties.Select(p => p.Relational().ColumnName) .SequenceEqual(fk.PrincipalKey.Properties.Select(p => p.Relational().ColumnName)))); /// <summary> /// This API supports the Entity Framework Core infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> public static IReadOnlyList<TableMapping> GetTableMappings([NotNull] IModel model) { var tables = new Dictionary<(string Schema, string TableName), List<IEntityType>>(); foreach (var entityType in model.GetEntityTypes().Where(et => !et.IsQueryType)) { var relationalExtentions = entityType.Relational(); var fullName = (relationalExtentions.Schema, relationalExtentions.TableName); if (!tables.TryGetValue(fullName, out var mappedEntityTypes)) { mappedEntityTypes = new List<IEntityType>(); tables.Add(fullName, mappedEntityTypes); } // TODO: Consider sorting to keep hierarchies together mappedEntityTypes.Add(entityType); } return tables.Select(kv => new TableMapping(kv.Key.Schema, kv.Key.TableName, kv.Value)) .OrderBy(t => t.Schema).ThenBy(t => t.Name).ToList(); } /// <summary> /// This API supports the Entity Framework Core infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> public static TableMapping GetTableMapping([NotNull] IModel model, [NotNull] string table, [CanBeNull] string schema) { var mappedEntities = new List<IEntityType>(); foreach (var entityType in model.GetEntityTypes().Where(et => !et.IsQueryType)) { var relationalExtentions = entityType.Relational(); if (table == relationalExtentions.TableName && schema == relationalExtentions.Schema) { mappedEntities.Add(entityType); } } return mappedEntities.Count > 0 ? new TableMapping(schema, table, mappedEntities) : null; } } }
48.791411
125
0.599145
[ "Apache-2.0" ]
chrisblock/EntityFramework
src/EFCore.Relational/Metadata/Internal/TableMapping.cs
7,953
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.Win32.SafeHandles; using System; using System.Runtime.InteropServices; internal partial class Interop { internal partial class Advapi32 { [DllImport(Libraries.Advapi32, EntryPoint = "OpenServiceW", CharSet = CharSet.Unicode, SetLastError = true)] internal static extern IntPtr OpenService(SafeServiceHandle databaseHandle, string serviceName, int access); } }
35.823529
116
0.761905
[ "MIT" ]
1shekhar/runtime
src/libraries/Common/src/Interop/Windows/Advapi32/Interop.OpenService.cs
609
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Internal; using Microsoft.AspNetCore.Mvc.Abstractions; using Microsoft.AspNetCore.Mvc.ModelBinding; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.AspNetCore.Mvc.ViewEngines; using Microsoft.AspNetCore.Routing; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging.Testing; using Moq; using Xunit; namespace Microsoft.AspNetCore.Mvc.ViewFeatures.Internal { // These tests cover the logic included in PartialViewResult.ExecuteResultAsync - see PartialViewResultExecutorTest // and ViewExecutorTest for more comprehensive tests. public class PartialViewResultTest { [Fact] public async Task ExecuteResultAsync_Throws_IfViewCouldNotBeFound_MessageUsesGetViewLocations() { // Arrange var expected = string.Join( Environment.NewLine, "The view 'MyView' was not found. The following locations were searched:", "Location1", "Location2"); var actionContext = GetActionContext(); var viewEngine = new Mock<IViewEngine>(MockBehavior.Strict); viewEngine .Setup(v => v.GetView(/*executingFilePath*/ null, "MyView", /*isMainPage*/ false)) .Returns(ViewEngineResult.NotFound("MyView", new[] { "Location1", "Location2" })) .Verifiable(); viewEngine .Setup(v => v.FindView(It.IsAny<ActionContext>(), "MyView", /*isMainPage*/ false)) .Returns(ViewEngineResult.NotFound("MyView", Enumerable.Empty<string>())) .Verifiable(); var viewResult = new PartialViewResult { ViewEngine = viewEngine.Object, ViewName = "MyView", ViewData = new ViewDataDictionary(new EmptyModelMetadataProvider()), TempData = Mock.Of<ITempDataDictionary>(), }; // Act and Assert var ex = await Assert.ThrowsAsync<InvalidOperationException>( () => viewResult.ExecuteResultAsync(actionContext)); Assert.Equal(expected, ex.Message); viewEngine.Verify(); } [Fact] public async Task ExecuteResultAsync_Throws_IfViewCouldNotBeFound_MessageUsesFindViewLocations() { // Arrange var expected = string.Join( Environment.NewLine, "The view 'MyView' was not found. The following locations were searched:", "Location1", "Location2"); var actionContext = GetActionContext(); var viewEngine = new Mock<IViewEngine>(MockBehavior.Strict); viewEngine .Setup(v => v.GetView(/*executingFilePath*/ null, "MyView", /*isMainPage*/ false)) .Returns(ViewEngineResult.NotFound("MyView", Enumerable.Empty<string>())) .Verifiable(); viewEngine .Setup(v => v.FindView(It.IsAny<ActionContext>(), "MyView", /*isMainPage*/ false)) .Returns(ViewEngineResult.NotFound("MyView", new[] { "Location1", "Location2" })) .Verifiable(); var viewResult = new PartialViewResult { ViewEngine = viewEngine.Object, ViewName = "MyView", ViewData = new ViewDataDictionary(new EmptyModelMetadataProvider()), TempData = Mock.Of<ITempDataDictionary>(), }; // Act and Assert var ex = await Assert.ThrowsAsync<InvalidOperationException>( () => viewResult.ExecuteResultAsync(actionContext)); Assert.Equal(expected, ex.Message); viewEngine.Verify(); } [Fact] public async Task ExecuteResultAsync_Throws_IfViewCouldNotBeFound_MessageUsesAllLocations() { // Arrange var expected = string.Join( Environment.NewLine, "The view 'MyView' was not found. The following locations were searched:", "Location1", "Location2", "Location3", "Location4"); var actionContext = GetActionContext(); var viewEngine = new Mock<IViewEngine>(MockBehavior.Strict); viewEngine .Setup(v => v.GetView(/*executingFilePath*/ null, "MyView", /*isMainPage*/ false)) .Returns(ViewEngineResult.NotFound("MyView", new[] { "Location1", "Location2" })) .Verifiable(); viewEngine .Setup(v => v.FindView(It.IsAny<ActionContext>(), "MyView", /*isMainPage*/ false)) .Returns(ViewEngineResult.NotFound("MyView", new[] { "Location3", "Location4" })) .Verifiable(); var viewResult = new PartialViewResult { ViewEngine = viewEngine.Object, ViewName = "MyView", ViewData = new ViewDataDictionary(new EmptyModelMetadataProvider()), TempData = Mock.Of<ITempDataDictionary>(), }; // Act and Assert var ex = await Assert.ThrowsAsync<InvalidOperationException>( () => viewResult.ExecuteResultAsync(actionContext)); Assert.Equal(expected, ex.Message); viewEngine.Verify(); } [Fact] public async Task ExecuteResultAsync_FindsAndExecutesView() { // Arrange var viewName = "myview"; var context = GetActionContext(); var view = new Mock<IView>(MockBehavior.Strict); view .Setup(v => v.RenderAsync(It.IsAny<ViewContext>())) .Returns(Task.FromResult(0)) .Verifiable(); view .As<IDisposable>() .Setup(v => v.Dispose()) .Verifiable(); // Used by logging view .SetupGet(v => v.Path) .Returns("myview.cshtml"); var viewEngine = new Mock<IViewEngine>(MockBehavior.Strict); viewEngine .Setup(v => v.GetView(/*executingFilePath*/ null, "myview", /*isMainPage*/ false)) .Returns(ViewEngineResult.NotFound("myview", Enumerable.Empty<string>())) .Verifiable(); viewEngine .Setup(v => v.FindView(It.IsAny<ActionContext>(), "myview", /*isMainPage*/ false)) .Returns(ViewEngineResult.Found("myview", view.Object)) .Verifiable(); var viewResult = new PartialViewResult { ViewName = viewName, ViewEngine = viewEngine.Object, ViewData = new ViewDataDictionary(new EmptyModelMetadataProvider()), TempData = Mock.Of<ITempDataDictionary>(), }; // Act await viewResult.ExecuteResultAsync(context); // Assert view.Verify(); viewEngine.Verify(); } private ActionContext GetActionContext() { return new ActionContext(GetHttpContext(), new RouteData(), new ActionDescriptor()); } private HttpContext GetHttpContext() { var options = new TestOptionsManager<MvcViewOptions>(); var viewExecutor = new PartialViewResultExecutor( options, new TestHttpResponseStreamWriterFactory(), new CompositeViewEngine(options), new TempDataDictionaryFactory(new SessionStateTempDataProvider()), new DiagnosticListener("Microsoft.AspNetCore"), NullLoggerFactory.Instance); var services = new ServiceCollection(); services.AddSingleton(viewExecutor); var httpContext = new DefaultHttpContext(); httpContext.RequestServices = services.BuildServiceProvider(); return httpContext; } } }
39.247664
119
0.578878
[ "Apache-2.0" ]
Mani4007/ASPNET
test/Microsoft.AspNetCore.Mvc.ViewFeatures.Test/Internal/PartialViewResultTest.cs
8,399
C#
using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using Parse; using Parse.Core.Internal; using System; using System.Collections.Generic; using System.Net; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; namespace Parse.Test { [TestClass] public class UserControllerTests { [TestInitialize] public void SetUp() => ParseClient.Initialize(new ParseClient.Configuration { ApplicationID = "", Key = "" }); [TestMethod] [AsyncStateMachine(typeof(UserControllerTests))] public Task TestSignUp() { MutableObjectState state = new MutableObjectState { ClassName = "_User", ServerData = new Dictionary<string, object>() { { "username", "hallucinogen" }, { "password", "secret" } } }; Dictionary<string, IParseFieldOperation> operations = new Dictionary<string, IParseFieldOperation>() { { "gogo", new Mock<IParseFieldOperation>().Object } }; Dictionary<string, object> responseDict = new Dictionary<string, object>() { { "__type", "Object" }, { "className", "_User" }, { "objectId", "d3ImSh3ki" }, { "sessionToken", "s3ss10nt0k3n" }, { "createdAt", "2015-09-18T18:11:28.943Z" } }; Tuple<HttpStatusCode, IDictionary<string, object>> response = new Tuple<HttpStatusCode, IDictionary<string, object>>(HttpStatusCode.Accepted, responseDict); Mock<IParseCommandRunner> mockRunner = CreateMockRunner(response); ParseUserController controller = new ParseUserController(mockRunner.Object); return controller.SignUpAsync(state, operations, CancellationToken.None).ContinueWith(t => { Assert.IsFalse(t.IsFaulted); Assert.IsFalse(t.IsCanceled); mockRunner.Verify(obj => obj.RunCommandAsync(It.Is<ParseCommand>(command => command.Uri.AbsolutePath == "/1/classes/_User"), It.IsAny<IProgress<ParseUploadProgressEventArgs>>(), It.IsAny<IProgress<ParseDownloadProgressEventArgs>>(), It.IsAny<CancellationToken>()), Times.Exactly(1)); IObjectState newState = t.Result; Assert.AreEqual("s3ss10nt0k3n", newState["sessionToken"]); Assert.AreEqual("d3ImSh3ki", newState.ObjectId); Assert.IsNotNull(newState.CreatedAt); Assert.IsNotNull(newState.UpdatedAt); }); } [TestMethod] [AsyncStateMachine(typeof(UserControllerTests))] public Task TestLogInWithUsernamePassword() { Dictionary<string, object> responseDict = new Dictionary<string, object>() { { "__type", "Object" }, { "className", "_User" }, { "objectId", "d3ImSh3ki" }, { "sessionToken", "s3ss10nt0k3n" }, { "createdAt", "2015-09-18T18:11:28.943Z" } }; Tuple<HttpStatusCode, IDictionary<string, object>> response = new Tuple<HttpStatusCode, IDictionary<string, object>>(HttpStatusCode.Accepted, responseDict); Mock<IParseCommandRunner> mockRunner = CreateMockRunner(response); ParseUserController controller = new ParseUserController(mockRunner.Object); return controller.LogInAsync("grantland", "123grantland123", CancellationToken.None).ContinueWith(t => { Assert.IsFalse(t.IsFaulted); Assert.IsFalse(t.IsCanceled); mockRunner.Verify(obj => obj.RunCommandAsync(It.Is<ParseCommand>(command => command.Uri.AbsolutePath == "/1/login"), It.IsAny<IProgress<ParseUploadProgressEventArgs>>(), It.IsAny<IProgress<ParseDownloadProgressEventArgs>>(), It.IsAny<CancellationToken>()), Times.Exactly(1)); IObjectState newState = t.Result; Assert.AreEqual("s3ss10nt0k3n", newState["sessionToken"]); Assert.AreEqual("d3ImSh3ki", newState.ObjectId); Assert.IsNotNull(newState.CreatedAt); Assert.IsNotNull(newState.UpdatedAt); }); } [TestMethod] [AsyncStateMachine(typeof(UserControllerTests))] public Task TestLogInWithAuthData() { Dictionary<string, object> responseDict = new Dictionary<string, object>() { { "__type", "Object" }, { "className", "_User" }, { "objectId", "d3ImSh3ki" }, { "sessionToken", "s3ss10nt0k3n" }, { "createdAt", "2015-09-18T18:11:28.943Z" } }; Tuple<HttpStatusCode, IDictionary<string, object>> response = new Tuple<HttpStatusCode, IDictionary<string, object>>(HttpStatusCode.Accepted, responseDict); Mock<IParseCommandRunner> mockRunner = CreateMockRunner(response); ParseUserController controller = new ParseUserController(mockRunner.Object); return controller.LogInAsync("facebook", data: null, cancellationToken: CancellationToken.None).ContinueWith(t => { Assert.IsFalse(t.IsFaulted); Assert.IsFalse(t.IsCanceled); mockRunner.Verify(obj => obj.RunCommandAsync(It.Is<ParseCommand>(command => command.Uri.AbsolutePath == "/1/users"), It.IsAny<IProgress<ParseUploadProgressEventArgs>>(), It.IsAny<IProgress<ParseDownloadProgressEventArgs>>(), It.IsAny<CancellationToken>()), Times.Exactly(1)); IObjectState newState = t.Result; Assert.AreEqual("s3ss10nt0k3n", newState["sessionToken"]); Assert.AreEqual("d3ImSh3ki", newState.ObjectId); Assert.IsNotNull(newState.CreatedAt); Assert.IsNotNull(newState.UpdatedAt); }); } [TestMethod] [AsyncStateMachine(typeof(UserControllerTests))] public Task TestGetUserFromSessionToken() { Dictionary<string, object> responseDict = new Dictionary<string, object>() { { "__type", "Object" }, { "className", "_User" }, { "objectId", "d3ImSh3ki" }, { "sessionToken", "s3ss10nt0k3n" }, { "createdAt", "2015-09-18T18:11:28.943Z" } }; Tuple<HttpStatusCode, IDictionary<string, object>> response = new Tuple<HttpStatusCode, IDictionary<string, object>>(HttpStatusCode.Accepted, responseDict); Mock<IParseCommandRunner> mockRunner = CreateMockRunner(response); ParseUserController controller = new ParseUserController(mockRunner.Object); return controller.GetUserAsync("s3ss10nt0k3n", CancellationToken.None).ContinueWith(t => { Assert.IsFalse(t.IsFaulted); Assert.IsFalse(t.IsCanceled); mockRunner.Verify(obj => obj.RunCommandAsync(It.Is<ParseCommand>(command => command.Uri.AbsolutePath == "/1/users/me"), It.IsAny<IProgress<ParseUploadProgressEventArgs>>(), It.IsAny<IProgress<ParseDownloadProgressEventArgs>>(), It.IsAny<CancellationToken>()), Times.Exactly(1)); IObjectState newState = t.Result; Assert.AreEqual("s3ss10nt0k3n", newState["sessionToken"]); Assert.AreEqual("d3ImSh3ki", newState.ObjectId); Assert.IsNotNull(newState.CreatedAt); Assert.IsNotNull(newState.UpdatedAt); }); } [TestMethod] [AsyncStateMachine(typeof(UserControllerTests))] public Task TestRequestPasswordReset() { Dictionary<string, object> responseDict = new Dictionary<string, object>(); Tuple<HttpStatusCode, IDictionary<string, object>> response = new Tuple<HttpStatusCode, IDictionary<string, object>>(HttpStatusCode.Accepted, responseDict); Mock<IParseCommandRunner> mockRunner = CreateMockRunner(response); ParseUserController controller = new ParseUserController(mockRunner.Object); return controller.RequestPasswordResetAsync("gogo@parse.com", CancellationToken.None).ContinueWith(t => { Assert.IsFalse(t.IsFaulted); Assert.IsFalse(t.IsCanceled); mockRunner.Verify(obj => obj.RunCommandAsync(It.Is<ParseCommand>(command => command.Uri.AbsolutePath == "/1/requestPasswordReset"), It.IsAny<IProgress<ParseUploadProgressEventArgs>>(), It.IsAny<IProgress<ParseDownloadProgressEventArgs>>(), It.IsAny<CancellationToken>()), Times.Exactly(1)); }); } private Mock<IParseCommandRunner> CreateMockRunner(Tuple<HttpStatusCode, IDictionary<string, object>> response) { Mock<IParseCommandRunner> mockRunner = new Mock<IParseCommandRunner>(); mockRunner.Setup(obj => obj.RunCommandAsync(It.IsAny<ParseCommand>(), It.IsAny<IProgress<ParseUploadProgressEventArgs>>(), It.IsAny<IProgress<ParseDownloadProgressEventArgs>>(), It.IsAny<CancellationToken>())) .Returns(Task<Tuple<HttpStatusCode, IDictionary<string, object>>>.FromResult(response)); return mockRunner; } } }
47.489899
168
0.621291
[ "BSD-3-Clause" ]
RxParse/Parse-SDK-dotNET
Parse.Test/UserControllerTests.cs
9,403
C#
// <auto-generated /> using System; using Harvest.Core.Data; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using NetTopologySuite.Geometries; namespace Harvest.Core.Migrations.Sqlite { [DbContext(typeof(AppDbContextSqlite))] [Migration("20210420170842_updateAndRemoveTablesForSlothService")] partial class updateAndRemoveTablesForSlothService { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "5.0.1"); modelBuilder.Entity("Harvest.Core.Domain.Account", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<int?>("ApprovedById") .HasColumnType("INTEGER"); b.Property<DateTime?>("ApprovedOn") .HasColumnType("TEXT"); b.Property<string>("Name") .HasMaxLength(200) .HasColumnType("TEXT"); b.Property<string>("Number") .HasMaxLength(100) .HasColumnType("TEXT"); b.Property<decimal>("Percentage") .HasPrecision(18, 2) .HasColumnType("TEXT"); b.Property<int>("ProjectId") .HasColumnType("INTEGER"); b.HasKey("Id"); b.HasIndex("ApprovedById"); b.HasIndex("Name"); b.HasIndex("Number"); b.HasIndex("ProjectId"); b.ToTable("Accounts"); }); modelBuilder.Entity("Harvest.Core.Domain.Document", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<string>("Identifier") .IsRequired() .HasMaxLength(200) .HasColumnType("TEXT"); b.Property<string>("Name") .HasMaxLength(50) .HasColumnType("TEXT"); b.Property<int>("QuoteId") .HasColumnType("INTEGER"); b.HasKey("Id"); b.HasIndex("Name"); b.HasIndex("QuoteId") .IsUnique(); b.ToTable("Documents"); }); modelBuilder.Entity("Harvest.Core.Domain.Expense", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<string>("Account") .IsRequired() .HasMaxLength(50) .HasColumnType("TEXT"); b.Property<int?>("CreatedById") .HasColumnType("INTEGER"); b.Property<DateTime>("CreatedOn") .HasColumnType("TEXT"); b.Property<string>("Description") .IsRequired() .HasMaxLength(250) .HasColumnType("TEXT"); b.Property<int?>("InvoiceId") .HasColumnType("INTEGER"); b.Property<decimal>("Price") .HasColumnType("TEXT"); b.Property<int>("ProjectId") .HasColumnType("INTEGER"); b.Property<decimal>("Quantity") .HasColumnType("TEXT"); b.Property<int>("RateId") .HasColumnType("INTEGER"); b.Property<decimal>("Total") .HasPrecision(18, 2) .HasColumnType("TEXT"); b.Property<string>("Type") .IsRequired() .HasMaxLength(15) .HasColumnType("TEXT"); b.HasKey("Id"); b.HasIndex("CreatedById"); b.HasIndex("InvoiceId"); b.HasIndex("ProjectId"); b.HasIndex("RateId"); b.ToTable("Expenses"); }); modelBuilder.Entity("Harvest.Core.Domain.Invoice", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<DateTime>("CreatedOn") .HasColumnType("TEXT"); b.Property<string>("Notes") .HasColumnType("TEXT"); b.Property<int>("ProjectId") .HasColumnType("INTEGER"); b.Property<string>("Status") .HasColumnType("TEXT"); b.Property<decimal>("Total") .HasPrecision(18, 2) .HasColumnType("TEXT"); b.HasKey("Id"); b.HasIndex("ProjectId"); b.ToTable("Invoices"); }); modelBuilder.Entity("Harvest.Core.Domain.Notification", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<string>("Body") .IsRequired() .HasColumnType("TEXT"); b.Property<string>("Email") .IsRequired() .HasMaxLength(300) .HasColumnType("TEXT"); b.Property<int>("ProjectId") .HasColumnType("INTEGER"); b.Property<bool>("Sent") .HasColumnType("INTEGER"); b.Property<string>("Subject") .IsRequired() .HasMaxLength(300) .HasColumnType("TEXT"); b.HasKey("Id"); b.HasIndex("ProjectId"); b.ToTable("Notifications"); }); modelBuilder.Entity("Harvest.Core.Domain.Permission", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<int>("RoleId") .HasColumnType("INTEGER"); b.Property<int>("UserId") .HasColumnType("INTEGER"); b.HasKey("Id"); b.HasIndex("RoleId"); b.HasIndex("UserId"); b.ToTable("Permissions"); }); modelBuilder.Entity("Harvest.Core.Domain.Project", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<decimal>("ChargedTotal") .HasPrecision(18, 2) .HasColumnType("TEXT"); b.Property<int>("CreatedById") .HasColumnType("INTEGER"); b.Property<DateTime>("CreatedOn") .HasColumnType("TEXT"); b.Property<string>("Crop") .HasMaxLength(50) .HasColumnType("TEXT"); b.Property<int>("CurrentAccountVersion") .HasColumnType("INTEGER"); b.Property<DateTime>("End") .HasColumnType("TEXT"); b.Property<bool>("IsActive") .HasColumnType("INTEGER"); b.Property<Geometry>("Location") .HasColumnType("GEOMETRY"); b.Property<string>("LocationCode") .HasMaxLength(50) .HasColumnType("TEXT"); b.Property<string>("Name") .HasMaxLength(200) .HasColumnType("TEXT"); b.Property<int>("PrincipalInvestigatorId") .HasColumnType("INTEGER"); b.Property<int?>("QuoteId") .HasColumnType("INTEGER"); b.Property<int?>("QuoteId1") .HasColumnType("INTEGER"); b.Property<decimal>("QuoteTotal") .HasPrecision(18, 2) .HasColumnType("TEXT"); b.Property<string>("Requirements") .HasColumnType("TEXT"); b.Property<DateTime>("Start") .HasColumnType("TEXT"); b.Property<string>("Status") .HasMaxLength(50) .HasColumnType("TEXT"); b.HasKey("Id"); b.HasIndex("CreatedById"); b.HasIndex("Name"); b.HasIndex("PrincipalInvestigatorId"); b.HasIndex("QuoteId"); b.HasIndex("QuoteId1"); b.ToTable("Projects"); }); modelBuilder.Entity("Harvest.Core.Domain.ProjectHistory", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<string>("Action") .HasMaxLength(200) .HasColumnType("TEXT"); b.Property<DateTime>("ActionDate") .HasColumnType("TEXT"); b.Property<int>("Actor") .HasMaxLength(20) .HasColumnType("INTEGER"); b.Property<string>("ActorName") .HasMaxLength(50) .HasColumnType("TEXT"); b.Property<string>("Description") .HasColumnType("TEXT"); b.Property<int>("ProjectId") .HasColumnType("INTEGER"); b.Property<string>("Type") .HasMaxLength(50) .HasColumnType("TEXT"); b.HasKey("Id"); b.HasIndex("ProjectId"); b.ToTable("ProjectHistory"); }); modelBuilder.Entity("Harvest.Core.Domain.Quote", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<int?>("ApprovedById") .HasColumnType("INTEGER"); b.Property<DateTime?>("ApprovedOn") .HasColumnType("TEXT"); b.Property<DateTime>("CreatedDate") .HasColumnType("TEXT"); b.Property<int?>("CurrentDocumentId") .HasColumnType("INTEGER"); b.Property<int>("InitiatedById") .HasColumnType("INTEGER"); b.Property<int>("ProjectId") .HasColumnType("INTEGER"); b.Property<string>("Status") .HasMaxLength(50) .HasColumnType("TEXT"); b.Property<string>("Text") .HasColumnType("TEXT"); b.Property<decimal>("Total") .HasPrecision(18, 2) .HasColumnType("TEXT"); b.HasKey("Id"); b.HasIndex("ApprovedById"); b.HasIndex("CurrentDocumentId") .IsUnique(); b.HasIndex("InitiatedById"); b.HasIndex("ProjectId"); b.ToTable("Quotes"); }); modelBuilder.Entity("Harvest.Core.Domain.Rate", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<string>("Account") .IsRequired() .HasMaxLength(50) .HasColumnType("TEXT"); b.Property<string>("BillingUnit") .HasMaxLength(50) .HasColumnType("TEXT"); b.Property<int>("CreatedById") .HasColumnType("INTEGER"); b.Property<DateTime>("CreatedOn") .HasColumnType("TEXT"); b.Property<string>("Description") .IsRequired() .HasMaxLength(250) .HasColumnType("TEXT"); b.Property<DateTime?>("EffectiveOn") .HasColumnType("TEXT"); b.Property<bool>("IsActive") .HasColumnType("INTEGER"); b.Property<decimal>("Price") .HasPrecision(18, 2) .HasColumnType("TEXT"); b.Property<string>("Type") .IsRequired() .HasMaxLength(15) .HasColumnType("TEXT"); b.Property<string>("Unit") .HasMaxLength(50) .HasColumnType("TEXT"); b.Property<int>("UpdatedById") .HasColumnType("INTEGER"); b.Property<DateTime>("UpdatedOn") .HasColumnType("TEXT"); b.HasKey("Id"); b.HasIndex("CreatedById"); b.HasIndex("Description"); b.HasIndex("Type"); b.HasIndex("UpdatedById"); b.ToTable("Rates"); }); modelBuilder.Entity("Harvest.Core.Domain.Role", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<string>("Name") .IsRequired() .HasMaxLength(50) .HasColumnType("TEXT"); b.HasKey("Id"); b.HasIndex("Name") .IsUnique(); b.ToTable("Roles"); }); modelBuilder.Entity("Harvest.Core.Domain.Transfer", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<string>("Account") .IsRequired() .HasMaxLength(50) .HasColumnType("TEXT"); b.Property<int>("InvoiceId") .HasColumnType("INTEGER"); b.Property<decimal>("Total") .HasPrecision(18, 2) .HasColumnType("TEXT"); b.Property<string>("Type") .IsRequired() .HasMaxLength(10) .HasColumnType("TEXT"); b.HasKey("Id"); b.HasIndex("InvoiceId"); b.ToTable("Transfers"); }); modelBuilder.Entity("Harvest.Core.Domain.User", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<string>("Email") .IsRequired() .HasMaxLength(300) .HasColumnType("TEXT"); b.Property<string>("FirstName") .IsRequired() .HasMaxLength(50) .HasColumnType("TEXT"); b.Property<string>("Iam") .HasMaxLength(10) .HasColumnType("TEXT"); b.Property<string>("Kerberos") .HasMaxLength(20) .HasColumnType("TEXT"); b.Property<string>("LastName") .IsRequired() .HasMaxLength(50) .HasColumnType("TEXT"); b.HasKey("Id"); b.HasIndex("Email"); b.HasIndex("Iam"); b.HasIndex("Kerberos"); b.ToTable("Users"); }); modelBuilder.Entity("Harvest.Core.Domain.Account", b => { b.HasOne("Harvest.Core.Domain.User", "ApprovedBy") .WithMany() .HasForeignKey("ApprovedById"); b.HasOne("Harvest.Core.Domain.Project", "Project") .WithMany("Accounts") .HasForeignKey("ProjectId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.Navigation("ApprovedBy"); b.Navigation("Project"); }); modelBuilder.Entity("Harvest.Core.Domain.Document", b => { b.HasOne("Harvest.Core.Domain.Quote", null) .WithMany("Documents") .HasForeignKey("QuoteId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); }); modelBuilder.Entity("Harvest.Core.Domain.Expense", b => { b.HasOne("Harvest.Core.Domain.User", "CreatedBy") .WithMany() .HasForeignKey("CreatedById"); b.HasOne("Harvest.Core.Domain.Invoice", "Invoice") .WithMany("Expenses") .HasForeignKey("InvoiceId") .OnDelete(DeleteBehavior.Restrict); b.HasOne("Harvest.Core.Domain.Project", "Project") .WithMany() .HasForeignKey("ProjectId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("Harvest.Core.Domain.Rate", "Rate") .WithMany() .HasForeignKey("RateId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("CreatedBy"); b.Navigation("Invoice"); b.Navigation("Project"); b.Navigation("Rate"); }); modelBuilder.Entity("Harvest.Core.Domain.Invoice", b => { b.HasOne("Harvest.Core.Domain.Project", "Project") .WithMany() .HasForeignKey("ProjectId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Project"); }); modelBuilder.Entity("Harvest.Core.Domain.Notification", b => { b.HasOne("Harvest.Core.Domain.Project", "Project") .WithMany() .HasForeignKey("ProjectId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.Navigation("Project"); }); modelBuilder.Entity("Harvest.Core.Domain.Permission", b => { b.HasOne("Harvest.Core.Domain.Role", "Role") .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.HasOne("Harvest.Core.Domain.User", "User") .WithMany("Permissions") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.Navigation("Role"); b.Navigation("User"); }); modelBuilder.Entity("Harvest.Core.Domain.Project", b => { b.HasOne("Harvest.Core.Domain.User", "CreatedBy") .WithMany("CreatedProjects") .HasForeignKey("CreatedById") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.HasOne("Harvest.Core.Domain.User", "PrincipalInvestigator") .WithMany("PrincipalInvestigatorProjects") .HasForeignKey("PrincipalInvestigatorId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.HasOne("Harvest.Core.Domain.Quote", "Quote") .WithMany() .HasForeignKey("QuoteId1"); b.Navigation("CreatedBy"); b.Navigation("PrincipalInvestigator"); b.Navigation("Quote"); }); modelBuilder.Entity("Harvest.Core.Domain.ProjectHistory", b => { b.HasOne("Harvest.Core.Domain.Project", "Project") .WithMany() .HasForeignKey("ProjectId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.Navigation("Project"); }); modelBuilder.Entity("Harvest.Core.Domain.Quote", b => { b.HasOne("Harvest.Core.Domain.User", "ApprovedBy") .WithMany() .HasForeignKey("ApprovedById"); b.HasOne("Harvest.Core.Domain.Document", "CurrentDocument") .WithOne("Quote") .HasForeignKey("Harvest.Core.Domain.Quote", "CurrentDocumentId") .OnDelete(DeleteBehavior.Restrict); b.HasOne("Harvest.Core.Domain.User", "InitiatedBy") .WithMany() .HasForeignKey("InitiatedById") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("Harvest.Core.Domain.Project", "Project") .WithMany("Quotes") .HasForeignKey("ProjectId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.Navigation("ApprovedBy"); b.Navigation("CurrentDocument"); b.Navigation("InitiatedBy"); b.Navigation("Project"); }); modelBuilder.Entity("Harvest.Core.Domain.Rate", b => { b.HasOne("Harvest.Core.Domain.User", "CreatedBy") .WithMany("CreatedRates") .HasForeignKey("CreatedById") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.HasOne("Harvest.Core.Domain.User", "UpdatedBy") .WithMany("UpdatedRates") .HasForeignKey("UpdatedById") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.Navigation("CreatedBy"); b.Navigation("UpdatedBy"); }); modelBuilder.Entity("Harvest.Core.Domain.Transfer", b => { b.HasOne("Harvest.Core.Domain.Invoice", "Invoice") .WithMany("Transfers") .HasForeignKey("InvoiceId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.Navigation("Invoice"); }); modelBuilder.Entity("Harvest.Core.Domain.Document", b => { b.Navigation("Quote"); }); modelBuilder.Entity("Harvest.Core.Domain.Invoice", b => { b.Navigation("Expenses"); b.Navigation("Transfers"); }); modelBuilder.Entity("Harvest.Core.Domain.Project", b => { b.Navigation("Accounts"); b.Navigation("Quotes"); }); modelBuilder.Entity("Harvest.Core.Domain.Quote", b => { b.Navigation("Documents"); }); modelBuilder.Entity("Harvest.Core.Domain.User", b => { b.Navigation("CreatedProjects"); b.Navigation("CreatedRates"); b.Navigation("Permissions"); b.Navigation("PrincipalInvestigatorProjects"); b.Navigation("UpdatedRates"); }); #pragma warning restore 612, 618 } } }
34.472681
89
0.395429
[ "MIT" ]
ucdavis/Harvest
Harvest.Core/Migrations/Sqlite/20210420170842_updateAndRemoveTablesForSlothService.Designer.cs
27,132
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using BindingAttributes; using Disunity.Store.Data.Services; using Disunity.Store.Entities; using Disunity.Store.Entities.Factories; using Disunity.Store.Extensions; using Microsoft.AspNetCore.Hosting; using TopoSort; using Tracery; namespace Disunity.Store.Data.Seeds { [AsScoped(typeof(ISeeder))] [DependsOn(typeof(UnityVersionSeed))] public class TargetSeed : ISeeder { private readonly ApplicationDbContext _context; private readonly IHostingEnvironment _env; private readonly IVersionNumberFactory _versionNumberFactory; private readonly ISlugifier _slugifier; private readonly IconRandomizer _iconRandomizer; private readonly Unparser _unparser; public TargetSeed(ApplicationDbContext context, IHostingEnvironment env, IVersionNumberFactory versionNumberFactory, ISlugifier slugifier, Func<string, Unparser> unparserFactory, IconRandomizer iconRandomizer) { _context = context; _env = env; _versionNumberFactory = versionNumberFactory; _slugifier = slugifier; _iconRandomizer = iconRandomizer; _unparser = unparserFactory("Entities/target.json"); } public bool ShouldSeed() { return _env.IsDevelopment() && !_context.Targets.Any(); } public Task Seed() { var unity2018Min = _context.UnityVersions.FindExactVersion((VersionNumber) "2018.1.0").Single(); var unity2018Max = _context.UnityVersions.FindExactVersion((VersionNumber) "2018.4.4").Single(); for (var i = 0; i < 10; i++) { var displayName = _unparser.Generate("#display_name.title#"); var slug = _slugifier.Slugify(displayName); var iconUrl = _iconRandomizer.GetIconUrl(); var description = _unparser.Generate("#description#"); var targetVersion = new TargetVersion() { Description = description, Hash = $"0123456789abcdef-{i}", DisplayName = displayName, IconUrl = iconUrl, WebsiteUrl = "", VersionNumber = "1", DisunityCompatibility = new TargetVersionCompatibility() { MinCompatibleVersion = unity2018Min, MaxCompatibleVersion = unity2018Max } }; var target = new Target() { Slug = slug, Versions = new List<TargetVersion>() { targetVersion } }; _context.Targets.Add(target); } return _context.SaveChangesAsync(); } } }
33.119565
93
0.573351
[ "MIT" ]
disunity-hq/disunity
Disunity.Store/Shared/Data/Seeds/TargetSeed.cs
3,047
C#
// <copyright file="Benchmark2.cs" company="Endjin Limited"> // Copyright (c) Endjin Limited. All rights reserved. // </copyright> #pragma warning disable namespace ContainsDraft201909Feature.ContainsKeywordValidation { using System.Threading.Tasks; using BenchmarkDotNet.Attributes; using BenchmarkDotNet.Diagnosers; using Corvus.JsonSchema.Benchmarking.Benchmarks; /// <summary> /// Additional properties benchmark. /// </summary> [MemoryDiagnoser] public class Benchmark2 : BenchmarkBase { /// <summary> /// Global setup. /// </summary> /// <returns>A <see cref="Task"/> which completes once setup is complete.</returns> [GlobalSetup] public Task GlobalSetup() { return this.GlobalSetup("draft2019-09\\contains.json", "#/0/schema", "#/000/tests/002/data", true); } /// <summary> /// Validates using the Corvus types. /// </summary> [Benchmark] public void ValidateCorvus() { this.ValidateCorvusCore<ContainsDraft201909Feature.ContainsKeywordValidation.Schema>(); } /// <summary> /// Validates using the Newtonsoft types. /// </summary> [Benchmark] public void ValidateNewtonsoft() { this.ValidateNewtonsoftCore(); } } }
31.340909
111
0.611313
[ "Apache-2.0" ]
corvus-dotnet/Corvus.JsonSchema
Solutions/Corvus.JsonSchema.Benchmarking/201909/ContainsDraft201909/ContainsKeywordValidation/Benchmark2.cs
1,379
C#
// <auto-generated /> using System; using Fritz.ResourceManagement.Web.Models; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; namespace Fritz.ResourceManagement.Web.Migrations { [DbContext(typeof(MyDbContext))] [Migration("20190725143654_NewDatabase")] partial class NewDatabase { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "3.0.0-preview7.19362.6"); modelBuilder.Entity("Fritz.ResourceManagement.Domain.Person", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("GivenName"); b.Property<string>("MiddleName"); b.Property<string>("PhoneNumber"); b.Property<int>("ScheduleId"); b.Property<string>("SurName"); b.HasKey("Id"); b.HasIndex("ScheduleId"); b.ToTable("Persons"); }); modelBuilder.Entity("Fritz.ResourceManagement.Domain.PersonPersonType", b => { b.Property<int>("PersonId"); b.Property<int>("PersonTypeId"); b.HasKey("PersonId", "PersonTypeId"); b.HasIndex("PersonTypeId"); b.ToTable("PersonPersonType"); }); modelBuilder.Entity("Fritz.ResourceManagement.Domain.PersonType", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("Name"); b.HasKey("Id"); b.ToTable("PersonTypes"); }); modelBuilder.Entity("Fritz.ResourceManagement.Domain.RecurringSchedule", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("CronPattern"); b.Property<TimeSpan>("Duration"); b.Property<DateTime>("MaxEndDateTime"); b.Property<DateTime>("MinStartDateTime"); b.Property<string>("Name"); b.Property<int>("ScheduleId"); b.Property<int>("Status"); b.HasKey("Id"); b.HasIndex("ScheduleId"); b.ToTable("RecurringSchedule"); }); modelBuilder.Entity("Fritz.ResourceManagement.Domain.Schedule", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.HasKey("Id"); b.ToTable("Schedules"); }); modelBuilder.Entity("Fritz.ResourceManagement.Domain.ScheduleException", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("EndDateTime"); b.Property<string>("Name"); b.Property<int?>("ScheduleId"); b.Property<DateTime>("StartDateTime"); b.HasKey("Id"); b.HasIndex("ScheduleId"); b.ToTable("ScheduleException"); }); modelBuilder.Entity("Fritz.ResourceManagement.Domain.ScheduleItem", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("EndDateTime"); b.Property<string>("Name"); b.Property<int>("ScheduleId"); b.Property<DateTime>("StartDateTime"); b.Property<int>("Status"); b.HasKey("Id"); b.HasIndex("ScheduleId"); b.ToTable("ScheduleItem"); }); modelBuilder.Entity("Fritz.ResourceManagement.Domain.Person", b => { b.HasOne("Fritz.ResourceManagement.Domain.Schedule", "Schedule") .WithMany() .HasForeignKey("ScheduleId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Fritz.ResourceManagement.Domain.PersonPersonType", b => { b.HasOne("Fritz.ResourceManagement.Domain.Person", "Person") .WithMany("PersonPersonType") .HasForeignKey("PersonId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("Fritz.ResourceManagement.Domain.PersonType", "PersonType") .WithMany("PersonPersonTypes") .HasForeignKey("PersonTypeId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Fritz.ResourceManagement.Domain.RecurringSchedule", b => { b.HasOne("Fritz.ResourceManagement.Domain.Schedule", null) .WithMany("RecurringSchedules") .HasForeignKey("ScheduleId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Fritz.ResourceManagement.Domain.ScheduleException", b => { b.HasOne("Fritz.ResourceManagement.Domain.Schedule", null) .WithMany("ScheduleExceptions") .HasForeignKey("ScheduleId"); }); modelBuilder.Entity("Fritz.ResourceManagement.Domain.ScheduleItem", b => { b.HasOne("Fritz.ResourceManagement.Domain.Schedule", null) .WithMany("ScheduleItems") .HasForeignKey("ScheduleId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); #pragma warning restore 612, 618 } } }
32.90404
89
0.479355
[ "MIT" ]
FritzAndFriends/ResourceManagement
src/Fritz.ResourceManagement.Web/Migrations/20190725143654_NewDatabase.Designer.cs
6,517
C#
namespace SimpleAuth.Stores.Redis.AcceptanceTests.Features { using System; using System.IdentityModel.Tokens.Jwt; using Microsoft.IdentityModel.Tokens; using SimpleAuth.Client; using SimpleAuth.Shared; using SimpleAuth.Shared.Responses; using Xbehave; using Xunit; using Xunit.Abstractions; public class JwksFeature : AuthFlowFeature { /// <inheritdoc /> public JwksFeature(ITestOutputHelper output) : base(output) { } [Scenario] public void SuccessfulPermissionCreation() { string jwksJson = null!; "then can download json web key set".x( async () => { jwksJson = await _fixture.Client().GetStringAsync(BaseUrl + "/jwks").ConfigureAwait(false); Assert.NotNull(jwksJson); }); "and can create JWKS from json".x( () => { var jwks = new JsonWebKeySet(jwksJson); Assert.NotEmpty(jwks.Keys); }); } [Scenario] public void SuccessfulTokenValidationFromMetadata() { GrantedTokenResponse tokenResponse = null!; JsonWebKeySet jwks = null!; "And a valid token".x( async () => { var tokenClient = new TokenClient( TokenCredentials.FromClientCredentials("clientCredentials", "clientCredentials"), _fixture.Client, new Uri(WellKnownOpenidConfiguration)); var response = await tokenClient.GetToken(TokenRequest.FromScopes("api1")).ConfigureAwait(false) as Option<GrantedTokenResponse>.Result; Assert.NotNull(response); tokenResponse = response!.Item; }); "then can download json web key set".x( async () => { var jwksJson = await _fixture.Client().GetStringAsync(BaseUrl + "/jwks").ConfigureAwait(false); Assert.NotNull(jwksJson); jwks = JsonWebKeySet.Create(jwksJson); }); "Then can create token validation parameters from service metadata".x( () => { var validationParameters = new TokenValidationParameters { IssuerSigningKeys = jwks.Keys, ValidIssuer = "https://localhost", ValidAudience = "clientCredentials" }; var handler = new JwtSecurityTokenHandler(); handler.ValidateToken(tokenResponse.AccessToken, validationParameters, out var securityToken); Assert.NotNull(securityToken); }); } } }
32.223404
115
0.510069
[ "Apache-2.0" ]
jjrdk/SimpleAuth
tests/simpleauth.stores.redis.acceptancetests/Features/JwksFeature.cs
3,031
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.AwsNative.CloudFront { /// <summary> /// Resource Type definition for AWS::CloudFront::ResponseHeadersPolicy /// </summary> [AwsNativeResourceType("aws-native:cloudfront:ResponseHeadersPolicy")] public partial class ResponseHeadersPolicy : Pulumi.CustomResource { [Output("lastModifiedTime")] public Output<string> LastModifiedTime { get; private set; } = null!; [Output("responseHeadersPolicyConfig")] public Output<Outputs.ResponseHeadersPolicyConfig> ResponseHeadersPolicyConfig { get; private set; } = null!; /// <summary> /// Create a ResponseHeadersPolicy resource with the given unique name, arguments, and options. /// </summary> /// /// <param name="name">The unique name of the resource</param> /// <param name="args">The arguments used to populate this resource's properties</param> /// <param name="options">A bag of options that control this resource's behavior</param> public ResponseHeadersPolicy(string name, ResponseHeadersPolicyArgs args, CustomResourceOptions? options = null) : base("aws-native:cloudfront:ResponseHeadersPolicy", name, args ?? new ResponseHeadersPolicyArgs(), MakeResourceOptions(options, "")) { } private ResponseHeadersPolicy(string name, Input<string> id, CustomResourceOptions? options = null) : base("aws-native:cloudfront:ResponseHeadersPolicy", name, null, MakeResourceOptions(options, id)) { } private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id) { var defaultOptions = new CustomResourceOptions { Version = Utilities.Version, }; var merged = CustomResourceOptions.Merge(defaultOptions, options); // Override the ID if one was specified for consistency with other language SDKs. merged.Id = id ?? merged.Id; return merged; } /// <summary> /// Get an existing ResponseHeadersPolicy resource's state with the given name, ID, and optional extra /// properties used to qualify the lookup. /// </summary> /// /// <param name="name">The unique name of the resulting resource.</param> /// <param name="id">The unique provider ID of the resource to lookup.</param> /// <param name="options">A bag of options that control this resource's behavior</param> public static ResponseHeadersPolicy Get(string name, Input<string> id, CustomResourceOptions? options = null) { return new ResponseHeadersPolicy(name, id, options); } } public sealed class ResponseHeadersPolicyArgs : Pulumi.ResourceArgs { [Input("responseHeadersPolicyConfig", required: true)] public Input<Inputs.ResponseHeadersPolicyConfigArgs> ResponseHeadersPolicyConfig { get; set; } = null!; public ResponseHeadersPolicyArgs() { } } }
43.818182
146
0.666568
[ "Apache-2.0" ]
AaronFriel/pulumi-aws-native
sdk/dotnet/CloudFront/ResponseHeadersPolicy.cs
3,374
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the amplifybackend-2020-08-11.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.AmplifyBackend.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.AmplifyBackend.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for CreateBackendAuthForgotPasswordConfig Object /// </summary> public class CreateBackendAuthForgotPasswordConfigUnmarshaller : IUnmarshaller<CreateBackendAuthForgotPasswordConfig, XmlUnmarshallerContext>, IUnmarshaller<CreateBackendAuthForgotPasswordConfig, JsonUnmarshallerContext> { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> CreateBackendAuthForgotPasswordConfig IUnmarshaller<CreateBackendAuthForgotPasswordConfig, XmlUnmarshallerContext>.Unmarshall(XmlUnmarshallerContext context) { throw new NotImplementedException(); } /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public CreateBackendAuthForgotPasswordConfig Unmarshall(JsonUnmarshallerContext context) { context.Read(); if (context.CurrentTokenType == JsonToken.Null) return null; CreateBackendAuthForgotPasswordConfig unmarshalledObject = new CreateBackendAuthForgotPasswordConfig(); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { if (context.TestExpression("deliveryMethod", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.DeliveryMethod = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("emailSettings", targetDepth)) { var unmarshaller = EmailSettingsUnmarshaller.Instance; unmarshalledObject.EmailSettings = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("smsSettings", targetDepth)) { var unmarshaller = SmsSettingsUnmarshaller.Instance; unmarshalledObject.SmsSettings = unmarshaller.Unmarshall(context); continue; } } return unmarshalledObject; } private static CreateBackendAuthForgotPasswordConfigUnmarshaller _instance = new CreateBackendAuthForgotPasswordConfigUnmarshaller(); /// <summary> /// Gets the singleton. /// </summary> public static CreateBackendAuthForgotPasswordConfigUnmarshaller Instance { get { return _instance; } } } }
38.269231
224
0.651005
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/AmplifyBackend/Generated/Model/Internal/MarshallTransformations/CreateBackendAuthForgotPasswordConfigUnmarshaller.cs
3,980
C#
// Copyright (c) 2016-2020 Alexander Ong // See LICENSE in project root for license information. using System; using System.Collections; using System.Collections.Generic; using UnityEngine; namespace MoonscraperEngine.Input { [Serializable] public class JoystickMap : IInputMap, IEnumerable { static System.Text.StringBuilder sb = new System.Text.StringBuilder(); [Serializable] public struct ButtonConfig { public int buttonIndex; } [Serializable] public struct AxisConfig { public int axisIndex; public JoystickDevice.AxisDir dir; } [Serializable] public struct BallConfig { public int ballIndex; } [Serializable] public struct HatConfig { public int hatIndex; public JoystickDevice.HatPosition position; } [SerializeField] string deviceId; public List<ButtonConfig> buttons = new List<ButtonConfig>(); public List<AxisConfig> axes = new List<AxisConfig>(); public List<BallConfig> balls = new List<BallConfig>(); // ??? public List<HatConfig> hats = new List<HatConfig>(); public JoystickMap(string deviceId) { this.deviceId = deviceId; } public void Add(ButtonConfig button) { buttons.Add(button); } public void Add(IList<ButtonConfig> buttonConfigs) { buttons.AddRange(buttonConfigs); } public void Add(int axis, JoystickDevice.AxisDir dir) { axes.Add(new AxisConfig() { axisIndex = axis, dir = dir }); } public void Add(BallConfig ball) { balls.Add(ball); } public void Add(int hat, JoystickDevice.HatPosition position) { hats.Add(new HatConfig() { hatIndex = hat, position = position }); } public bool IsEmpty { get { return buttons.Count <= 0 && axes.Count <= 0 && balls.Count <= 0 && hats.Count <= 0; } } public IInputMap Clone() { JoystickMap clone = new JoystickMap(deviceId); clone.buttons.AddRange(buttons); clone.axes.AddRange(axes); clone.balls.AddRange(balls); clone.hats.AddRange(hats); return clone; } public string GetInputStr() { sb.Clear(); foreach (var index in buttons) { if (sb.Length > 0) sb.Append(" + "); sb.AppendFormat("Button {0}", index.buttonIndex); } foreach (var axis in axes) { if (sb.Length > 0) sb.Append(" + "); sb.AppendFormat("Axis {0}", axis.axisIndex); } foreach (var ball in balls) { if (sb.Length > 0) sb.Append(" + "); sb.AppendFormat("Ball {0}", ball); } foreach (var hat in hats) { if (sb.Length > 0) sb.Append(" + "); sb.AppendFormat("Hat {0} {1}", hat.hatIndex, hat.position.ToString()); } return sb.ToString(); } public bool HasConflict(IInputMap other, InputAction.Properties properties) { JoystickMap otherMap = other as JoystickMap; if (otherMap == null || otherMap.IsEmpty) return false; bool allowSameFrameMultiInput = properties.allowSameFrameMultiInput; if (allowSameFrameMultiInput) { if (buttons.Count > 0 && otherMap.buttons.Count > 0) { // Check if they match exactly, or if one map is a sub-set of the other var smallerButtonMap = buttons.Count < otherMap.buttons.Count ? buttons : otherMap.buttons; var largerButtonMap = buttons.Count < otherMap.buttons.Count ? otherMap.buttons : buttons; int sameInputCount = 0; foreach (var button in smallerButtonMap) { bool contains = false; foreach (var otherButton in largerButtonMap) { if (button.buttonIndex == otherButton.buttonIndex) { contains = true; break; } } if (contains) { ++sameInputCount; } } if (sameInputCount == smallerButtonMap.Count) { return true; } } } else { foreach (var button in buttons) { foreach (var otherButton in otherMap.buttons) { if (button.buttonIndex == otherButton.buttonIndex) return true; } } } foreach (var axis in axes) { foreach (var otherAxis in otherMap.axes) { if (axis.axisIndex == otherAxis.axisIndex && (axis.dir == otherAxis.dir || axis.dir == JoystickDevice.AxisDir.Any || otherAxis.dir == JoystickDevice.AxisDir.Any)) return true; } } foreach (var ballIndex in balls) { foreach (var otherBallIndex in otherMap.balls) { if (ballIndex.ballIndex == otherBallIndex.ballIndex) return true; } } foreach (var hat in hats) { foreach (var otherHat in otherMap.hats) { if (hat.hatIndex == otherHat.hatIndex && hat.position == otherHat.position) return true; } } return false; } public void SetEmpty() { buttons.Clear(); axes.Clear(); balls.Clear(); hats.Clear(); } public bool SetFrom(IInputMap that) { JoystickMap jsCast = that as JoystickMap; if (jsCast == null) { Debug.LogError("Type incompatibility when trying to call SetFrom on a joystick input map"); return false; } SetEmpty(); buttons.AddRange(jsCast.buttons); axes.AddRange(jsCast.axes); balls.AddRange(jsCast.balls); hats.AddRange(jsCast.hats); return true; } public IEnumerator GetEnumerator() { foreach (var button in buttons) { yield return button; } foreach (var axis in axes) { yield return axis; } foreach (var ball in balls) { yield return ball; } foreach (var hat in hats) { yield return hat; } } public bool IsCompatibleWithDevice(IInputDevice device) { if (device.Type == DeviceType.Joystick) { var jsDevice = device as JoystickDevice; return jsDevice.deviceId == deviceId; } return false; } } }
28.87108
183
0.44014
[ "BSD-3-Clause" ]
Mario64iscool2/Moonscraper-Chart-Editor
Moonscraper Chart Editor/Assets/Scripts/Engine/Input/JoystickMap.cs
8,288
C#
namespace Secucard.Connect.DemoApp._02_client_payments { using System; using Product.Payment.Model; using System.IO; using Secucard.Connect.Product.Document.Model; public class Create_Secupay_Payout_Transaction { public SecupayPayout Run(SecucardConnect client, Customer customer, Container container) { Console.WriteLine(Environment.NewLine + "### Create secupay payout transaction sample ### " + Environment.NewLine); var service = client.Payment.Secupaypayout; var payout = new SecupayPayout(); payout.Amount = 300; // Amount in cents (or in the smallest unit of the given currency) payout.Currency = "EUR"; // The ISO-4217 code of the currency payout.Purpose = "Payout Test #3"; payout.OrderId = "12345"; // The shop order id payout.Customer = customer.Id; payout.RedirectUrl = new RedirectUrl { }; payout.TransactionList = new TransactionList[3]; // We want to store two items // if you want to create payout payment for a cloned contract (contract that you created by cloning main contract), // otherwise it will be assinged to the plattform contract, add the follwing line: // payout.Contract = "PCR_XXXX"; // Sample for create a payout based on a payment instrument of the completed investment var item1 = new TransactionList(); item1.ItemType = TransactionList.ItemTypeTransactionPayout; item1.ReferenceId = "123.1"; item1.Name = "Payout Purpose 1"; item1.TransactionHash = "ckaidxxxfskc1176505"; // you can use TransactionHash or TransactionId, if you transmit both only TransactionId will be used. item1.Total = 100; payout.TransactionList[0] = item1; // Sample for create a payout based on a completed investment with a new bank account var item2 = new TransactionList(); item2.ItemType = TransactionList.ItemTypeTransactionPayout; item2.ReferenceId = "123.2"; item2.Name = "Payout Purpose 2"; item2.TransactionId = "PCI_WR67G325XTG2R45JJDNBG048PW4BN4"; // you can use TransactionHash or TransactionId, if you transmit both only TransactionId will be used. item2.ContainerId = container.Id; // f.e. "PCT_E4Z8U4W4J2N7MFV270ZAVWZFNJYHA3"; item2.Total = 100; payout.TransactionList[1] = item2; // Sample for create a payout with a new bank account (and investor / payment customer) var item3 = new TransactionList(); item3.ItemType = TransactionList.ItemTypeTransactionPayout; item3.ReferenceId = "123.3"; item3.Name = "Payout Purpose 3"; item3.ContainerId = container.Id; // f.e. "PCT_E4Z8U4W4J2N7MFV270ZAVWZFNJYHA3"; item3.Total = 100; payout.TransactionList[2] = item3; try { payout = service.Create(payout); } catch (Exception ex) { Console.WriteLine($"Error message: {ex.Message}"); } if (!string.IsNullOrEmpty(payout.Id)) { Console.WriteLine($"Created secupay payout transaction with id: {payout.Id}"); Console.WriteLine($"Payout data: {payout.ToString()}"); } else { Console.WriteLine("Payout creation failed"); } return null; } } }
45.4875
174
0.605386
[ "Apache-2.0" ]
secucard/secucard-connect-net-sdk-demo
app/Secucard.Connect.DemoApp/02_client_payments/Create_Secupay_Payout_Transaction.cs
3,641
C#
using Gum.DataTypes; using Gum.Managers; using Gum.Wireframe; using Microsoft.Xna.Framework.Graphics; using RenderingLibrary; using RenderingLibrary.Content; using RenderingLibrary.Graphics; using RenderingLibrary.Math.Geometry; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace GumRuntime { public static class InstanceSaveExtensionMethods { public static GraphicalUiElement ToGraphicalUiElement(this InstanceSave instanceSave, SystemManagers systemManagers) { ElementSave instanceElement = ObjectFinder.Self.GetElementSave(instanceSave.BaseType); GraphicalUiElement toReturn = null; if (instanceElement != null) { toReturn = ElementSaveExtensions.CreateGueForElement(instanceElement, true); // If we get here but there's no contained graphical object then that means we don't // have a strongly-typed system (like when a game is running in FRB). Therefore, we'll // just fall back to the regular creation of graphical objects, like is done in the Gum tool: if(toReturn.RenderableComponent == null) { instanceElement.SetGraphicalUiElement(toReturn, systemManagers); } toReturn.Name = instanceSave.Name; toReturn.Tag = instanceSave; var state = instanceSave.ParentContainer.DefaultState; foreach (var variable in state.Variables.Where(item => item.SetsValue && item.SourceObject == instanceSave.Name)) { string propertyOnInstance = variable.Name.Substring(variable.Name.LastIndexOf('.') + 1); if (toReturn.IsExposedVariable(propertyOnInstance)) { toReturn.SetProperty(propertyOnInstance, variable.Value); } } } return toReturn; } internal static bool TryHandleAsBaseType(string baseType, SystemManagers systemManagers, out IRenderable containedObject) { bool handledAsBaseType = true; containedObject = null; switch (baseType) { case "Container": if(GraphicalUiElement.ShowLineRectangles) { LineRectangle lineRectangle = new LineRectangle(systemManagers); containedObject = lineRectangle; } else { containedObject = new InvisibleRenderable(); } break; case "Rectangle": LineRectangle rectangle = new LineRectangle(systemManagers); rectangle.IsDotted = false; containedObject = rectangle; break; case "Circle": LineCircle circle = new LineCircle(systemManagers); circle.CircleOrigin = CircleOrigin.TopLeft; containedObject = circle; break; case "Polygon": LinePolygon polygon = new LinePolygon(systemManagers); containedObject = polygon; break; case "ColoredRectangle": SolidRectangle solidRectangle = new SolidRectangle(); containedObject = solidRectangle; break; case "Sprite": Texture2D texture = null; Sprite sprite = new Sprite(texture); containedObject = sprite; break; case "NineSlice": { NineSlice nineSlice = new NineSlice(); containedObject = nineSlice; } break; case "Text": { Text text = new Text(systemManagers, ""); containedObject = text; } break; default: handledAsBaseType = false; break; } return handledAsBaseType; } private static void SetAlphaAndColorValues(SolidRectangle solidRectangle, RecursiveVariableFinder rvf) { solidRectangle.Color = ColorFromRvf(rvf); } private static void SetAlphaAndColorValues(Sprite sprite, RecursiveVariableFinder rvf) { sprite.Color = ColorFromRvf(rvf); } private static void SetAlphaAndColorValues(NineSlice nineSlice, RecursiveVariableFinder rvf) { nineSlice.Color = ColorFromRvf(rvf); } private static void SetAlphaAndColorValues(Text text, RecursiveVariableFinder rvf) { Microsoft.Xna.Framework.Color color = ColorFromRvf(rvf); text.Red = color.R; text.Green = color.G; text.Blue = color.B; text.Alpha = color.A; //Is alpha supported? } static Microsoft.Xna.Framework.Color ColorFromRvf(RecursiveVariableFinder rvf) { Microsoft.Xna.Framework.Color color = new Microsoft.Xna.Framework.Color( rvf.GetValue<int>("Red"), rvf.GetValue<int>("Green"), rvf.GetValue<int>("Blue"), rvf.GetValue<int>("Alpha") ); return color; } private static void SetAlignmentValues(Text text, RecursiveVariableFinder rvf) { //Could these potentially be out of bounds? text.HorizontalAlignment = rvf.GetValue<HorizontalAlignment>("HorizontalAlignment"); text.VerticalAlignment = rvf.GetValue<VerticalAlignment>("VerticalAlignment"); } } }
35.298246
129
0.548376
[ "MIT" ]
gitter-badger/Gum
GumRuntime/InstanceSaveExtensionMethods.GumRuntime.cs
6,038
C#
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using Lucene.Net.Index; using IndexReader = Lucene.Net.Index.IndexReader; namespace Lucene.Net.Search { /// <summary> A query that wraps a filter and simply returns a constant score equal to the /// query boost for every document in the filter. /// </summary> //[Serializable] //Disabled for https://github.com/dotnet/standard/issues/300 public class ConstantScoreQuery:Query { protected internal Filter internalFilter; public ConstantScoreQuery(Filter filter) { this.internalFilter = filter; } /// <summary>Returns the encapsulated filter </summary> public virtual Filter Filter { get { return internalFilter; } } public override Query Rewrite(IndexReader reader) { return this; } public override void ExtractTerms(System.Collections.Generic.ISet<Term> terms) { // OK to not add any terms when used for MultiSearcher, // but may not be OK for highlighting } //[Serializable] //Disabled for https://github.com/dotnet/standard/issues/300 protected internal class ConstantWeight:Weight { private void InitBlock(ConstantScoreQuery enclosingInstance) { this.enclosingInstance = enclosingInstance; } private ConstantScoreQuery enclosingInstance; public ConstantScoreQuery Enclosing_Instance { get { return enclosingInstance; } } private readonly Similarity similarity; private float queryNorm; private float queryWeight; public ConstantWeight(ConstantScoreQuery enclosingInstance, Searcher searcher) { InitBlock(enclosingInstance); this.similarity = Enclosing_Instance.GetSimilarity(searcher); } public override Query Query { get { return Enclosing_Instance; } } public override float Value { get { return queryWeight; } } public override float GetSumOfSquaredWeights() { queryWeight = Enclosing_Instance.Boost; return queryWeight*queryWeight; } public override void Normalize(float norm) { this.queryNorm = norm; queryWeight *= this.queryNorm; } public override Scorer Scorer(IndexReader reader, bool scoreDocsInOrder, bool topScorer) { return new ConstantScorer(enclosingInstance, similarity, reader, this); } public override Explanation Explain(IndexReader reader, int doc) { var cs = new ConstantScorer(enclosingInstance, similarity, reader, this); bool exists = cs.docIdSetIterator.Advance(doc) == doc; var result = new ComplexExplanation(); if (exists) { result.Description = "ConstantScoreQuery(" + Enclosing_Instance.internalFilter + "), product of:"; result.Value = queryWeight; System.Boolean tempAux = true; result.Match = tempAux; result.AddDetail(new Explanation(Enclosing_Instance.Boost, "boost")); result.AddDetail(new Explanation(queryNorm, "queryNorm")); } else { result.Description = "ConstantScoreQuery(" + Enclosing_Instance.internalFilter + ") doesn't match id " + doc; result.Value = 0; System.Boolean tempAux2 = false; result.Match = tempAux2; } return result; } } protected internal class ConstantScorer : Scorer { private void InitBlock(ConstantScoreQuery enclosingInstance) { this.enclosingInstance = enclosingInstance; } private ConstantScoreQuery enclosingInstance; public ConstantScoreQuery Enclosing_Instance { get { return enclosingInstance; } } internal DocIdSetIterator docIdSetIterator; internal float theScore; internal int doc = - 1; public ConstantScorer(ConstantScoreQuery enclosingInstance, Similarity similarity, IndexReader reader, Weight w):base(similarity) { InitBlock(enclosingInstance); theScore = w.Value; DocIdSet docIdSet = Enclosing_Instance.internalFilter.GetDocIdSet(reader); if (docIdSet == null) { docIdSetIterator = DocIdSet.EMPTY_DOCIDSET.Iterator(); } else { DocIdSetIterator iter = docIdSet.Iterator(); if (iter == null) { docIdSetIterator = DocIdSet.EMPTY_DOCIDSET.Iterator(); } else { docIdSetIterator = iter; } } } public override int NextDoc() { return docIdSetIterator.NextDoc(); } public override int DocID() { return docIdSetIterator.DocID(); } public override float Score() { return theScore; } public override int Advance(int target) { return docIdSetIterator.Advance(target); } } public override Weight CreateWeight(Searcher searcher) { return new ConstantScoreQuery.ConstantWeight(this, searcher); } /// <summary>Prints a user-readable version of this query. </summary> public override System.String ToString(string field) { return "ConstantScore(" + internalFilter + (Boost == 1.0?")":"^" + Boost); } /// <summary>Returns true if <c>o</c> is equal to this. </summary> public override bool Equals(System.Object o) { if (this == o) return true; if (!(o is ConstantScoreQuery)) return false; ConstantScoreQuery other = (ConstantScoreQuery) o; return this.Boost == other.Boost && internalFilter.Equals(other.internalFilter); } /// <summary>Returns a hash code value for this object. </summary> public override int GetHashCode() { // Simple add is OK since no existing filter hashcode has a float component. return internalFilter.GetHashCode() + BitConverter.ToInt32(BitConverter.GetBytes(Boost), 0); } override public System.Object Clone() { // {{Aroush-1.9}} is this all that we need to clone?! ConstantScoreQuery clone = (ConstantScoreQuery)base.Clone(); clone.internalFilter = (Filter)this.internalFilter; return clone; } } }
29.411017
133
0.664313
[ "Apache-2.0" ]
Anomalous-Software/Lucene.NET
src/core/Search/ConstantScoreQuery.cs
6,941
C#
using Newtonsoft.Json; using Serilog; using System; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using EO59.Api.Demo.Models; using EO59.Api.Demo.Services; namespace EO59.Api.Demo { /// <summary> /// This is a demo class to show data retrieval workflow for EO59 API /// </summary> public class ApiReaderService { /// <summary> /// Logger instance /// </summary> private readonly ILogger _logger; /// <summary> /// Static definition of API base URL /// </summary> private const string ApiBase = "https://api.eo59.com/api/"; /// <summary> /// Variable to store file system root directory location /// </summary> private readonly string _basePath; /// <summary> /// Size of data page to be downloaded, supported sizes are from 1 to /// 10000, currently using recommended default of 5000 /// </summary> private const int DownloadPageSize = 5000; /// <summary> /// Default constructor /// </summary> /// <param name="logger">Pass instance of <see cref="Serilog"/> logger</param> /// <param name="basePath">Pass variable containing file system root where /// data will be stored.</param> public ApiReaderService(ILogger logger, string basePath) { _logger = logger; _basePath = basePath; } /// <summary> /// Main workflow entry point /// </summary> /// <param name="subscription">Pass here valid subscription key</param> /// <param name="name">Pass here name for subscription, will be used to store cached file.</param> /// <returns></returns> public async Task DoWork(string subscription, string name) { _logger.Information("Checking API subscription {Name}", name); // Define main place holder for subscription information block from API. SubscriptionModel sub; try { // Download subscription information from API sub = JsonConvert.DeserializeObject<SubscriptionModel>( await ApiRequestClient.GetString($"{ApiBase}Subscriptions?subscription={subscription}")); } catch (Exception e) { _logger.Fatal(e, "Error while reading subscription for {Name}", name); return; } // Check if subscription is missing. if (sub == null) { _logger.Error("Subscription for {Name} is empty, check key value", name); return; } // Check if subscription has any data sets. if (sub.DataSets == null || sub.DataSets.Count == 0) { _logger.Warning("Subscription {Name} has no data sets, exiting", name); return; } // Check cached json to check if subscription has new data. if (!await NeedToProcessDataSet(name, sub)) { _logger.Information("No changes in data for {Name}, exiting", name); return; } // Start processing subscription data. _logger.Information("Loaded subscription {Name} data, will process {NumOfSets} data sets", name, sub.DataSets.Count); // Loop through all data sets on the subscription. foreach (var dataSet in sub.DataSets) { var fileName = Path.Combine(_basePath, $"{dataSet.DataSourceKey}.json"); await DownloadDataSet(subscription, dataSet.DataSourceKey, dataSet.NumberOfPoints, fileName); } // Replace or save subscription block from API to cached file, this will be used to check if there // are any updates in future requests. try { await File.WriteAllTextAsync(GetSubscriptionCachedFileName(name), JsonConvert.SerializeObject(sub)); } catch (Exception e) { _logger.Error(e, "Writing subscription cache file caused exception"); } _logger.Information("Completed all tasks, exiting"); } /// <summary> /// Method to compare cached copy of subscription block to new data. /// </summary> /// <param name="name"></param> /// <param name="newData"></param> /// <returns></returns> private async Task<bool> NeedToProcessDataSet(string name, SubscriptionModel newData) { // build cache file name var cacheFileName = GetSubscriptionCachedFileName(name); // check if file exists, if not, signal need for processing. if (!File.Exists(cacheFileName)) return true; // load cached file into memory var cached = JsonConvert.DeserializeObject<SubscriptionModel>( await File.ReadAllTextAsync(cacheFileName) ); // cached file sanity check if (cached != null && cached.DataSets.Count < newData.DataSets.Count) return true; // check if any update dates have changed since last download return cached != null && (from dataSet in cached.DataSets let toCheck = newData.DataSets .FirstOrDefault(x => x.DataSourceKey == dataSet.DataSourceKey) where toCheck != null where DateTimeOffset.Compare(dataSet.LastUpdate, toCheck.LastUpdate) != 0 select dataSet).Any(); } /// <summary> /// Convert name into subscription cache file name. /// </summary> /// <param name="name">Name of subscription</param> /// <returns>File system reference to subscription cache file</returns> private string GetSubscriptionCachedFileName(string name) { return Path.Combine(_basePath, $"{name}.json"); } /// <summary> /// Download and save data set into JSON text file. /// Please note: /// This is simplistic text processing approach that does not include JSON validation /// When creating a tool that will later convert or move data to another format, please change the method /// to use DTO conversion and validate data context. /// </summary> /// <param name="subscription">Subscription key</param> /// <param name="key">Data set key</param> /// <param name="rows">How many rows data set has</param> /// <param name="fileName">File name where json will be saved</param> /// <returns></returns> private async Task DownloadDataSet(string subscription, int key, int rows, string fileName) { _logger.Information("Downloading data set {Id} to {File}", key, fileName); // Set remaining rows count var remaining = rows; // Set start of download page, we load from 0 var skip = 0; // We will collect JSON strings into string builder, this is simplistic approach and we do not validate data. var data = new StringBuilder(); // Since saved json will contain array of points, append start of array. data.Append('['); // Loop to page through data segments. while (remaining > 0) { _logger.Information("Remaining rows: {Rows}", remaining); // build API request url var url = $"{ApiBase}Data?subscription={subscription}&key={key}&numberOfItems={DownloadPageSize}&skip={skip}"; // shift loop variables remaining -= DownloadPageSize; skip += DownloadPageSize; // read json var json = await ApiRequestClient.GetString(url); // Check if response has any data if (string.IsNullOrWhiteSpace(json)) { _logger.Warning("Reading data at point {Skip} returned empty result, ignoring", skip); continue; } // Small sanity check to make sure response is array like thing. if (!json.Contains("[") || !json.Contains("]")) continue; // returned json is list, remove list symbols to convert them into block, then append json = json.Remove(json.IndexOf('['), 1); json = json.Remove(json.LastIndexOf(']'), 1); data.AppendLine(json); if (remaining > 0) { data.Append(','); } } // append array closing symbol. data.Append(']'); // write string builder memory stream into final string. var finalJson = data.ToString(); // check if json ends in a way that will cause error if (finalJson.EndsWith(",]")) { // remove trailing , finalJson = finalJson.Remove(finalJson.LastIndexOf(','), 1); } // write json to file await File.WriteAllTextAsync(fileName, finalJson); _logger.Information("Completed saving {File}", fileName); } } }
43.231818
126
0.559563
[ "MIT" ]
EO59-LLc/api-demo
ApiReaderService.cs
9,513
C#
// Copyright (c) Quarrel. All rights reserved. using System; using DiscordAPI.Models; using DiscordAPI.Voice; using DiscordAPI.Voice.DownstreamEvents; using GalaSoft.MvvmLight.Ioc; using GalaSoft.MvvmLight.Messaging; using Quarrel.ViewModels.Messages.Gateway; using Quarrel.ViewModels.Messages.Voice; using Quarrel.ViewModels.Models.Bindables.Channels; using Quarrel.ViewModels.Services.Discord.Channels; using Quarrel.ViewModels.Services.Discord.Rest; using Quarrel.ViewModels.Services.DispatcherHelper; using Quarrel.ViewModels.Services.Gateway; using System.Collections.Concurrent; using System.Collections.Generic; using System.Threading.Tasks; using Windows.ApplicationModel.AppService; using Windows.Foundation.Collections; using Newtonsoft.Json; using Quarrel.ViewModels.Messages.Services.Settings; using Quarrel.ViewModels.Services.Settings; namespace Quarrel.ViewModels.Services.Voice { /// <summary> /// Manages all voice state data. /// </summary> public sealed class VoiceService : IVoiceService { private readonly IChannelsService _channelsService; private readonly IDiscordService _discordService; private readonly IDispatcherHelper _dispatcherHelper; private readonly IGatewayService _gatewayService; private readonly IWebrtcManager _webrtcManager; private readonly ISettingsService _settingsService; private AppServiceConnection _serviceConnection; /// <summary> /// Initializes a new instance of the <see cref="VoiceService"/> class. /// </summary> /// <param name="channelsService">The app's channel service.</param> /// <param name="discordService">The app's discord service.</param> /// <param name="dispatcherHelper">The app's dispatcher helper.</param> /// <param name="gatewayService">The app's gateway service.</param> /// <param name="webrtcManager">The app's webrtc manager.</param> public VoiceService( IChannelsService channelsService, IDiscordService discordService, IDispatcherHelper dispatcherHelper, IGatewayService gatewayService, ISettingsService settingsService) { _channelsService = channelsService; _discordService = discordService; _dispatcherHelper = dispatcherHelper; _gatewayService = gatewayService; _settingsService = settingsService; _ = CreateAppService(); Messenger.Default.Register<GatewayVoiceStateUpdateMessage>(this, m => { _dispatcherHelper.CheckBeginInvokeOnUi(() => { if (VoiceStates.ContainsKey(m.VoiceState.UserId)) { var oldChannel = _channelsService.GetChannel(VoiceStates[m.VoiceState.UserId].ChannelId); oldChannel?.ConnectedUsers.Remove(m.VoiceState.UserId); if (m.VoiceState.ChannelId == null) { if (m.VoiceState.UserId == _discordService.CurrentUser.Id) { DisconnectFromVoiceChannel(); } else { VoiceStates.Remove(m.VoiceState.UserId); } } else { VoiceStates[m.VoiceState.UserId] = m.VoiceState; } } else { VoiceStates[m.VoiceState.UserId] = m.VoiceState; } }); }); Messenger.Default.Register<GatewayVoiceServerUpdateMessage>(this, m => { if (!VoiceStates.ContainsKey(_discordService.CurrentUser.Id)) { VoiceStates.Add( _discordService.CurrentUser.Id, new VoiceState() { ChannelId = m.VoiceServer.ChannelId, GuildId = m.VoiceServer.GuildId, UserId = _discordService.CurrentUser.Id, }); } ConnectToVoiceChannel(m.VoiceServer, VoiceStates[_discordService.CurrentUser.Id]); }); Messenger.Default.Register<SettingChangedMessage<string>>(this, async (m) => { // Todo: this switch (m.Key) { case SettingKeys.InputDevice: SetInputDevice(m.Value); break; case SettingKeys.OutputDevice: SetOutputDevice(m.Value); break; } }); } /// <inheritdoc/> public IDictionary<string, VoiceState> VoiceStates { get; } = new ConcurrentDictionary<string, VoiceState>(); /// <inheritdoc/> public async void ToggleDeafen() { var state = VoiceStates[_discordService.CurrentUser.Id]; state.SelfDeaf = !state.SelfDeaf; var message = new ValueSet { ["type"] = "voiceStateUpdate", ["state"] = JsonConvert.SerializeObject(state), }; AppServiceResponse response = await SendServiceMessage(message); await _gatewayService.Gateway.VoiceStatusUpdate(state.GuildId, state.ChannelId, state.SelfMute, state.SelfDeaf); } /// <inheritdoc/> public async void ToggleMute() { var state = VoiceStates[_discordService.CurrentUser.Id]; state.SelfMute = !state.SelfMute; var message = new ValueSet { ["type"] = "voiceStateUpdate", ["state"] = JsonConvert.SerializeObject(state), }; AppServiceResponse response = await SendServiceMessage(message); await _gatewayService.Gateway.VoiceStatusUpdate(state.GuildId, state.ChannelId, state.SelfMute, state.SelfDeaf); } public event EventHandler<IList<float>> AudioInData; public event EventHandler<IList<float>> AudioOutData; private void SetInputDevice(string id) { Task.Run(async() => { var message = new ValueSet { ["type"] = "inputDevice", ["id"] = id, }; AppServiceResponse response = await SendServiceMessage(message); }); } private void SetOutputDevice(string id) { Task.Run(async () => { var message = new ValueSet { ["type"] = "outputDevice", ["id"] = id, }; AppServiceResponse response = await SendServiceMessage(message); }); } private async void ConnectToVoiceChannel(VoiceServerUpdate data, VoiceState state) { var message = new ValueSet { ["type"] = "connect", ["config"] = JsonConvert.SerializeObject(data), ["state"] = JsonConvert.SerializeObject(state), ["inputId"] = _settingsService.Roaming.GetValue<string>(SettingKeys.InputDevice), ["outputId"] = _settingsService.Roaming.GetValue<string>(SettingKeys.OutputDevice), }; AppServiceResponse response = await SendServiceMessage(message); } private async Task<bool> CreateAppService() { _serviceConnection = new AppServiceConnection { AppServiceName = "com.Quarrel.voip", PackageFamilyName = Windows.ApplicationModel.Package.Current.Id.FamilyName, }; var status = await _serviceConnection.OpenAsync(); _serviceConnection.RequestReceived += OnRequestReceived; _serviceConnection.ServiceClosed += OnServiceClosed; return status == AppServiceConnectionStatus.Success; } private void OnServiceClosed(AppServiceConnection sender, AppServiceClosedEventArgs args) { _serviceConnection = null; } private async void OnRequestReceived(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args) { AppServiceDeferral deferral = args.GetDeferral(); ValueSet message = args.Request.Message; if (message == null || !message.ContainsKey("type")) { return; } switch (message["type"]) { case "speaking": Speak speak = JsonConvert.DeserializeObject<Speak>(message["payload"] as string); Messenger.Default.Send(new SpeakMessage(speak)); break; case "audioInData": AudioInData?.Invoke(this, message["data"] as float[]); break; case "audioOutData": AudioOutData?.Invoke(this, message["data"] as float[]); break; } deferral.Complete(); } private async void DisconnectFromVoiceChannel() { var message = new ValueSet { ["type"] = "disconnect", }; AppServiceResponse response = await SendServiceMessage(message); } private async Task<AppServiceResponse> SendServiceMessage(ValueSet message) { if (_serviceConnection == null) { if (!await CreateAppService()) { return null; } } return await _serviceConnection.SendMessageAsync(message); } } }
37.164835
124
0.549773
[ "Apache-2.0" ]
UWPCommunity/Quarrel
src/Quarrel/Services/Voice/VoiceService.cs
10,148
C#
// ------------------------------------------------------------------------------ // <auto-generated> // This code was generated by SpecFlow (http://www.specflow.org/). // SpecFlow Version:1.8.1.0 // SpecFlow Generator Version:1.8.0.0 // Runtime Version:4.0.30319.269 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> // ------------------------------------------------------------------------------ #region Designer generated code #pragma warning disable namespace Conference.Specflow.Features.UserInterface.Views.Registration { using TechTalk.SpecFlow; [System.CodeDom.Compiler.GeneratedCodeAttribute("TechTalk.SpecFlow", "1.8.1.0")] [System.Runtime.CompilerServices.CompilerGeneratedAttribute()] public partial class SelfRegistrantEndToEndScenarioForMakingARegistrationForAConferenceSiteHappyPathFeature : Xunit.IUseFixture<SelfRegistrantEndToEndScenarioForMakingARegistrationForAConferenceSiteHappyPathFeature.FixtureData>, System.IDisposable { private static TechTalk.SpecFlow.ITestRunner testRunner; #line 1 "SelfRegistrationEndToEndHappy.feature" #line hidden public SelfRegistrantEndToEndScenarioForMakingARegistrationForAConferenceSiteHappyPathFeature() { this.TestInitialize(); } public static void FeatureSetup() { testRunner = TechTalk.SpecFlow.TestRunnerManager.GetTestRunner(); TechTalk.SpecFlow.FeatureInfo featureInfo = new TechTalk.SpecFlow.FeatureInfo(new System.Globalization.CultureInfo("en-US"), "Self Registrant end to end scenario for making a Registration for a Conference si" + "te (happy path)", "In order to register for a conference\r\nAs an Attendee\r\nI want to be able to regis" + "ter for the conference, pay for the Registration Order and associate myself with" + " the paid Order automatically", ProgrammingLanguage.CSharp, ((string[])(null))); testRunner.OnFeatureStart(featureInfo); } public static void FeatureTearDown() { testRunner.OnFeatureEnd(); testRunner = null; } public virtual void TestInitialize() { } public virtual void ScenarioTearDown() { testRunner.OnScenarioEnd(); } public virtual void ScenarioSetup(TechTalk.SpecFlow.ScenarioInfo scenarioInfo) { testRunner.OnScenarioStart(scenarioInfo); } public virtual void ScenarioCleanup() { testRunner.CollectScenarioErrors(); } public virtual void FeatureBackground() { #line 19 #line hidden TechTalk.SpecFlow.Table table1 = new TechTalk.SpecFlow.Table(new string[] { "seat type", "rate", "quota"}); table1.AddRow(new string[] { "General admission", "$199", "100"}); table1.AddRow(new string[] { "CQRS Workshop", "$500", "100"}); table1.AddRow(new string[] { "Additional cocktail party", "$50", "100"}); #line 20 testRunner.Given("the list of the available Order Items for the CQRS summit 2012 conference", ((string)(null)), table1); #line hidden TechTalk.SpecFlow.Table table2 = new TechTalk.SpecFlow.Table(new string[] { "seat type", "quantity"}); table2.AddRow(new string[] { "General admission", "1"}); table2.AddRow(new string[] { "Additional cocktail party", "1"}); #line 25 testRunner.And("the selected Order Items", ((string)(null)), table2); #line hidden } public virtual void SetFixture(SelfRegistrantEndToEndScenarioForMakingARegistrationForAConferenceSiteHappyPathFeature.FixtureData fixtureData) { } void System.IDisposable.Dispose() { this.ScenarioTearDown(); } [Xunit.FactAttribute()] [Xunit.TraitAttribute("FeatureTitle", "Self Registrant end to end scenario for making a Registration for a Conference si" + "te (happy path)")] [Xunit.TraitAttribute("Description", "Make a reservation with the selected Order Items")] public virtual void MakeAReservationWithTheSelectedOrderItems() { TechTalk.SpecFlow.ScenarioInfo scenarioInfo = new TechTalk.SpecFlow.ScenarioInfo("Make a reservation with the selected Order Items", ((string[])(null))); #line 31 this.ScenarioSetup(scenarioInfo); #line 19 this.FeatureBackground(); #line 32 testRunner.When("the Registrant proceeds to make the Reservation"); #line 33 testRunner.Then("the Reservation is confirmed for all the selected Order Items"); #line hidden TechTalk.SpecFlow.Table table3 = new TechTalk.SpecFlow.Table(new string[] { "seat type", "quantity"}); table3.AddRow(new string[] { "General admission", "1"}); table3.AddRow(new string[] { "Additional cocktail party", "1"}); #line 34 testRunner.And("these Order Items should be reserved", ((string)(null)), table3); #line hidden TechTalk.SpecFlow.Table table4 = new TechTalk.SpecFlow.Table(new string[] { "seat type"}); table4.AddRow(new string[] { "CQRS Workshop"}); #line 38 testRunner.And("these Order Items should not be reserved", ((string)(null)), table4); #line 41 testRunner.And("the total should read $249"); #line 42 testRunner.And("the countdown is started"); #line hidden this.ScenarioCleanup(); } [Xunit.FactAttribute()] [Xunit.TraitAttribute("FeatureTitle", "Self Registrant end to end scenario for making a Registration for a Conference si" + "te (happy path)")] [Xunit.TraitAttribute("Description", "Checkout:Registrant Details")] public virtual void CheckoutRegistrantDetails() { TechTalk.SpecFlow.ScenarioInfo scenarioInfo = new TechTalk.SpecFlow.ScenarioInfo("Checkout:Registrant Details", ((string[])(null))); #line 45 this.ScenarioSetup(scenarioInfo); #line 19 this.FeatureBackground(); #line 46 testRunner.Given("the Registrant proceeds to make the Reservation"); #line hidden TechTalk.SpecFlow.Table table5 = new TechTalk.SpecFlow.Table(new string[] { "first name", "last name", "email address"}); table5.AddRow(new string[] { "William", "Flash", "william@fabrikam.com"}); #line 47 testRunner.And("the Registrant enters these details", ((string)(null)), table5); #line 50 testRunner.When("the Registrant proceeds to Checkout:Payment"); #line 51 testRunner.Then("the payment options should be offered for a total of $249"); #line hidden this.ScenarioCleanup(); } [Xunit.FactAttribute()] [Xunit.TraitAttribute("FeatureTitle", "Self Registrant end to end scenario for making a Registration for a Conference si" + "te (happy path)")] [Xunit.TraitAttribute("Description", "Checkout:Payment and sucessfull Order completed")] public virtual void CheckoutPaymentAndSucessfullOrderCompleted() { TechTalk.SpecFlow.ScenarioInfo scenarioInfo = new TechTalk.SpecFlow.ScenarioInfo("Checkout:Payment and sucessfull Order completed", ((string[])(null))); #line 53 this.ScenarioSetup(scenarioInfo); #line 19 this.FeatureBackground(); #line 54 testRunner.Given("the Registrant proceeds to make the Reservation"); #line hidden TechTalk.SpecFlow.Table table6 = new TechTalk.SpecFlow.Table(new string[] { "first name", "last name", "email address"}); table6.AddRow(new string[] { "William", "Flash", "william@fabrikam.com"}); #line 55 testRunner.And("the Registrant enters these details", ((string)(null)), table6); #line 58 testRunner.And("the Registrant proceeds to Checkout:Payment"); #line 59 testRunner.When("the Registrant proceeds to confirm the payment"); #line 60 testRunner.Then("the Registration process was successful"); #line hidden TechTalk.SpecFlow.Table table7 = new TechTalk.SpecFlow.Table(new string[] { "seat type", "quantity"}); table7.AddRow(new string[] { "General admission", "1"}); table7.AddRow(new string[] { "Additional cocktail party", "1"}); #line 61 testRunner.And("the Order should be created with the following Order Items", ((string)(null)), table7); #line hidden this.ScenarioCleanup(); } [Xunit.FactAttribute()] [Xunit.TraitAttribute("FeatureTitle", "Self Registrant end to end scenario for making a Registration for a Conference si" + "te (happy path)")] [Xunit.TraitAttribute("Description", "Allocate all purchased Seats")] public virtual void AllocateAllPurchasedSeats() { TechTalk.SpecFlow.ScenarioInfo scenarioInfo = new TechTalk.SpecFlow.ScenarioInfo("Allocate all purchased Seats", ((string[])(null))); #line 67 this.ScenarioSetup(scenarioInfo); #line 19 this.FeatureBackground(); #line 68 testRunner.Given("the Registrant proceeds to make the Reservation"); #line hidden TechTalk.SpecFlow.Table table8 = new TechTalk.SpecFlow.Table(new string[] { "first name", "last name", "email address"}); table8.AddRow(new string[] { "William", "Flash", "william@fabrikam.com"}); #line 69 testRunner.And("the Registrant enters these details", ((string)(null)), table8); #line 72 testRunner.And("the Registrant proceeds to Checkout:Payment"); #line 73 testRunner.And("the Registrant proceeds to confirm the payment"); #line 74 testRunner.And("the Registration process was successful"); #line hidden TechTalk.SpecFlow.Table table9 = new TechTalk.SpecFlow.Table(new string[] { "seat type", "quantity"}); table9.AddRow(new string[] { "General admission", "1"}); table9.AddRow(new string[] { "Additional cocktail party", "1"}); #line 75 testRunner.And("the Order should be created with the following Order Items", ((string)(null)), table9); #line hidden TechTalk.SpecFlow.Table table10 = new TechTalk.SpecFlow.Table(new string[] { "seat type", "first name", "last name", "email address"}); table10.AddRow(new string[] { "General admission", "William", "Flash", "william@fabrikam.com"}); table10.AddRow(new string[] { "Additional cocktail party", "Jon", "Jaffe", "jon@fabrikam.com"}); #line 79 testRunner.When("the Registrant assigns these seats", ((string)(null)), table10); #line hidden TechTalk.SpecFlow.Table table11 = new TechTalk.SpecFlow.Table(new string[] { "seat type", "quantity"}); table11.AddRow(new string[] { "General admission", "1"}); table11.AddRow(new string[] { "Additional cocktail party", "1"}); #line 83 testRunner.Then("these seats are assigned", ((string)(null)), table11); #line hidden this.ScenarioCleanup(); } [System.CodeDom.Compiler.GeneratedCodeAttribute("TechTalk.SpecFlow", "1.8.1.0")] [System.Runtime.CompilerServices.CompilerGeneratedAttribute()] public class FixtureData : System.IDisposable { public FixtureData() { SelfRegistrantEndToEndScenarioForMakingARegistrationForAConferenceSiteHappyPathFeature.FeatureSetup(); } void System.IDisposable.Dispose() { SelfRegistrantEndToEndScenarioForMakingARegistrationForAConferenceSiteHappyPathFeature.FeatureTearDown(); } } } } #pragma warning restore #endregion
40.833333
251
0.571725
[ "Apache-2.0" ]
wayne-o/delete-me
source/Conference.AcceptanceTests/Conference.Specflow/Features/UserInterface/Views/Registration/SelfRegistrationEndToEndHappy.feature.cs
13,477
C#
namespace HBaseManagementStudio { partial class NewTableForm { /// <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() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(NewTableForm)); System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle1 = new System.Windows.Forms.DataGridViewCellStyle(); this.toolStrip1 = new System.Windows.Forms.ToolStrip(); this.btnSave = new System.Windows.Forms.ToolStripButton(); this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel(); this.label1 = new System.Windows.Forms.Label(); this.txtTableName = new System.Windows.Forms.TextBox(); this.dgvColumn = new System.Windows.Forms.DataGridView(); this.ColName = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.ColInMemory = new System.Windows.Forms.DataGridViewCheckBoxColumn(); this.ColCompression = new System.Windows.Forms.DataGridViewComboBoxColumn(); this.ColTimeToLive = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.ColMaxVersions = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.statusStrip1 = new System.Windows.Forms.StatusStrip(); this.toolStrip1.SuspendLayout(); this.tableLayoutPanel1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.dgvColumn)).BeginInit(); this.SuspendLayout(); // // toolStrip1 // this.toolStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.btnSave}); this.toolStrip1.Location = new System.Drawing.Point(0, 0); this.toolStrip1.Name = "toolStrip1"; this.toolStrip1.Size = new System.Drawing.Size(541, 25); this.toolStrip1.TabIndex = 0; this.toolStrip1.Text = "toolStrip1"; // // btnSave // this.btnSave.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.btnSave.Image = ((System.Drawing.Image)(resources.GetObject("btnSave.Image"))); this.btnSave.ImageTransparentColor = System.Drawing.Color.Magenta; this.btnSave.Name = "btnSave"; this.btnSave.Size = new System.Drawing.Size(23, 22); this.btnSave.Text = "Save"; this.btnSave.Click += new System.EventHandler(this.btnSave_Click); // // tableLayoutPanel1 // this.tableLayoutPanel1.ColumnCount = 2; this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 100F)); this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F)); this.tableLayoutPanel1.Controls.Add(this.label1, 0, 0); this.tableLayoutPanel1.Controls.Add(this.txtTableName, 1, 0); this.tableLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Top; this.tableLayoutPanel1.Location = new System.Drawing.Point(0, 25); this.tableLayoutPanel1.Name = "tableLayoutPanel1"; this.tableLayoutPanel1.RowCount = 1; this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F)); this.tableLayoutPanel1.Size = new System.Drawing.Size(541, 26); this.tableLayoutPanel1.TabIndex = 1; // // label1 // this.label1.Dock = System.Windows.Forms.DockStyle.Fill; this.label1.Location = new System.Drawing.Point(3, 0); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(94, 26); this.label1.TabIndex = 0; this.label1.Text = "Table Name:"; this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // txtTableName // this.txtTableName.Dock = System.Windows.Forms.DockStyle.Fill; this.txtTableName.Location = new System.Drawing.Point(103, 3); this.txtTableName.Name = "txtTableName"; this.txtTableName.Size = new System.Drawing.Size(435, 21); this.txtTableName.TabIndex = 1; // // dgvColumn // this.dgvColumn.BackgroundColor = System.Drawing.Color.FromArgb(((int)(((byte)(224)))), ((int)(((byte)(224)))), ((int)(((byte)(224))))); this.dgvColumn.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.dgvColumn.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { this.ColName, this.ColInMemory, this.ColCompression, this.ColTimeToLive, this.ColMaxVersions}); this.dgvColumn.Dock = System.Windows.Forms.DockStyle.Fill; this.dgvColumn.Location = new System.Drawing.Point(0, 51); this.dgvColumn.Name = "dgvColumn"; this.dgvColumn.RowTemplate.Height = 23; this.dgvColumn.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.CellSelect; this.dgvColumn.Size = new System.Drawing.Size(541, 253); this.dgvColumn.TabIndex = 2; // // ColName // this.ColName.HeaderText = "FamilyName"; this.ColName.Name = "ColName"; this.ColName.Width = 150; // // ColInMemory // this.ColInMemory.HeaderText = "InMemory"; this.ColInMemory.Name = "ColInMemory"; this.ColInMemory.Width = 60; // // ColCompression // this.ColCompression.DisplayStyle = System.Windows.Forms.DataGridViewComboBoxDisplayStyle.ComboBox; this.ColCompression.HeaderText = "Compression"; this.ColCompression.Items.AddRange(new object[] { "gz", "lzo", "snappy"}); this.ColCompression.Name = "ColCompression"; this.ColCompression.Resizable = System.Windows.Forms.DataGridViewTriState.True; this.ColCompression.Width = 80; // // ColTimeToLive // this.ColTimeToLive.HeaderText = "TimeToLive"; this.ColTimeToLive.Name = "ColTimeToLive"; // // ColMaxVersions // dataGridViewCellStyle1.NullValue = "1"; this.ColMaxVersions.DefaultCellStyle = dataGridViewCellStyle1; this.ColMaxVersions.HeaderText = "MaxVersions"; this.ColMaxVersions.Name = "ColMaxVersions"; // // statusStrip1 // this.statusStrip1.Location = new System.Drawing.Point(0, 304); this.statusStrip1.Name = "statusStrip1"; this.statusStrip1.Size = new System.Drawing.Size(541, 22); this.statusStrip1.TabIndex = 3; this.statusStrip1.Text = "statusStrip1"; // // Sub_NewTableForm // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(541, 326); this.Controls.Add(this.dgvColumn); this.Controls.Add(this.statusStrip1); this.Controls.Add(this.tableLayoutPanel1); this.Controls.Add(this.toolStrip1); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "Sub_NewTableForm"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "New Table"; this.toolStrip1.ResumeLayout(false); this.toolStrip1.PerformLayout(); this.tableLayoutPanel1.ResumeLayout(false); this.tableLayoutPanel1.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.dgvColumn)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.ToolStrip toolStrip1; private System.Windows.Forms.ToolStripButton btnSave; private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1; private System.Windows.Forms.Label label1; private System.Windows.Forms.TextBox txtTableName; private System.Windows.Forms.DataGridView dgvColumn; private System.Windows.Forms.StatusStrip statusStrip1; private System.Windows.Forms.DataGridViewTextBoxColumn ColName; private System.Windows.Forms.DataGridViewCheckBoxColumn ColInMemory; private System.Windows.Forms.DataGridViewComboBoxColumn ColCompression; private System.Windows.Forms.DataGridViewTextBoxColumn ColTimeToLive; private System.Windows.Forms.DataGridViewTextBoxColumn ColMaxVersions; } }
49.131707
147
0.617355
[ "Apache-2.0" ]
zhengyangyong/HBaseManagementStudio
HBaseManagementStudio/Form/NewTableForm.Designer.cs
10,076
C#
// <auto-generated /> using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using PizzaShop.Data; namespace PizzaShop.Migrations { [DbContext(typeof(PizzaShopContext))] [Migration("20191030185516_ChangedCostBackToInt")] partial class ChangedCostBackToInt { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "2.2.6-servicing-10079") .HasAnnotation("Relational:MaxIdentifierLength", 64); modelBuilder.Entity("PizzaShop.Core.PizzaOrder", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<int>("Cost"); b.Property<bool>("IsComplete"); b.Property<bool>("IsDelivery"); b.Property<int>("Quantity"); b.Property<string>("Size"); b.Property<string>("Toppings"); b.HasKey("Id"); b.ToTable("PizzaOrders"); }); modelBuilder.Entity("PizzaShop.Core.User", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("Name"); b.Property<int>("Pin"); b.Property<string>("Role"); b.HasKey("Id"); b.ToTable("Users"); }); #pragma warning restore 612, 618 } } }
28.241935
75
0.529983
[ "MIT" ]
troyfitzwater/pizza-shop-lab
PizzaShop/Migrations/20191030185516_ChangedCostBackToInt.Designer.cs
1,753
C#
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Cloud.Bigtable.V2.Snippets { // [START bigtable_v2_generated_BigtableServiceApi_CheckAndMutateRow_sync_flattened1] using Google.Cloud.Bigtable.V2; using Google.Protobuf; using System.Collections.Generic; public sealed partial class GeneratedBigtableServiceApiClientSnippets { /// <summary>Snippet for CheckAndMutateRow</summary> /// <remarks> /// This snippet has been automatically generated for illustrative purposes only. /// It may require modifications to work in your environment. /// </remarks> public void CheckAndMutateRow1() { // Create client BigtableServiceApiClient bigtableServiceApiClient = BigtableServiceApiClient.Create(); // Initialize request argument(s) string tableName = "projects/[PROJECT]/instances/[INSTANCE]/tables/[TABLE]"; ByteString rowKey = ByteString.Empty; RowFilter predicateFilter = new RowFilter(); IEnumerable<Mutation> trueMutations = new Mutation[] { new Mutation(), }; IEnumerable<Mutation> falseMutations = new Mutation[] { new Mutation(), }; // Make the request CheckAndMutateRowResponse response = bigtableServiceApiClient.CheckAndMutateRow(tableName, rowKey, predicateFilter, trueMutations, falseMutations); } } // [END bigtable_v2_generated_BigtableServiceApi_CheckAndMutateRow_sync_flattened1] }
44.638298
159
0.70877
[ "Apache-2.0" ]
AlexandrTrf/google-cloud-dotnet
apis/Google.Cloud.Bigtable.V2/Google.Cloud.Bigtable.V2.GeneratedSnippets/BigtableServiceApiClient.CheckAndMutateRow1Snippet.g.cs
2,098
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the ec2-2015-04-15.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.EC2.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; namespace Amazon.EC2.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for Volume Object /// </summary> public class VolumeUnmarshaller : IUnmarshaller<Volume, XmlUnmarshallerContext>, IUnmarshaller<Volume, JsonUnmarshallerContext> { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public Volume Unmarshall(XmlUnmarshallerContext context) { Volume unmarshalledObject = new Volume(); int originalDepth = context.CurrentDepth; int targetDepth = originalDepth + 1; if (context.IsStartOfDocument) targetDepth += 2; while (context.ReadAtDepth(originalDepth)) { if (context.IsStartElement || context.IsAttribute) { if (context.TestExpression("attachmentSet/item", targetDepth)) { var unmarshaller = VolumeAttachmentUnmarshaller.Instance; var item = unmarshaller.Unmarshall(context); unmarshalledObject.Attachments.Add(item); continue; } if (context.TestExpression("availabilityZone", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.AvailabilityZone = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("createTime", targetDepth)) { var unmarshaller = DateTimeUnmarshaller.Instance; unmarshalledObject.CreateTime = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("encrypted", targetDepth)) { var unmarshaller = BoolUnmarshaller.Instance; unmarshalledObject.Encrypted = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("iops", targetDepth)) { var unmarshaller = IntUnmarshaller.Instance; unmarshalledObject.Iops = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("kmsKeyId", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.KmsKeyId = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("size", targetDepth)) { var unmarshaller = IntUnmarshaller.Instance; unmarshalledObject.Size = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("snapshotId", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.SnapshotId = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("status", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.State = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("tagSet/item", targetDepth)) { var unmarshaller = TagUnmarshaller.Instance; var item = unmarshaller.Unmarshall(context); unmarshalledObject.Tags.Add(item); continue; } if (context.TestExpression("volumeId", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.VolumeId = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("volumeType", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.VolumeType = unmarshaller.Unmarshall(context); continue; } } else if (context.IsEndElement && context.CurrentDepth < originalDepth) { return unmarshalledObject; } } return unmarshalledObject; } /// <summary> /// Unmarshaller error response to exception. /// </summary> /// <param name="context"></param> /// <returns></returns> public Volume Unmarshall(JsonUnmarshallerContext context) { return null; } private static VolumeUnmarshaller _instance = new VolumeUnmarshaller(); /// <summary> /// Gets the singleton. /// </summary> public static VolumeUnmarshaller Instance { get { return _instance; } } } }
40.593939
131
0.52971
[ "Apache-2.0" ]
jasoncwik/aws-sdk-net
sdk/src/Services/EC2/Generated/Model/Internal/MarshallTransformations/VolumeUnmarshaller.cs
6,698
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.IO; using Microsoft.Azure.WebJobs.Script.Configuration; using Microsoft.Azure.WebJobs.Script.WebHost.Configuration; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using Microsoft.WebJobs.Script.Tests; using Xunit; using static Microsoft.Azure.WebJobs.Script.EnvironmentSettingNames; namespace Microsoft.Azure.WebJobs.Script.Tests.Configuration { public class CustomHttpHeadersOptionsSetupTests { private readonly TestEnvironment _environment = new TestEnvironment(); private readonly TestLoggerProvider _loggerProvider = new TestLoggerProvider(); private readonly string _hostJsonFile; private readonly string _rootPath; private readonly ScriptApplicationHostOptions _options; public CustomHttpHeadersOptionsSetupTests() { _rootPath = Path.Combine(Environment.CurrentDirectory, "ScriptHostTests"); Environment.SetEnvironmentVariable(AzureWebJobsScriptRoot, _rootPath); if (!Directory.Exists(_rootPath)) { Directory.CreateDirectory(_rootPath); } _options = new ScriptApplicationHostOptions { ScriptPath = _rootPath }; _hostJsonFile = Path.Combine(_rootPath, "host.json"); if (File.Exists(_hostJsonFile)) { File.Delete(_hostJsonFile); } } [Theory] [InlineData(@"{ 'version': '2.0', }")] [InlineData(@"{ 'version': '2.0', 'http': { 'customHeaders': { 'X-Content-Type-Options': 'nosniff' } } }")] public void MissingOrValidCustomHttpHeadersConfig_DoesNotThrowException(string hostJsonContent) { File.WriteAllText(_hostJsonFile, hostJsonContent); var configuration = BuildHostJsonConfiguration(); CustomHttpHeadersOptionsSetup setup = new CustomHttpHeadersOptionsSetup(configuration); CustomHttpHeadersOptions options = new CustomHttpHeadersOptions(); var ex = Record.Exception(() => setup.Configure(options)); Assert.Null(ex); } [Fact] public void ValidCustomHttpHeadersConfig_BindsToOptions() { string hostJsonContent = @"{ 'version': '2.0', 'http': { 'customHeaders': { 'X-Content-Type-Options': 'nosniff' } } }"; File.WriteAllText(_hostJsonFile, hostJsonContent); var configuration = BuildHostJsonConfiguration(); CustomHttpHeadersOptionsSetup setup = new CustomHttpHeadersOptionsSetup(configuration); CustomHttpHeadersOptions options = new CustomHttpHeadersOptions(); setup.Configure(options); Assert.Equal(new Dictionary<string, string>() { { "X-Content-Type-Options", "nosniff" } }, options); } private IConfiguration BuildHostJsonConfiguration(IEnvironment environment = null) { environment = environment ?? new TestEnvironment(); var loggerFactory = new LoggerFactory(); loggerFactory.AddProvider(_loggerProvider); var configSource = new HostJsonFileConfigurationSource(_options, environment, loggerFactory); var configurationBuilder = new ConfigurationBuilder() .Add(configSource); return configurationBuilder.Build(); } } }
38.754717
112
0.585686
[ "Apache-2.0", "MIT" ]
Hazhzeng/azure-functions-host
test/WebJobs.Script.Tests/Configuration/CustomHttpHeadersOptionsSetupTests.cs
4,110
C#
// dnlib: See LICENSE.txt for more info using System.IO; using dnlib.DotNet.Pdb.Symbols; using dnlib.IO; namespace dnlib.DotNet.Pdb.Managed { /// <summary> /// Creates a <see cref="SymbolReader"/> instance /// </summary> static class SymbolReaderFactory { /// <summary> /// Creates a new <see cref="SymbolReader"/> instance /// </summary> /// <param name="pdbContext">PDB context</param> /// <param name="pdbStream">PDB file stream which is now owned by this method</param> /// <returns>A new <see cref="SymbolReader"/> instance or <c>null</c>.</returns> public static SymbolReader Create(PdbReaderContext pdbContext, DataReaderFactory pdbStream) { if (pdbStream == null) return null; try { var debugDir = pdbContext.CodeViewDebugDirectory; if (debugDir == null) return null; if (!pdbContext.TryGetCodeViewData(out var pdbGuid, out uint age)) return null; var pdbReader = new PdbReader(pdbGuid, age); pdbReader.Read(pdbStream.CreateReader()); if (pdbReader.MatchesModule) return pdbReader; return null; } catch (PdbException) { } catch (IOException) { } finally { pdbStream?.Dispose(); } return null; } } }
26.955556
95
0.671063
[ "MIT" ]
KevOrr/dnlib
src/DotNet/Pdb/Managed/SymbolReaderFactory.cs
1,215
C#
using Unity.Entities; public struct SimulatedUnitRequestHandler : IComponentData { public bool SelectActionRequestSent; public bool LockActionRequestSent; }
18.555556
58
0.808383
[ "MIT" ]
r00f/LeyLineNetworking
workers/unity/Assets/Scripts/ECSPrototype/Systems/Simulated/SimulatedUnitRequestHandler.cs
167
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using UnityEngine; using HoloToolkit.Unity; using System.Collections.Generic; using HoloToolkit.Unity.InputModule; namespace HoloToolkit.Examples.GazeRuler { /// <summary> /// mananger all lines in the scene /// </summary> public class LineManager : Singleton<LineManager>, IGeometry { // save all lines in scene private Stack<Line> Lines = new Stack<Line>(); private Point lastPoint; private const float defaultLineScale = 0.005f; // place point and lines public void AddPoint(GameObject LinePrefab, GameObject PointPrefab, GameObject TextPrefab) { Vector3 hitPoint = GazeManager.Instance.HitPosition; GameObject point = (GameObject)Instantiate(PointPrefab, hitPoint, Quaternion.identity); if (lastPoint != null && lastPoint.IsStart) { Vector3 centerPos = (lastPoint.Position + hitPoint) * 0.5f; Vector3 directionFromCamera = centerPos - Camera.main.transform.position; float distanceA = Vector3.Distance(lastPoint.Position, Camera.main.transform.position); float distanceB = Vector3.Distance(hitPoint, Camera.main.transform.position); Debug.Log("A: " + distanceA + ",B: " + distanceB); Vector3 direction; if (distanceB > distanceA || (distanceA > distanceB && distanceA - distanceB < 0.1)) { direction = hitPoint - lastPoint.Position; } else { direction = lastPoint.Position - hitPoint; } float distance = Vector3.Distance(lastPoint.Position, hitPoint); GameObject line = (GameObject)Instantiate(LinePrefab, centerPos, Quaternion.LookRotation(direction)); line.transform.localScale = new Vector3(distance, defaultLineScale, defaultLineScale); line.transform.Rotate(Vector3.down, 90f); Vector3 normalV = Vector3.Cross(direction, directionFromCamera); Vector3 normalF = Vector3.Cross(direction, normalV) * -1; GameObject tip = (GameObject)Instantiate(TextPrefab, centerPos, Quaternion.LookRotation(normalF)); //unit is meter tip.transform.Translate(Vector3.up * 0.05f); tip.GetComponent<TextMesh>().text = distance + "m"; GameObject root = new GameObject(); lastPoint.Root.transform.parent = root.transform; line.transform.parent = root.transform; point.transform.parent = root.transform; tip.transform.parent = root.transform; Lines.Push(new Line { Start = lastPoint.Position, End = hitPoint, Root = root, Distance = distance }); lastPoint = new Point { Position = hitPoint, Root = point, IsStart = false }; } else { lastPoint = new Point { Position = hitPoint, Root = point, IsStart = true }; } } // delete latest placed lines public void Delete() { if (Lines != null && Lines.Count > 0) { Line lastLine = Lines.Pop(); Destroy(lastLine.Root); } } // delete all lines in the scene public void Clear() { if (Lines != null && Lines.Count > 0) { while (Lines.Count > 0) { Line lastLine = Lines.Pop(); Destroy(lastLine.Root); } } } // reset current unfinished line public void Reset() { if (lastPoint != null && lastPoint.IsStart) { Destroy(lastPoint.Root); lastPoint = null; } } } public struct Line { public Vector3 Start { get; set; } public Vector3 End { get; set; } public GameObject Root { get; set; } public float Distance { get; set; } } }
32.335664
117
0.520329
[ "MIT" ]
ChrisMa130/CSE461_P3
Assets/HoloToolkit-Examples/GazeRuler/Scripts/LineManager.cs
4,624
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.Device.I2c; using System.Device.Model; using System.Threading; using UnitsNet; namespace Iot.Device.Ahtxx { /// <summary> /// Base class for common functions of the AHT10/15 and AHT20 sensors. /// </summary> [Interface("AHTxx temperature and humidity sensor")] public abstract class AhtBase : IDisposable { /// <summary> /// Address of AHT10/15/20 device (0x38). This address is fix and cannot be changed. /// This implies that only one device can be attached to a single I2C bus at a time. /// </summary> public const int DefaultI2cAddress = 0x38; private readonly byte _initCommand; private I2cDevice _i2cDevice; private double _temperature; private double _humidity; /// <summary> /// Initializes a new instance of the binding for a sensor connected through I2C interface. /// </summary> /// <paramref name="i2cDevice">Reference to the initialized I2C interface device</paramref> /// <paramref name="initCommand">Type specific command for device initialization</paramref> public AhtBase(I2cDevice i2cDevice, byte initCommand) { _i2cDevice = i2cDevice ?? throw new ArgumentNullException(nameof(i2cDevice)); _initCommand = initCommand; // even if not clearly stated in datasheet, start with a software reset to assure clear start conditions SoftReset(); // check whether the device indicates the need for a calibration cycle // and perform calibration if indicated ==> c.f. datasheet, version 1.1, ch. 5.4 if (!IsCalibrated()) { Initialize(); } } /// <summary> /// Gets the current temperature reading from the sensor. /// Reading the temperature takes between 10 ms and 80 ms. /// </summary> /// <returns>Temperature reading</returns> [Telemetry("Temperature")] public Temperature GetTemperature() { Measure(); return Temperature.FromDegreesCelsius(_temperature); } /// <summary> /// Gets the current relative humidity reading from the sensor. /// Reading the humidity takes between 10 ms and 80 ms. /// </summary> /// <returns>Relative humidity reading</returns> [Telemetry("Humidity")] public RelativeHumidity GetHumidity() { Measure(); return RelativeHumidity.FromPercent(_humidity); } /// <summary> /// Perform sequence to retrieve current readings from device /// </summary> private void Measure() { SpanByte buffer = new byte[3] { // command parameters c.f. datasheet, version 1.1, ch. 5.4 (byte)CommonCommand.Measure, 0x33, 0x00 }; _i2cDevice.Write(buffer); // According to the datasheet the measurement takes 80 ms and completion is indicated by the status bit. // However, it seems to be faster at around 10 ms and sometimes up to 50 ms. while (IsBusy()) { Thread.Sleep(10); } buffer = new byte[6]; _i2cDevice.Read(buffer); // data format: 20 bit humidity, 20 bit temperature // 7 0 7 0 7 4 0 7 0 7 0 // [humidity 19..12] [humidity 11..4] [humidity 3..0|temp 19..16] [temp 15..8] [temp 7..0] // c.f. datasheet ch. 5.4.5 Int32 rawHumidity = (buffer[1] << 12) | (buffer[2] << 4) | (buffer[3] >> 4); Int32 rawTemperature = ((buffer[3] & 0xF) << 16) | (buffer[4] << 8) | buffer[5]; // RH[%] = Hraw / 2^20 * 100%, c.f. datasheet ch. 6.1 _humidity = (rawHumidity * 100.0) / 0x100000; // T[°C] = Traw / 2^20 * 200 - 50, c.f. datasheet ch. 6.1 _temperature = ((rawTemperature * 200.0) / 0x100000) - 50; } /// <summary> /// Perform soft reset command sequence /// </summary> private void SoftReset() { _i2cDevice.WriteByte((byte)CommonCommand.SoftReset); // reset requires 20ms at most, c.f. datasheet version 1.1, ch. 5.5 Thread.Sleep(20); } /// <summary> /// Perform initialization (calibration) command sequence /// </summary> private void Initialize() { SpanByte buffer = new byte[3] { _initCommand, 0x08, // command parameters c.f. datasheet, version 1.1, ch. 5.4 0x00 }; _i2cDevice.Write(buffer); // wait 10ms c.f. datasheet, version 1.1, ch. 5.4 Thread.Sleep(10); } private byte GetStatus() { _i2cDevice.WriteByte(0x71); // without this delay the reading the status fails often. Thread.Sleep(10); return _i2cDevice.ReadByte(); } private bool IsBusy() => (GetStatus() & (byte)StatusBit.Busy) == (byte)StatusBit.Busy; private bool IsCalibrated() => (GetStatus() & (byte)StatusBit.Calibrated) == (byte)StatusBit.Calibrated; /// <inheritdoc cref="IDisposable" /> public void Dispose() { _i2cDevice?.Dispose(); _i2cDevice = null!; } // datasheet version 1.1, table 10 [Flags] private enum StatusBit : byte { Calibrated = 0b_0000_1000, Busy = 0b1000_0000 } private enum CommonCommand : byte { SoftReset = 0b1011_1010, Measure = 0b1010_1100 } } }
35.290698
116
0.550082
[ "MIT" ]
CarlosSardo/nanoFramework.IoT.Device
devices/Ahtxx/AhtBase.cs
6,071
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Unity.UIWidgets.foundation; using Unity.UIWidgets.gestures; using Unity.UIWidgets.ui; using UnityEngine.Assertions; namespace Unity.UIWidgets.painting { public class TextSpan : DiagnosticableTree, IEquatable<TextSpan> { public delegate bool Visitor(TextSpan span); public readonly TextStyle style; public readonly string text; public readonly List<TextSpan> children; public readonly GestureRecognizer recognizer; public readonly HoverRecognizer hoverRecognizer; public TextSpan(string text = "", TextStyle style = null, List<TextSpan> children = null, GestureRecognizer recognizer = null, HoverRecognizer hoverRecognizer = null) { this.text = text; this.style = style; this.children = children; this.recognizer = recognizer; this.hoverRecognizer = hoverRecognizer; } public void build(ParagraphBuilder builder, float textScaleFactor = 1.0f) { var hasStyle = this.style != null; if (hasStyle) { builder.pushStyle(this.style, textScaleFactor); } if (!string.IsNullOrEmpty(this.text)) { builder.addText(this.text); } if (this.children != null) { foreach (var child in this.children) { Assert.IsNotNull(child); child.build(builder, textScaleFactor); } } if (hasStyle) { builder.pop(); } } public bool hasHoverRecognizer { get { bool need = false; this.visitTextSpan((text) => { if (text.hoverRecognizer != null) { need = true; return false; } return true; }); return need; } } bool visitTextSpan(Visitor visitor) { if (!string.IsNullOrEmpty(this.text)) { if (!visitor.Invoke(this)) { return false; } } if (this.children != null) { foreach (var child in this.children) { if (!child.visitTextSpan(visitor)) { return false; } } } return true; } public TextSpan getSpanForPosition(TextPosition position) { D.assert(this.debugAssertIsValid()); var offset = 0; var targetOffset = position.offset; var affinity = position.affinity; TextSpan result = null; this.visitTextSpan((span) => { var endOffset = offset + span.text.Length; if ((targetOffset == offset && affinity == TextAffinity.downstream) || (targetOffset > offset && targetOffset < endOffset) || (targetOffset == endOffset && affinity == TextAffinity.upstream)) { result = span; return false; } offset = endOffset; return true; }); return result; } public string toPlainText() { var sb = new StringBuilder(); this.visitTextSpan((span) => { sb.Append(span.text); return true; }); return sb.ToString(); } public int? codeUnitAt(int index) { if (index < 0) { return null; } var offset = 0; int? result = null; this.visitTextSpan(span => { if (index - offset < span.text.Length) { result = span.text[index - offset]; return false; } offset += span.text.Length; return true; }); return result; } bool debugAssertIsValid() { D.assert(() => { if (!this.visitTextSpan(span => { if (span.children != null) { foreach (TextSpan child in span.children) { if (child == null) { return false; } } } return true; })) { throw new UIWidgetsError( "A TextSpan object with a non-null child list should not have any nulls in its child list.\n" + "The full text in question was:\n" + this.toStringDeep(prefixLineOne: " ")); } return true; }); return true; } public RenderComparison compareTo(TextSpan other) { if (this.Equals(other)) { return RenderComparison.identical; } if (other.text != this.text || ((this.children == null) != (other.children == null)) || (this.children != null && other.children != null && this.children.Count != other.children.Count) || ((this.style == null) != (other.style != null)) ) { return RenderComparison.layout; } RenderComparison result = Equals(this.recognizer, other.recognizer) ? RenderComparison.identical : RenderComparison.metadata; if (!Equals(this.hoverRecognizer, other.hoverRecognizer)) { result = RenderComparison.function > result ? RenderComparison.function : result; } if (this.style != null) { var candidate = this.style.compareTo(other.style); if (candidate > result) { result = candidate; } if (result == RenderComparison.layout) { return result; } } if (this.children != null) { for (var index = 0; index < this.children.Count; index++) { var candidate = this.children[index].compareTo(other.children[index]); if (candidate > result) { result = candidate; } if (result == RenderComparison.layout) { return result; } } } return result; } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) { return false; } if (ReferenceEquals(this, obj)) { return true; } if (obj.GetType() != this.GetType()) { return false; } return this.Equals((TextSpan) obj); } public override int GetHashCode() { unchecked { var hashCode = (this.style != null ? this.style.GetHashCode() : 0); hashCode = (hashCode * 397) ^ (this.text != null ? this.text.GetHashCode() : 0); hashCode = (hashCode * 397) ^ (this.recognizer != null ? this.recognizer.GetHashCode() : 0); hashCode = (hashCode * 397) ^ (this.childHash()); return hashCode; } } public bool Equals(TextSpan other) { if (ReferenceEquals(null, other)) { return false; } if (ReferenceEquals(this, other)) { return true; } return Equals(this.style, other.style) && string.Equals(this.text, other.text) && childEquals(this.children, other.children) && this.recognizer == other.recognizer; } public static bool operator ==(TextSpan left, TextSpan right) { return Equals(left, right); } public static bool operator !=(TextSpan left, TextSpan right) { return !Equals(left, right); } int childHash() { unchecked { var hashCode = 0; if (this.children != null) { foreach (var child in this.children) { hashCode = (hashCode * 397) ^ (child != null ? child.GetHashCode() : 0); } } return hashCode; } } static bool childEquals(List<TextSpan> left, List<TextSpan> right) { if (ReferenceEquals(left, right)) { return true; } if (left == null || right == null) { return false; } return left.SequenceEqual(right); } public override void debugFillProperties(DiagnosticPropertiesBuilder properties) { base.debugFillProperties(properties); properties.defaultDiagnosticsTreeStyle = DiagnosticsTreeStyle.whitespace; // Properties on style are added as if they were properties directly on // this TextSpan. if (this.style != null) { this.style.debugFillProperties(properties); } properties.add(new DiagnosticsProperty<GestureRecognizer>( "recognizer", this.recognizer, description: this.recognizer == null ? "" : this.recognizer.GetType().FullName, defaultValue: Diagnostics.kNullDefaultValue )); properties.add(new StringProperty("text", this.text, showName: false, defaultValue: Diagnostics.kNullDefaultValue)); if (this.style == null && this.text == null && this.children == null) { properties.add(DiagnosticsNode.message("(empty)")); } } public override List<DiagnosticsNode> debugDescribeChildren() { if (this.children == null) { return new List<DiagnosticsNode>(); } return this.children.Select((child) => { if (child != null) { return child.toDiagnosticsNode(); } else { return DiagnosticsNode.message("<null child>"); } }).ToList(); } } }
34.801917
120
0.465987
[ "Unlicense" ]
ameru/karting-microgame-unity
try not to fall off rainbow road/Library/PackageCache/com.unity.uiwidgets@1.0.6-preview/Runtime/painting/text_span.cs
10,895
C#
#region Using directives using System; using System.Configuration; using System.IO; using System.IO.IsolatedStorage; using System.Xml; using System.Diagnostics; using Timer = System.Threading.Timer; using TimerCallback = System.Threading.TimerCallback; using StringDictionary = System.Collections.Specialized.StringDictionary; #endregion namespace Genghis { //----------------------------------------------------------------------------- //<filedescription file="Preferences.cs" company="Microsoft"> // <copyright> // Copyright (c) 2004 Microsoft Corporation. All rights reserved. // </copyright> // <purpose> // Contains Preferences used in WindowSerializer Class // </purpose> // <notes> // </notes> //</filedescription> //----------------------------------------------------------------------------- /// <summary> /// Provides a way to persist user preferences.</summary> /// <remarks> /// By default, this class uses Isolated Storage to provide provide portable /// and safe persistance.<br/> /// It is envisioned that in the future, alternate backing stores will be /// available (the registry would be an obvious one). /// </remarks> /// /// <example> /// Here's an example of how to persist the persist the personal details of a /// user (for registration purposes, perhaps). /// <code> /// Preferences prefWriter = Preferences.GetUserNode("Personal Details"); /// prefWriter.SetProperty("Name", "Joe Bloggs"); /// prefWriter.SetProperty("Age", 56); /// prefWriter.Close(); /// </code> /// /// And here's an example of how to read these properties back in. /// <code> /// Preferences prefReader = Preferences.GetUserNode("Personal Details"); /// string name = prefReader.GetString("Name", "Anonymous"); /// int age = prefReader.GetInt32("Age", 0); /// prefReader.Close(); /// </code> /// </example> public abstract class Preferences : IDisposable { static Type backingStore = null; // The back-end data storage class. string path; /// <summary> /// Constructs a preferences writer at the root.</summary> protected Preferences() { path = ""; } /// <summary> /// Constructs a preferences writer with a path.</summary> /// <param name="path"> /// The path under which the preferences will be saved.</param> protected Preferences(string path) { this.path = ValidatePath(path, "path"); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Clean up any resources being used. /// </summary> protected virtual void Dispose(bool disposing) { } /// <summary> /// Disposes of any resources.</summary> /// <remarks> /// Equivalent to calling Dispose().</remarks> public void Close() { Dispose(); } /// <summary> /// Validates the path argument.</summary> private string ValidatePath(string path, string argumentName) { if (path.Length > 0 && path[path.Length - 1] != '/') { path = path + '/'; } return path; } public string Path { get { return path; } } /// <summary> /// Gets a property</summary> /// <param name="path"> /// The property name.<br/> /// Use slash (/) to logically separate groups of settings.</param> /// <param name="defaultValue"> /// The default property value. If no previous property exists, or the /// preferences store is unavailable, this value will be returned.</param> /// <param name="returnType"> /// The return type. This must be a type /// supported by the System.Convert class. The supported types are: /// Boolean, Char, SByte, Byte, Int16, Int32, Int64, UInt16, UInt32, /// UInt64, Single, Double, Decimal, DateTime and String.</param> /// <returns> /// Returns the property value (with the same type as returnType).</returns> public abstract object GetProperty(string path, object defaultValue, Type returnType); /// <summary> /// Gets a property</summary> /// <param name="name"> /// The property name.<br/> /// Use slash (/) to logically separate groups of /// settings.</param> /// <param name="defaultValue"> /// The default property value. If no previous property exists, or the /// preferences store is unavailable, this value will be returned.</param> /// <returns> /// Returns the property value (with the same type as defaultValue).</returns> /// <remarks> /// The return type is converted to the same type as the defaultValue /// argument before it is returned. Therefore, this must be a type /// supported by the System.Convert class. The supported types are: /// Boolean, Char, SByte, Byte, Int16, Int32, Int64, UInt16, UInt32, /// UInt64, Single, Double, Decimal, DateTime and String.</remarks> public object GetProperty(string name, object defaultValue) { if (defaultValue == null) { throw new ArgumentNullException("defaultValue"); } return GetProperty(name, defaultValue, defaultValue.GetType()); } // Convenience helper methods. public string GetString(string name, string defaultValue) { return (string)GetProperty(name, defaultValue, typeof(string)); } public bool GetBoolean(string name, bool defaultValue) { return (bool)GetProperty(name, defaultValue, typeof(bool)); } public int GetInt32(string name, int defaultValue) { return (int)GetProperty(name, defaultValue, typeof(int)); } public double GetInt64(string name, long defaultValue) { return (long)GetProperty(name, defaultValue, typeof(long)); } public float GetSingle(string name, float defaultValue) { return (float)GetProperty(name, defaultValue, typeof(float)); } public double GetDouble(string name, double defaultValue) { return (double)GetProperty(name, defaultValue, typeof(double)); } /// <summary> /// Sets a property</summary> /// <param name="name"> /// The property name.<br/> /// Use slash (/) to logically separate groups of settings.</param> /// <param name="value"> /// The property value.</param> /// <remarks> /// Currently, the value parameter must be a type supported by the /// System.Convert class. The supported types are: Boolean, Char, SByte, /// Byte, Int16, Int32, Int64, UInt16, UInt32, UInt64, Single, Double, /// Decimal, DateTime and String.</remarks> public abstract void SetProperty(string name, object value); /// <summary> /// Flushes any outstanding property data to disk.</summary> public abstract void Flush(); /// <summary> /// Opens a new subnode to store settings under. /// </summary> /// <param name="subpath">The path of the new subnode.</param> /// <remarks>The subnode is created if it doesn't already exist.</remarks> public virtual Preferences GetSubnode(string subpath) { // Create a new instance of the same store as this. return (Preferences)Activator.CreateInstance(GetType(), new object[] { path + ValidatePath(subpath, "subpath") }); } /// <summary> /// Constructs a preferences object at the root of the per-user /// settings.</summary> public static Preferences GetUserRoot() { return GetUserNode(""); } /// <summary> /// Constructs a per-user preferences object from a class.</summary> /// <param name="type"> /// The class you want to store settings for. All the /// periods in the name will be converted to slashes.</param> public static Preferences GetUserNode(Type type) { string path = type.FullName; path = path.Replace('.', '/'); return GetUserNode(path); } /// <summary> /// Constructs a per-user preferences object from a path.</summary> /// <param name="path"> /// Represents the path the preferences are stored under. /// Equivalent to a directory path or a registry key path.<br/> /// <b>Important Note:</b> The seperator character is slash ('/') /// <b>NOT</b> backslash ('\'). /// </param> /// <remarks>The path of the root node is "".</remarks> public static Preferences GetUserNode(string path) { if (path == null) { throw new ArgumentNullException("path"); } if (backingStore == null) { try { string backingStoreName = null; try { // Read the fully-qualified type name of the backing store. AppSettingsReader appSettings = new AppSettingsReader(); backingStoreName = (string)appSettings.GetValue("CustomPreferencesStore", typeof(string)); } catch { Trace.WriteLine("No custom data store specified (in application settings file). Using default."); throw; } try { // Load the type and create a new instance. backingStore = Type.GetType(backingStoreName, true); } catch { Trace.WriteLine("Could not load custom data store " + backingStoreName + ". Using default."); throw; } } catch { // Use the default backing store (isolated storage). backingStore = typeof(IsolatedStorageUserPreferencesStore); } } // Create an instance of the backing store. return (Preferences)Activator.CreateInstance(backingStore, new object[] { path }); } } /// <summary> /// A back-end preferences implementation using Isolated Storage as the /// underlying storage mechanism.</summary> /// <remarks> /// This implementation has the following properties: /// <list type="bullet"> /// <item><description>Reads and writes are involve a single hashtable /// access, and are thus very fast.</description></item> /// <item><description>The backing file is read once on startup, and /// written once on shutdown (using the Application.ApplicationExit event). /// </description></item> /// </list> /// </remarks> class IsolatedStorageUserPreferencesStore : Preferences { static StringDictionary userStore; static bool userStoreModified; //static StringDictionary machineStore; //static bool machineStoreModified; /// <summary>Initializes instance variables and loads initial settings from /// the backing store.</summary> /// <param name="path"> /// Represents the name of the group the preferences are stored under. /// Roughly equivalent to a directory path or a registry key path. /// You can nest groups using the slash (/) character. /// "" (the empty string) represents the top-level group. A slash (/) /// will be added to the end of the path if it is lacking one.</param> public IsolatedStorageUserPreferencesStore(string path) : base(path) { if (userStore == null) { userStore = new StringDictionary(); // Load preferences. Deserialize(); userStoreModified = false; // Flush the preferences on application exit. System.Windows.Forms.Application.ApplicationExit += new EventHandler(OnApplicationExit); } } /// <summary> /// Gets a property</summary> /// <param name="name"> /// The property name.<br/> /// Use slash (/) to logically separate groups of settings.</param> /// <param name="defaultValue"> /// The default property value. If no previous property exists, or the /// preferences store is unavailable, this value will be returned.</param> /// <param name="returnType"> /// The return type. This must be a type /// supported by the System.Convert class. The supported types are: /// Boolean, Char, SByte, Byte, Int16, Int32, Int64, UInt16, UInt32, /// UInt64, Single, Double, Decimal, DateTime and String.</param> /// <returns> /// Returns the property value (with the same type as returnType).</returns> public override object GetProperty(string name, object defaultValue, Type returnType) { string value = userStore[Path + name]; if (value == null) { return defaultValue; } try { return Convert.ChangeType(value, returnType); } catch (Exception e) { Trace.WriteLine("Genghis.Preferences: The property " + name + " could not be converted to the intended type (" + returnType + "). Using defaults."); Trace.WriteLine("Genghis.Preferences: The exception was: " + e.Message); return defaultValue; } } /// <summary> /// Sets a property</summary> /// <param name="name"> /// The property name.<br/> /// Use slash (/) to logically separate groups of settings.</param> /// <param name="value"> /// The property value.</param> /// <remarks> /// Currently, the value parameter must be a type supported by the /// System.Convert class. The supported types are: Boolean, Char, SByte, /// Byte, Int16, Int32, Int64, UInt16, UInt32, UInt64, Single, Double, /// Decimal, DateTime and String.</remarks> public override void SetProperty(string name, object value) { userStore[Path + name] = Convert.ToString(value); userStoreModified = true; } /// <summary> /// Flushes any outstanding properties to disk.</summary> public override void Flush() { Serialize(); } /// <summary> /// Flush any outstanding preferences data on application exit.</summary> private static void OnApplicationExit(object sender, EventArgs e) { Serialize(); } /// <summary> /// Creates a write-only stream on the backing store.</summary> /// <returns> /// A stream to write to.</returns> private static IsolatedStorageFileStream CreateSettingsStream() { // TODO: Check for permission to do roaming. // Roaming stores require higher permissions. // If we are not allowed, use IsolatedStorageFile.GetUserStoreForDomain() instead. IsolatedStorageFile store = IsolatedStorageFile.GetStore( IsolatedStorageScope.User | IsolatedStorageScope.Assembly | IsolatedStorageScope.Domain | IsolatedStorageScope.Roaming, null, null); return new IsolatedStorageFileStream("preferences.xml", FileMode.Create, store); } /// <summary> /// Opens a read-only stream on the backing store.</summary> /// <returns> /// A stream to read from.</returns> private static IsolatedStorageFileStream OpenSettingsStream() { // TODO: Check for permission to do roaming. // Roaming stores require higher permissions. // If we are not allowed, use IsolatedStorageFile.GetUserStoreForDomain() instead. IsolatedStorageFile store = IsolatedStorageFile.GetStore( IsolatedStorageScope.User | IsolatedStorageScope.Assembly | IsolatedStorageScope.Domain | IsolatedStorageScope.Roaming, null, null); return new IsolatedStorageFileStream("preferences.xml", FileMode.Open, store); } /// <summary>Deserializes to the userStore hashtable from an isolated storage stream.</summary> /// <remarks>Exceptions are silently ignored.</remarks> private static void Deserialize() { XmlTextReader reader = null; try { reader = new XmlTextReader(OpenSettingsStream()); // Read name/value pairs. while (reader.Read()) { if (reader.NodeType == XmlNodeType.Element && reader.Name == "property") { string name = reader.GetAttribute("name"); string value = reader.ReadString(); userStore[name] = value; } } reader.Close(); } catch (Exception e) { // Release all resources held by the XmlTextReader. if (reader != null) reader.Close(); // Report exception. Trace.WriteLine("Genghis.Preferences: There was an error while deserializing from Isolated Storage. Ignoring."); Trace.WriteLine("Genghis.Preferences: The exception was: " + e.Message); Trace.WriteLine(e.StackTrace); } } /// <summary>Serializes the userStore hashtable to an isolated storage stream.</summary> /// <remarks>Exceptions are silently ignored.</remarks> private static void Serialize() { if (userStoreModified == false) { return; } XmlTextWriter writer = null; try { writer = new XmlTextWriter(CreateSettingsStream(), null); // Write stream to console. //XmlTextWriter writer = new XmlTextWriter(Console.Out); // Use indentation for readability. writer.Formatting = Formatting.Indented; writer.Indentation = 4; writer.WriteStartDocument(true); writer.WriteStartElement("preferences"); // Write properties. foreach (System.Collections.DictionaryEntry entry in userStore) { writer.WriteStartElement("property"); writer.WriteAttributeString("name", (string)entry.Key); writer.WriteString((string)entry.Value); writer.WriteEndElement(); } writer.WriteEndElement(); writer.WriteEndDocument(); writer.Close(); // No longer modified compared to the copy on disk. userStoreModified = false; } catch (Exception e) { // Release all resources held by the XmlTextWriter. if (writer != null) { writer.Close(); } // Report exception. Trace.WriteLine("Genghis.Preferences: There was an error while serializing to Isolated Storage. Ignoring."); Trace.WriteLine("Genghis.Preferences: The exception was: " + e.Message); Trace.WriteLine(e.StackTrace); } } } }
38.445455
166
0.536392
[ "BSD-3-Clause" ]
RssBandit/RssBandit
source/RssBandit/WinGui/Genghis/Preferences.cs
21,147
C#
using Org.BouncyCastle.Bcpg; using Org.BouncyCastle.Bcpg.OpenPgp; using Org.BouncyCastle.Security; using Org.BouncyCastle.Utilities.IO; using System; using System.Collections.Generic; using System.IO; using System.Text; namespace PGPSteam { public class PGPLib { #region Methods String m_PublicKey = null; String m_PrivateKey = null; String m_PrivateKeyPassword = null; #endregion #region Methods /// <summary> /// Encrypt some data using public key /// </summary> /// <param name="data">Data</param> public String Encrypt(String data) { using (Stream stream = m_PublicKey.Streamify()) { var key = stream.ImportPublicKey(); using (var clearStream = data.Streamify()) using (var cryptoStream = new MemoryStream()) { clearStream.PgpEncrypt(cryptoStream, key); cryptoStream.Position = 0; return cryptoStream.Stringify(); } } } /// <summary> /// Decrypt some data using private key /// </summary> /// <param name="data">Data</param> public String Decrypt(String data) { using (var cryptoStream = data.Streamify()) using (var clearStream = new MemoryStream()) { cryptoStream.PgpDecrypt(m_PrivateKey, m_PrivateKeyPassword); return cryptoStream.Stringify(); } } #endregion #region Constructors /// <summary> /// Create a PGP Library instance /// </summary> /// <param name="publicKey">Public key</param> public PGPLib(String publicKey) { m_PublicKey = publicKey; } /// <summary> /// Create a PGP Library instance /// </summary> /// <param name="publicKey">Public key</param> /// <param name="privateKey">Private key</param> /// <param name="privateKeyPassword">Private key password</param> public PGPLib(String publicKey, String privateKey, String privateKeyPassword) { m_PublicKey = publicKey; m_PrivateKey = privateKey; m_PrivateKeyPassword = privateKeyPassword; } #endregion } }
30.1125
85
0.552927
[ "MIT" ]
alandoherty/pgpsteam
Source/PGPLib.cs
2,411
C#
using UnityEngine; using System.Collections; using System; [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] public class DOMParserAttribute : Attribute { public string[] Names { get; private set; } public Type[] Types { get; private set; } public DOMParserAttribute(params string[] names) { Names = names; Types = new Type[0]; } public DOMParserAttribute(params Type[] types) { Types = types; Names = new string[0]; } }
21
62
0.644841
[ "CC0-1.0" ]
Grupo-M-JuegosSerios/ProyectFinal
ProyectoFinal/Assets/uAdventure/__Scripts/Core/Loader/Subparsers/DOMParserAttribute.cs
506
C#
using Dapper; using Dapper.Contrib.Extensions; using DataAccess.Interfaces; using Domain.Models; using Microsoft.Data.SqlClient; using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; namespace DataAccess { public class DapperUserRepository : IUserRepository { private readonly string _connectionString; public DapperUserRepository(string connectionString) { _connectionString = connectionString; } public void Create(User entity) { using (var connection = new SqlConnection(_connectionString)) { connection.Open(); connection.Insert(entity); } } public void Delete(int id) { var user = GetById(id); using (var connection = new SqlConnection(_connectionString)) { connection.Open(); connection.Delete(user); } } public List<User> GetAll() { using (var connection = new SqlConnection(_connectionString)) { var sqlQuery = @"SELECT * FROM Users u left join MovieUser mu on mu.UsersId = u.Id left join Movies m on mu.MoviesId = m.Id"; var users = connection.Query<User, Movie, User>(sqlQuery, (user, movie) => { if (movie?.Id != default) { user.Movies.Add(movie); } return user; }); var result = users.GroupBy(x => x.Id).Select(users => { var groupedUser = users.FirstOrDefault(); groupedUser.Movies = users.SelectMany(x => x.Movies).ToList(); return groupedUser; }); return result.ToList(); } } public User GetById(int id) { using (var connection = new SqlConnection(_connectionString)) { var parameters = new DynamicParameters(); parameters.Add("id", id, DbType.Int32, ParameterDirection.Input); var sqlQuery = @"SELECT * FROM Users u WHERE u.Id = @id"; return connection.QuerySingle<User>(sqlQuery, parameters); } } public void Update(User entity) { using (var connection = new SqlConnection(_connectionString)) { connection.Update(entity); } } public void RentMovie(int movieId, int userId) { using(var connection = new SqlConnection(_connectionString)) { var parameters = new DynamicParameters(); parameters.Add("MovieId", movieId, DbType.Int32, ParameterDirection.Input); parameters.Add("UserId", userId, DbType.Int32, ParameterDirection.Input); connection.Execute(@"INSERT INTO MovieUser (MoviesId, UsersId) VALUES(@MovieId, @UserId)", parameters); } } } }
31.194175
119
0.524121
[ "MIT" ]
filipbelevski/WebApiHomework
SEDC.WebApi.Workshop.Movies.API/DataAccess/DapperUserRepository.cs
3,215
C#
using Engine.Model.Common.Dto; using System; using System.Security; namespace Engine.Model.Common.Entities { [Serializable] public class FileDescription : IEquatable<FileDescription> { private readonly FileId _id; private readonly long _size; private readonly string _name; /// <summary> /// Create new file description instance. /// </summary> /// <param name="dto">File description dto.</param> public FileDescription(FileDescriptionDto dto) : this(dto.Id, dto.Size, dto.Name) { } /// <summary> /// Create new file description instance. /// </summary> /// <param name="id">File identification.</param> /// <param name="size">File size.</param> /// <param name="name">File name.</param> [SecuritySafeCritical] public FileDescription(FileId id, long size, string name) { _id = id; _size = size; _name = name; } /// <summary> /// File identification. /// </summary> public FileId Id { [SecuritySafeCritical] get { return _id; } } /// <summary> /// File name. /// </summary> public string Name { [SecuritySafeCritical] get { return _name; } } /// <summary> /// File size. /// </summary> public long Size { [SecuritySafeCritical] get { return _size; } } [SecuritySafeCritical] public override bool Equals(object obj) { if (obj is null) return false; if (ReferenceEquals(obj, this)) return true; var file = obj as FileDescription; if (file is null) return false; return Equals(file); } [SecuritySafeCritical] public bool Equals(FileDescription file) { if (file is null) return false; if (ReferenceEquals(file, this)) return true; return _id == file._id; } [SecuritySafeCritical] public override int GetHashCode() { return _id.GetHashCode(); } [SecuritySafeCritical] public FileDescriptionDto ToDto() { return new FileDescriptionDto(this); } } }
20.207547
61
0.591036
[ "MIT" ]
Nirklav/TCPChat
Engine/Model/Common/Entities/FileDescription.cs
2,144
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the rekognition-2016-06-27.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.Rekognition.Model { /// <summary> /// Information about the Amazon Kinesis Data Streams stream to which a Amazon Rekognition /// Video stream processor streams the results of a video analysis. For more information, /// see CreateStreamProcessor in the Amazon Rekognition Developer Guide. /// </summary> public partial class StreamProcessorOutput { private KinesisDataStream _kinesisDataStream; private S3Destination _s3Destination; /// <summary> /// Gets and sets the property KinesisDataStream. /// <para> /// The Amazon Kinesis Data Streams stream to which the Amazon Rekognition stream processor /// streams the analysis results. /// </para> /// </summary> public KinesisDataStream KinesisDataStream { get { return this._kinesisDataStream; } set { this._kinesisDataStream = value; } } // Check to see if KinesisDataStream property is set internal bool IsSetKinesisDataStream() { return this._kinesisDataStream != null; } /// <summary> /// Gets and sets the property S3Destination. /// <para> /// The Amazon S3 bucket location to which Amazon Rekognition publishes the detailed /// inference results of a video analysis operation. /// </para> /// </summary> public S3Destination S3Destination { get { return this._s3Destination; } set { this._s3Destination = value; } } // Check to see if S3Destination property is set internal bool IsSetS3Destination() { return this._s3Destination != null; } } }
33.175
109
0.656745
[ "Apache-2.0" ]
Hazy87/aws-sdk-net
sdk/src/Services/Rekognition/Generated/Model/StreamProcessorOutput.cs
2,654
C#
using Microsoft.AspNetCore.StaticFiles; namespace Audiochan.Core.Common.Extensions { public static class FileExtensions { private static readonly FileExtensionContentTypeProvider FileExtensionContentTypeProvider = new(); public static string GetContentType(this string fileName, string? defaultContentType = null) { if (FileExtensionContentTypeProvider.TryGetContentType(fileName, out var contentType)) { return contentType; } return string.IsNullOrWhiteSpace(defaultContentType) ? "application/octet-stream" : defaultContentType; } public static bool TryGetContentType(this string fileName, out string contentType) { return FileExtensionContentTypeProvider.TryGetContentType(fileName, out contentType); } } }
34.230769
106
0.673034
[ "MIT" ]
nollidnosnhoj/Audiochan
src/api/src/Audiochan.Core/Common/Extensions/FileExtensions.cs
892
C#