content
stringlengths
23
1.05M
using System.Collections.Generic; using ViceIO.Web.ViewModels.VicesCategories; namespace ViceIO.Services { public interface IVicesCategoriesService { IEnumerable<VicesCategoriesModel> GetAll(); } }
using UnityEngine; namespace UI.Controllers { [RequireComponent(typeof(TMPro.TextMeshProUGUI))] // ReSharper disable once InconsistentNaming public class UIValueController : MonoBehaviour { [SerializeField] private TMPro.TextMeshProUGUI value; private void Awake() { value = GetComponent<TMPro.TextMeshProUGUI>(); } /// <summary> /// Sets given integer value to "text". /// </summary> /// <param name="value">int-only</param> // ReSharper disable once ParameterHidesMember public void SetValue(int value) { this.value.text = value == -1 ? "Tutorial" : value.ToString(); } /// <summary> /// Sets given integer values to "text" in a given debug conditions. /// </summary> /// <param name="currentValue"></param> /// <param name="selectedValue"></param> public void SetValue(int currentValue, int selectedValue) { this.value.text = selectedValue == -1 ? $"{currentValue} / Tutorial" : $"{currentValue} / {selectedValue}"; } /// <summary> /// Gets current "text" value as integer. /// </summary> /// <returns>int-only</returns> public int GetValue() { return System.Convert.ToInt32(value.text); } /// <summary> /// Increment "text" value by given integer. /// </summary> /// <param name="by">Default 1.</param> public void Increment(int by = 1) { value.text = (GetValue() + by).ToString(); } /// <summary> /// Decrement "text" value by given integer. /// </summary> /// <param name="by">Default 1.</param> public void Decrement(int by = 1) { value.text = GetValue() + (-1 * by) >= 0 ? (GetValue() + (-1 * by)).ToString() : 0.ToString(); } } }
using Android.Content; using LagoVista.Core.IOC; using LagoVista.Core.PlatformSupport; using LagoVista.XPlat.Droid.Services; using LagoVista.Core; namespace LagoVista.XPlat.Droid { public static class Startup { public static void Init(Context context, string key) { SLWIOC.RegisterSingleton<ILogger>(new Loggers.MobileCenterLogger(key)); SLWIOC.Register<IStorageService>(new StorageService()); SLWIOC.Register<IPopupServices>(new LagoVista.XPlat.Core.Services.PopupServices()); SLWIOC.Register<INetworkService>(new NetworkService()); SLWIOC.Register<IDeviceInfo>(new DeviceInfo()); SLWIOC.Register<IDispatcherServices>(new DispatcherServices(context)); IconFonts.IconFontSupport.RegisterFonts(); } } }
using AssetsTools.NET; using AssetsTools.NET.Extra; using Avalonia; using Avalonia.Controls; using Avalonia.Markup.Xaml; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.IO; using System.Linq; namespace UABEAvalonia { public partial class ExportBatchChooseType : Window { private ComboBox comboFileType; private Button btnOk; private Button btnCancel; public ExportBatchChooseType() { InitializeComponent(); #if DEBUG this.AttachDevTools(); #endif //generated items comboFileType = this.FindControl<ComboBox>("comboFileType"); btnOk = this.FindControl<Button>("btnOk"); btnCancel = this.FindControl<Button>("btnCancel"); btnOk.Click += BtnOk_Click; btnCancel.Click += BtnCancel_Click; } private void BtnOk_Click(object? sender, Avalonia.Interactivity.RoutedEventArgs e) { Close(((ComboBoxItem)comboFileType.SelectedItem).Content.ToString()); } private void BtnCancel_Click(object? sender, Avalonia.Interactivity.RoutedEventArgs e) { Close(null); } private void InitializeComponent() { AvaloniaXamlLoader.Load(this); } } }
namespace Adrenak.AirPeer { public interface IPayload { byte[] GetBytes(); void SetBytes(byte[] bytes); } }
using System; using System.Collections.Generic; using System.Configuration; namespace Mash.AppSettings { /// <summary> /// Loads the requested setting from the app configiguration file /// </summary> internal class AppConfigSettingLoader : ISettingLoader { /// <summary> /// Loads the specified setting /// </summary> /// <param name="settingKey">The key of the setting to load</param> /// <returns>The value</returns> public string GetSetting(string settingKey) { if (String.IsNullOrWhiteSpace(settingKey)) { throw new ArgumentNullException(nameof(settingKey)); } return ConfigurationManager.AppSettings[settingKey]; } /// <summary> /// Loads the specified connection string /// </summary> /// <param name="connectionStringKey">The key of the connection string to load</param> /// <returns>The connection string value</returns> public string GetConnectionString(string connectionStringKey) { if (String.IsNullOrWhiteSpace(connectionStringKey)) { throw new ArgumentNullException(nameof(connectionStringKey)); } return ConfigurationManager.ConnectionStrings[connectionStringKey]?.ConnectionString; } /// <summary> /// Loads all connection strings from the config file /// </summary> /// <returns> /// A dictionary of connection strings where key is the name and the value is the connection string /// </returns> public IDictionary<string, string> GetConnectionStrings() { var connectionStrings = new Dictionary<string, string>(); foreach (ConnectionStringSettings item in ConfigurationManager.ConnectionStrings) { connectionStrings.Add(item.Name, item.ConnectionString); } return connectionStrings; } } }
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using Microsoft.AspNetCore.Mvc.Rendering; namespace IdentityServer4.Quickstart.UI { public class LoginInputModel { public string Username { get; set; } = "mrblue"; public bool RememberLogin { get; set; } public string ReturnUrl { get; set; } public List<SelectListItem> Users { get; } = new List<SelectListItem> { new SelectListItem { Value = "mrblack", Text = "mrblack" }, new SelectListItem { Value = "mrpurple", Text = "mrpurple" }, new SelectListItem { Value = "mrcyan", Text = "mrcyan" }, new SelectListItem { Value = "mrblue", Text = "mrblue" }, new SelectListItem { Value = "mrred", Text = "mrred" }, }; } }
#if UNITY_EDITOR using System; using System.Collections.Generic; using UnityEngine; using UnityEditor; using UnityEditor.Experimental.UIElements; public class WingmanMenu : EditorWindow { static List<Wingman> wingmans; static Wingman wingman = new Wingman(); static string[] selStrings; static int selGridInt = 0; static int selGridIntTemp = 0; private bool SaveError = false; private bool SaveErrorTemp = false; [MenuItem("Nova/WingmanEditor", false, 0)] static void Init() { WingmanMenu wingmanMenu = new WingmanMenu(); wingmanMenu.InitValue(); WingmanMenu window = (WingmanMenu)GetWindow(typeof(WingmanMenu)); window.Show(); } public void InitValue() { WingmanJsonLoader loader = new WingmanJsonLoader(); wingmans = loader.LoadData(); selStrings = new string[wingmans.Count]; selGridInt = 0; for (int i = 0; i < wingmans.Count; i++) { selStrings[i] = wingmans[i].Number; } if (wingmans.Count >= 1) { wingman = wingmans[0]; } else { AddWingman(); wingman = wingmans[0]; } } private void OnGUI() { GUILayout.Label("僚机参数", EditorStyles.largeLabel); wingman.Number = EditorGUILayout.TextField("僚机编号", wingman.Number); wingman.Name = EditorGUILayout.TextField("僚机名称", wingman.Name); wingman.Prefab = EditorGUILayout.TextField("所用预设", wingman.Prefab); wingman.iconPath = EditorGUILayout.TextField("图标路径", wingman.iconPath); wingman.Price = EditorGUILayout.IntField("僚机价格", wingman.Price); GUILayout.Label("僚机描述"); wingman.Description = EditorGUILayout.TextArea(wingman.Description); GUILayout.Space(10); GUILayout.Label("稀有度:" + wingman.rareLevel.ToString()); if (GUILayout.Button("稀有度向上")) { wingman.rareLevel++; } if (GUILayout.Button("稀有度向下")) { wingman.rareLevel--; } GUILayout.Space(10); if (GUILayout.Button("新建空僚机")) { AddWingman(); } if (GUILayout.Button("删除该僚机")) { DeleteWingman(); } if (GUILayout.Button("保存此修改")) { SaveWingman(); } GUILayout.Label("僚机列表", EditorStyles.largeLabel); GUILayout.BeginVertical("Box"); selGridIntTemp = selGridInt; selGridInt = GUILayout.SelectionGrid(selGridInt, selStrings, 1); if (selGridInt != selGridIntTemp) { wingman = wingmans[selGridInt]; } GUILayout.EndVertical(); GUILayout.Space(10); } /// <summary> /// 按wingmans刷新展示列表 /// </summary> private void UpadteGUI() { selStrings = new string[wingmans.Count]; for (int i = 0; i < wingmans.Count; i++) selStrings[i] = wingmans[i].Number; wingman = wingmans[0]; //刷新后选中列表第一个僚机 selGridInt = 0; } /// <summary> /// 触发保存修改时所用方法 /// </summary> private void SaveWingman() { SaveErrorTemp = false; for (int i = 0; i < wingmans.Count; i++) { if (wingmans[i].Number == wingman.Number && i != selGridInt) { SaveErrorTemp = true; } } if (wingman.Number == null || wingman.Number == "") { SaveErrorTemp = true; } SaveError = SaveErrorTemp; if (!SaveErrorTemp) { WingmanJsonLoader loader = new WingmanJsonLoader(); loader.SaveData(wingman); //将当前wingman存入json并排序 wingmans = loader.LoadData(); //读取json中已排序的信息 UpadteGUI(); } } /// <summary> /// 触发新建僚机按钮时所用方法, /// </summary> private void AddWingman() { SaveError = false; WingmanJsonLoader loader = new WingmanJsonLoader(); wingman = new Wingman(); //新建一个空白僚机并*暂存*于wingmans列表 wingman.Number = "default"; wingman.Name = "default"; wingman.Prefab = "default"; wingman.iconPath = "default"; wingman.Price = 0; wingman.rareLevel = 0; wingmans.Add(wingman); UpadteGUI(); } /// <summary> /// 触发删除按钮时所用方法,当前选中的僚机将会被删除 /// </summary> private void DeleteWingman() { WingmanJsonLoader loader = new WingmanJsonLoader(); loader.DeleteData(selGridInt,wingmans); wingmans = loader.LoadData(); //读取json中已排序的信息 UpadteGUI(); } } #endif
using GatherBuddy.Interfaces; using GatherBuddy.Plugin; namespace GatherBuddy.Alarms; public partial class AlarmManager { public void ToggleAlarm(AlarmGroup group, int idx) { var alarm = group.Alarms[idx]; if (alarm.Enabled) { alarm.Enabled = false; if (group.Enabled) RemoveActiveAlarm(alarm); } else { alarm.Enabled = true; if (group.Enabled) AddActiveAlarm(alarm); } Save(); } public void MoveAlarm(AlarmGroup group, int idx1, int idx2) { if (Functions.Move(group.Alarms, idx1, idx2)) Save(); } public void DeleteAlarm(AlarmGroup group, int idx) { var alarm = group.Alarms[idx]; if (group.Enabled && alarm.Enabled) RemoveActiveAlarm(alarm); group.Alarms.RemoveAt(idx); Save(); } public void AddAlarm(AlarmGroup group, Alarm value) { group.Alarms.Add(value); if (group.Enabled && value.Enabled) { AddActiveAlarm(value); SetDirty(); } Save(); } public void ChangeAlarmName(AlarmGroup group, int idx, string name) { var alarm = group.Alarms[idx]; if (alarm.Name == name) return; alarm.Name = name; Save(); } public void ChangeAlarmItem(AlarmGroup group, int idx, IGatherable item) { var alarm = group.Alarms[idx]; if (ReferenceEquals(alarm.Item, item)) return; RemoveActiveAlarm(alarm); alarm.Item = item; if (group.Enabled && alarm.Enabled) AddActiveAlarm(alarm); Save(); } public void ChangeAlarmMessage(AlarmGroup group, int idx, bool printMessage) { var alarm = group.Alarms[idx]; if (alarm.PrintMessage == printMessage) return; alarm.PrintMessage = printMessage; Save(); } public void ChangeAlarmSound(AlarmGroup group, int idx, Sounds soundId) { var alarm = group.Alarms[idx]; if (alarm.SoundId == soundId) return; alarm.SoundId = soundId; Save(); } public void ChangeAlarmLocation(AlarmGroup group, int idx, ILocation? location) { var alarm = group.Alarms[idx]; if (alarm.PreferLocation == location) return; RemoveActiveAlarm(alarm); alarm.PreferLocation = location; if (group.Enabled && alarm.Enabled) AddActiveAlarm(alarm); Save(); } public void ChangeAlarmOffset(AlarmGroup group, int idx, int secondOffset) { var alarm = group.Alarms[idx]; if (alarm.SecondOffset == secondOffset) return; RemoveActiveAlarm(alarm); alarm.SecondOffset = secondOffset; if (group.Enabled && alarm.Enabled) AddActiveAlarm(alarm); Save(); } }
using UnityEngine; using System.Collections; public class PlayerExplode : MonoBehaviour { public GameObject explosion; private GameObject player; void Start() { player = GameObject.FindGameObjectWithTag("Player"); } void Update() { if (GameManager.Instance.LoseCondition) { Instantiate(explosion, player.transform.position, Quaternion.identity); } } }
using System; namespace Praetorium.UnitTests.Utilities { class TypeExtensionSpecs { protected static Type NullType = null; } }
/* * Copyright 2018 Samsung Electronics Co., Ltd. All rights reserved. * * Licensed under the Flora License, Version 1.1 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://floralicense.org/license * * 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 SystemInfo.View; using Xamarin.Forms; namespace SystemInfo.Utils { /// <summary> /// Helper class that provides application's pages. /// </summary> public static class PageProvider { #region methods /// <summary> /// Method that provides platform-specific pages. /// </summary> /// <param name="s">Title of page.</param> /// <returns>Returns page by its title. In case of unsupported title empty ContentPage will be returned.</returns> public static Page CreatePage(string s) { switch (s) { case "Battery": return DependencyService.Get<IPageResolver>().BatteryPage; case "Display": return DependencyService.Get<IPageResolver>().DisplayPage; case "USB": return DependencyService.Get<IPageResolver>().UsbPage; case "Capabilities": return DependencyService.Get<IPageResolver>().CapabilitiesPage; case "Settings": return DependencyService.Get<IPageResolver>().SettingsPage; case "LED": return DependencyService.Get<IPageResolver>().LedPage; case "Vibrator": return DependencyService.Get<IPageResolver>().VibratorPage; default: return new ContentPage { Title = "Default " + s }; } } #endregion } }
// 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.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Shell; using System.Threading; using Microsoft.Win32.SafeHandles; using Microsoft.VisualStudio; using System.Diagnostics; using System.Runtime.InteropServices; namespace Microsoft.DebugEngineHost.VSImpl { // Seperate class for waiting using VS interfaces // ************************************************************ // * IMPORTANT: This needs to be a seperate class as when the JIT'er tries to JIT anything in this // * class it may through a FileNotFound exception for the VS assemblies. Do _NOT_ reference the // * VS assemblies from another class. // ************************************************************ internal class VsWaitLoop { private readonly IVsCommonMessagePump _messagePump; private VsWaitLoop(string text) { int hr; var messagePumpFactory = (IVsCommonMessagePumpFactory)Package.GetGlobalService(typeof(SVsCommonMessagePumpFactory)); if (messagePumpFactory == null) { return; // normal case in glass } IVsCommonMessagePump messagePump; hr = messagePumpFactory.CreateInstance(out messagePump); if (hr != 0) return; hr = messagePump.SetAllowCancel(true); if (hr != 0) return; hr = messagePump.SetWaitText(text); if (hr != 0) return; hr = messagePump.SetStatusBarText(string.Empty); if (hr != 0) return; _messagePump = messagePump; } static public VsWaitLoop TryCreate(string text) { VsWaitLoop waitLoop = new VsWaitLoop(text); if (waitLoop._messagePump == null) return null; return waitLoop; } /// <summary> /// Waits on the specified handle using the VS wait UI. /// </summary> /// <param name="launchCompleteHandle">[Required] handle to wait on</param> /// <param name="cancellationSource">[Required] Object to signal cancellation if cancellation is requested</param> /// <returns>true if we were able to successfully wait, false if we failed to wait and should fall back to the CLR provided wait function</returns> /// <exception cref="FileNotFoundException">Thrown by the JIT if Visual Studio is not installed</exception> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods", MessageId = "System.Runtime.InteropServices.SafeHandle.DangerousGetHandle")] public void Wait(WaitHandle launchCompleteHandle, CancellationTokenSource cancellationSource) { int hr; SafeWaitHandle safeWaitHandle = launchCompleteHandle.SafeWaitHandle; bool addRefSucceeded = false; try { safeWaitHandle.DangerousAddRef(ref addRefSucceeded); if (!addRefSucceeded) { throw new ObjectDisposedException("launchCompleteHandle"); } IntPtr nativeHandle = safeWaitHandle.DangerousGetHandle(); IntPtr[] handles = { nativeHandle }; uint waitResult; hr = _messagePump.ModalWaitForObjects(handles, (uint)handles.Length, out waitResult); if (hr == 0) { return; } else if (hr == VSConstants.E_PENDING || hr == VSConstants.E_ABORT) { // E_PENDING: user canceled // E_ABORT: application exit cancellationSource.Cancel(); throw new OperationCanceledException(); } else { Debug.Fail("Unexpected result from ModalWaitForObjects"); Marshal.ThrowExceptionForHR(hr); } } finally { if (addRefSucceeded) { safeWaitHandle.DangerousRelease(); } } } public void SetProgress(int totalSteps, int currentStep, string progressText) { _messagePump.SetProgressInfo(totalSteps, currentStep, progressText); } public void SetText(string text) { _messagePump.SetWaitText(text); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; namespace AuxiliaryLibraries.WPF.Interactivity { public class ActionCollection : AttachableCollection<ActionBase> { public ActionCollection() { } protected override void OnAttached() { } protected override void OnDetaching() { } internal override void ItemAdded(ActionBase item) { } internal override void ItemRemoved(ActionBase item) { } } }
using Godot; using System; using static Godot.Mathf; public class Starfield : Spatial { private MeshInstance SingleStar; private static PackedScene StarScene; static Starfield() { if(Engine.EditorHint) {return;} StarScene = GD.Load<PackedScene>("res://World/Star.tscn"); } public override void _Ready() { for(int i = 0; i < 1000; i++) { SingleStar = (MeshInstance) StarScene.Instance(); AddChild(SingleStar); Vector3 Pos = new Vector3( (float)Game.Rand.NextDouble()/2f * Game.Rand.RandomSign(), (float)Game.Rand.NextDouble()/2f, (float)Game.Rand.NextDouble()/2f * Game.Rand.RandomSign() ); float Distance = 43_000f + (float)(Game.Rand.NextDouble() * 15_000d) * Game.Rand.RandomSign(); Pos = Pos.Normalized() * Distance; SingleStar.Translation = Pos; } } public override void _Process(float Delta) { Camera Cam = GetViewport().GetCamera(); if(Cam != null) Translation = Cam.GlobalTransform.origin; SpatialMaterial Mat = ((SpatialMaterial) SingleStar.GetSurfaceMaterial(0)); Color Old = Mat.AlbedoColor; if(World.TimeOfDay > 0 && World.TimeOfDay < 30f*World.DayNightMinutes) //Daytime Mat.AlbedoColor = new Color(Old.r, Old.g, Old.b, 0); else { float Power = 0; if(World.TimeOfDay < 45f * World.DayNightMinutes) { //After sunset Power = (World.TimeOfDay - (30f * World.DayNightMinutes)) / (18f * World.DayNightMinutes); Power = Clamp(Power, 0, 1); } else { //Before sunrise Power = Abs(World.TimeOfDay - (60f * World.DayNightMinutes)) / (18f * World.DayNightMinutes); Power = Clamp(Power, 0, 1); } Mat.AlbedoColor = new Color(Old.r, Old.g, Old.b, Clamp(Power, 0, 1)); } } }
using System; using MIDIKeyboard.dataFolder; using MIDIKeyboard.Miscellaneous; namespace MIDIKeyboard.Run { internal class Run { private static readonly InputPort midi = new InputPort(); public static void Run_(ref bool runPogram) { int chanel = 0; bool error = false; //load data if (Program.values.Count < 1 || Settings.data.force_load_data_on_run) error = LoadData.Load(Settings.data.key_data_path); else Console.WriteLine("Data already loaded in memory..."); string[] valuesHex = new string[Program.values.Count]; for (int i = 0; i < Program.values.Count; i++) valuesHex[i] = Program.values[i][0].ToString("X").PadLeft(4, '0'); midi.Open(chanel); midi.Start(); if (!error) Console.ForegroundColor = ConsoleColor.Yellow; else Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("\nRuning..."); Console.ResetColor(); Console.WriteLine("Press escape to exit.\n"); //run application loop AppLoop(ref runPogram, valuesHex); //stop and clsoe MIDI port. midi.Stop(); midi.Close(); Program.teken = 0; //remove color LoadData.SendOutputDataZero(); } private static void AppLoop(ref bool runPogram, string[] valuesHex) { int oldValue = 0; while (runPogram) { if (Console.KeyAvailable && Console.ReadKey().Key == ConsoleKey.Escape) { runPogram = false; return; } if (Program.waitHandle.WaitOne(1000)) { int value = midi.p; if (oldValue != value) { string valueHex = midi.pS; string valueHex4 = valueHex.Substring(valueHex.Length - 4); if (valueHex.Substring(valueHex.Length - 2) != "D0") { int lenght = Program.values.Count; for (int lineIndex = 0; lineIndex < lenght; lineIndex++) if (valuesHex[lineIndex] == valueHex4) { if (Program.values[lineIndex][1] == 0) { // key KeyMode.Key(lineIndex, valueHex); break; } if (Program.values[lineIndex][1] == 2) { // addonkey KeyMode.Addonkey(lineIndex, valueHex); break; } if (Program.values[lineIndex][1] == 1) { // macro KeyMode.Macro(lineIndex, valueHex); break; } } } Console.WriteLine(valueHex + "\n"); oldValue = value; } } Program.waitHandle.Reset(); } } } }
using Creeper.Driver; using Creeper.SqlServer.Test.Entity.Model; using Microsoft.Data.SqlClient; using Microsoft.SqlServer.Types; using System; using System.ComponentModel; using System.Data; using System.IO; using System.Text; using Xunit; namespace Creeper.xUnitTest.SqlServer { public class CLRTest : BaseTest { private const int Id = 11; [Fact] public void Insert() { var info = Context.Insert(new TypeTestModel { BigintType = 10, BinaryType = new byte[] { 1, 234 }, BitType = false, CharType = "中国", DateTimeType = DateTime.Now, DateTime2Type = DateTime.Now, DateType = DateTime.Today, FloatType = 234.2D, NumericType = 12.3M, RealType = 12.3F, SmallIntType = 123, TextType = "中国", TimeType = DateTime.Now.TimeOfDay, TinyIntType = 10, VarbinaryType = new byte[] { 1, 234 }, VarcharType = "中国", DateTimeOffsetType = DateTimeOffset.Now, DecimalType = 12.3M, ImageType = new byte[] { 1, 234 }, IntType = 123, MoneyType = 12.3M, NcharType = "中国", NtextType = "中国", NvarcharType = "中国", SmallDateTimeType = DateTime.Now, SmallMoneyType = 12.3M, UniqueIdentifierType = Guid.NewGuid(), XmlType = "<name>中国</name>", TimestampType = BitConverter.GetBytes(DateTimeOffset.Now.ToUnixTimeMilliseconds()), SqlVariantType = 1, }); } /// <summary> /// <see cref="SqlDbType.BigInt"/> /// </summary> /// <param name="value"></param> [Theory] [InlineData(long.MaxValue)] public void Bitint(long value) { var obj = Context.Select<TypeTestModel>(a => a.Id == Id).FirstOrDefault<object>(a => a.BigintType); Assert.IsType<long>(obj); var result = Context.Update<TypeTestModel>(a => a.Id == Id).Set(a => a.BigintType, value).ToAffrows(); Assert.Equal(1, result); //Assert.Equal(1, result.AffectedRows); //Assert.Equal(l, result.Value.BigintType); } /// <summary> /// <see cref="SqlDbType.NVarChar"/> /// </summary> /// <param name="value"></param> [Theory] [InlineData("中国")] public void Nvarchar(string value) { var obj = Context.Select<TypeTestModel>(a => a.Id == Id).FirstOrDefault<object>(a => a.NvarcharType); Assert.IsType<string>(obj); var result = Context.Update<TypeTestModel>(a => a.Id == Id).Set(a => a.NvarcharType, value).ToAffrows(); Assert.Equal(1, result); } /// <summary> /// <see cref="SqlDbType.Bit"/> /// </summary> /// <param name="valueS"></param> [Theory] [InlineData(false)] public void Bit(bool value) { var obj = Context.Select<TypeTestModel>(a => a.Id == Id).FirstOrDefault<object>(a => a.BitType); Assert.IsType<bool>(obj); var result = Context.Update<TypeTestModel>(a => a.Id == Id).Set(a => a.BitType, value).ToAffrows(); Assert.Equal(1, result); } /// <summary> /// <see cref="SqlDbType.Binary"/> /// </summary> /// <param name="value"></param> [Theory] [InlineData(new byte[] { 1, 242, 213 })] public void Binary(byte[] value) { var obj = Context.Select<TypeTestModel>(a => a.Id == Id).FirstOrDefault<object>(a => a.BinaryType); Assert.IsType<byte[]>(obj); var result = Context.Update<TypeTestModel>(a => a.Id == Id).Set(a => a.BinaryType, value).ToAffrows(); Assert.Equal(1, result); } /// <summary> /// <see cref="SqlDbType.Char"/> /// </summary> /// <param name="value"></param> [Theory] [InlineData("中国")] public void Char(string value) { var obj = Context.Select<TypeTestModel>(a => a.Id == Id).FirstOrDefault<object>(a => a.CharType); Assert.IsType<string>(obj); var result = Context.Update<TypeTestModel>(a => a.Id == Id).Set(a => a.CharType, value).ToAffrows(); Assert.Equal(1, result); } /// <summary> /// <see cref="SqlDbType.Date"/> /// </summary> /// <param name="value"></param> [Theory] [InlineData("2021-1-1")] public void DateType(DateTime value) { var obj = Context.Select<TypeTestModel>(a => a.Id == Id).FirstOrDefault<object>(a => a.DateType); Assert.IsType<DateTime>(obj); var result = Context.Update<TypeTestModel>(a => a.Id == Id).Set(a => a.DateType, value).ToAffrows(); Assert.Equal(1, result); } /// <summary> /// <see cref="SqlDbType.DateTime"/> /// </summary> /// <param name="value"></param> [Theory] [InlineData("2021-1-1 20:00:00.23475")]//实际结果是: 2021-01-01 20:00:00.233 public void DateTimeType(DateTime value) { var obj = Context.Select<TypeTestModel>(a => a.Id == Id).FirstOrDefault<object>(a => a.DateTimeType); Assert.IsType<DateTime>(obj); var result = Context.Update<TypeTestModel>(a => a.Id == Id).Set(a => a.DateTimeType, value).ToAffrows(); Assert.Equal(1, result); } /// <summary> /// <see cref="SqlDbType.DateTime2"/> /// </summary> /// <param name="value"></param> [Theory] [InlineData("2021-1-1 20:00:00.6623566")]//实际结果是: 2021-01-01 20:00:00.6633333 public void DateTime2(DateTime value) { var obj = Context.Select<TypeTestModel>(a => a.Id == Id).FirstOrDefault<object>(a => a.DateTime2Type); Assert.IsType<DateTime>(obj); var result = Context.Update<TypeTestModel>(a => a.Id == Id).Set(a => a.DateTime2Type, value).ToAffrows(); Assert.Equal(1, result); } /// <summary> /// <see cref="SqlDbType.DateTimeOffset"/> /// </summary> /// <param name="value"></param> [Theory] [InlineData("2021-1-1 20:00:00.6683425+08:00")]//实际结果是: 2021-01-01 20:00:00.6683425 +08:00 public void DateTimeOffsetType(DateTimeOffset value) { var obj = Context.Select<TypeTestModel>(a => a.Id == Id).FirstOrDefault<object>(a => a.DateTimeOffsetType); Assert.IsType<DateTimeOffset>(obj); var result = Context.Update<TypeTestModel>(a => a.Id == Id).Set(a => a.DateTimeOffsetType, value).ToAffrows(); Assert.Equal(1, result); } /// <summary> /// <see cref="SqlDbType.Decimal"/> /// </summary> /// <param name="value"></param> [Theory] [InlineData(231.231)] public void Decimal(decimal value) { var obj = Context.Select<TypeTestModel>(a => a.Id == Id).FirstOrDefault<object>(a => a.DecimalType); Assert.IsType<decimal>(obj); var result = Context.Update<TypeTestModel>(a => a.Id == Id).Set(a => a.DecimalType, value).ToAffrows(); Assert.Equal(1, result); } /// <summary> /// <see cref="SqlDbType.Float"/> /// </summary> /// <param name="value"></param> [Theory] [InlineData(231.231D)] public void Float(double value) { var obj = Context.Select<TypeTestModel>(a => a.Id == Id).FirstOrDefault<object>(a => a.FloatType); Assert.IsType<double>(obj); var result = Context.Update<TypeTestModel>(a => a.Id == Id).Set(a => a.FloatType, value).ToAffrows(); Assert.Equal(1, result); } /// <summary> /// /// </summary> /// <param name="value"></param> [Fact] [Description("暂不支持此类型, 或以下面方式获取")] public void Geography() { SqlGeography geography = SqlGeography.Null; Context.ExecuteReader(dr => { var sqlDr = (SqlDataReader)dr; geography = SqlGeography.Deserialize(sqlDr.GetSqlBytes(0)); }, "select geographytype from typetest where id = 11"); ////Assert.IsType<object>(obj); //var result = Context.Update<TypeTestModel>(a => a.Id == Id).Set(a => a.GeographyType, value).ToAffrows(); //Assert.Equal(1, result); } /// <summary> /// /// </summary> /// <param name="value"></param> [Fact] [Description("暂不支持此类型, 或以下面方式获取")] public void Geometry() { SqlGeometry geometry = SqlGeometry.Null; Context.ExecuteReader(dr => { var sqlDr = (SqlDataReader)dr; geometry = SqlGeometry.Deserialize(sqlDr.GetSqlBytes(0)); }, "select geometrytype from typetest where id = 11"); //var obj = Context.Select<TypeTestModel>(a => a.Id == Id).FirstOrDefault<object>(a => a.GeographyType); //Assert.IsType<object>(obj); //var result = Context.Update<TypeTestModel>(a => a.Id == Id).Set(a => a.GeographyType, value).ToAffrows(); //Assert.Equal(1, result); } /// <summary> /// /// </summary> /// <param name="value"></param> [Fact] [Description("暂不支持此类型")] public void Hierarchyid() { //var obj = Context.Select<TypeTestModel>(a => a.Id == Id).FirstOrDefault<object>(a => a.HierarchyidType); //Assert.IsType<object>(obj); //var result = Context.Update<TypeTestModel>(a => a.Id == Id).Set(a => a.HierarchyidType, value).ToAffrows(); //Assert.Equal(1, result); } /// <summary> /// <see cref="SqlDbType.Image"/> /// </summary> /// <param name="value"></param> [Theory] [InlineData(new byte[] { 1, 242, 213 })] public void Image(byte[] value) { var obj = Context.Select<TypeTestModel>(a => a.Id == Id).FirstOrDefault<object>(a => a.ImageType); Assert.IsType<byte[]>(obj); var result = Context.Update<TypeTestModel>(a => a.Id == Id).Set(a => a.ImageType, value).ToAffrows(); Assert.Equal(1, result); } /// <summary> /// <see cref="SqlDbType.Int"/> /// </summary> /// <param name="value"></param> [Theory] [InlineData(99)] public void Int(int value) { var obj = Context.Select<TypeTestModel>(a => a.Id == Id).FirstOrDefault<object>(a => a.IntType); Assert.IsType<int>(obj); var result = Context.Update<TypeTestModel>(a => a.Id == Id).Set(a => a.IntType, value).ToAffrows(); Assert.Equal(1, result); } /// <summary> /// <see cref="SqlDbType.Money"/> /// </summary> /// <param name="value"></param> [Theory] [InlineData(245.243)] public void Money(decimal value) { var obj = Context.Select<TypeTestModel>(a => a.Id == Id).FirstOrDefault<object>(a => a.MoneyType); Assert.IsType<decimal>(obj); var result = Context.Update<TypeTestModel>(a => a.Id == Id).Set(a => a.MoneyType, value).ToAffrows(); Assert.Equal(1, result); } /// <summary> /// <see cref="SqlDbType.NChar"/> /// </summary> /// <param name="value"></param> [Theory] [InlineData("中国")] public void Nchar(string value) { var obj = Context.Select<TypeTestModel>(a => a.Id == Id).FirstOrDefault<object>(a => a.NcharType); Assert.IsType<string>(obj); var result = Context.Update<TypeTestModel>(a => a.Id == Id).Set(a => a.NcharType, value).ToAffrows(); Assert.Equal(1, result); } /// <summary> /// <see cref="SqlDbType.NText"/> /// </summary> /// <param name="value"></param> [Theory] [InlineData("中国")] public void Ntext(string value) { var obj = Context.Select<TypeTestModel>(a => a.Id == Id).FirstOrDefault<object>(a => a.NtextType); Assert.IsType<string>(obj); var result = Context.Update<TypeTestModel>(a => a.Id == Id).Set(a => a.NtextType, value).ToAffrows(); Assert.Equal(1, result); } /// <summary> /// /// </summary> /// <param name="value"></param> [Theory] [InlineData(35.03577)] //实际结果: 35.04 public void Numeric(decimal value) { var obj = Context.Select<TypeTestModel>(a => a.Id == Id).FirstOrDefault<object>(a => a.NumericType); Assert.IsType<decimal>(obj); var result = Context.Update<TypeTestModel>(a => a.Id == Id).Set(a => a.NumericType, value).ToAffrows(); Assert.Equal(1, result); } /// <summary> /// <see cref="SqlDbType.Real"/> /// </summary> /// <param name="value"></param> [Theory] [InlineData(35.03577f)] //实际结果: 35.04 public void Real(float value) { var obj = Context.Select<TypeTestModel>(a => a.Id == Id).FirstOrDefault<object>(a => a.RealType); Assert.IsType<float>(obj); var result = Context.Update<TypeTestModel>(a => a.Id == Id).Set(a => a.RealType, value).ToAffrows(); Assert.Equal(1, result); } /// <summary> /// <see cref="SqlDbType.SmallDateTime"/> /// </summary> /// <param name="value"></param> [Theory] [InlineData("2021-1-1 20:03:29.6623566")]//实际结果是: 2021-01-01 20:03:00 public void SmallDateTime(DateTime value) { var obj = Context.Select<TypeTestModel>(a => a.Id == Id).FirstOrDefault<object>(a => a.SmallDateTimeType); Assert.IsType<DateTime>(obj); var result = Context.Update<TypeTestModel>(a => a.Id == Id).Set(a => a.SmallDateTimeType, value).ToAffrows(); Assert.Equal(1, result); } /// <summary> /// <see cref="SqlDbType.SmallInt"/> /// </summary> /// <param name="value"></param> [Theory] [InlineData(short.MaxValue)] public void SmallInt(short value) { var obj = Context.Select<TypeTestModel>(a => a.Id == Id).FirstOrDefault<object>(a => a.SmallIntType); Assert.IsType<short>(obj); var result = Context.Update<TypeTestModel>(a => a.Id == Id).Set(a => a.SmallIntType, value).ToAffrows(); Assert.Equal(1, result); } /// <summary> /// <see cref="SqlDbType.SmallMoney"/> /// </summary> /// <param name="value"></param> [Theory] [InlineData(123.125)] public void SmallMoney(decimal value) { var obj = Context.Select<TypeTestModel>(a => a.Id == Id).FirstOrDefault<object>(a => a.SmallMoneyType); Assert.IsType<decimal>(obj); var result = Context.Update<TypeTestModel>(a => a.Id == Id).Set(a => a.SmallMoneyType, value).ToAffrows(); Assert.Equal(1, result); } /// <summary> /// /// </summary> /// <param name="value"></param> [Fact] public void SqlVariant() { var obj = Context.Select<TypeTestModel>(a => a.Id == Id).FirstOrDefault<object>(a => a.SqlVariantType); var result = Context.Update<TypeTestModel>(a => a.Id == Id).Set(a => a.SqlVariantType, "中国").ToAffrows(); Assert.Equal(1, result); } /// <summary> /// <see cref="SqlDbType.Text"/> /// </summary> /// <param name="value"></param> [Theory] [InlineData("中国")] public void Text(string value) { var obj = Context.Select<TypeTestModel>(a => a.Id == Id).FirstOrDefault<object>(a => a.TextType); Assert.IsType<string>(obj); var result = Context.Update<TypeTestModel>(a => a.Id == Id).Set(a => a.TextType, value).ToAffrows(); Assert.Equal(1, result); } /// <summary> /// <see cref="SqlDbType.Time"/> /// </summary> /// <param name="value"></param> [Fact] public void Time() { TimeSpan value = TimeSpan.Parse("20:24:53.2343155"); var obj = Context.Select<TypeTestModel>(a => a.Id == Id).FirstOrDefault<object>(a => a.TimeType); Assert.IsType<TimeSpan>(obj); var result = Context.Update<TypeTestModel>(a => a.Id == Id).Set(a => a.TimeType, value).ToAffrows(); Assert.Equal(1, result); } /// <summary> /// <see cref="SqlDbType.Timestamp"/> /// </summary> /// <param name="value"></param> [Fact] public void Timestamp() { var obj = Context.Select<TypeTestModel>(a => a.Id == Id).FirstOrDefault<object>(a => a.TimestampType); Assert.IsType<byte[]>(obj); //不能更新时间戳列。 Assert.ThrowsAny<Creeper.CreeperException>(() => { var result = Context.Update<TypeTestModel>(a => a.Id == Id) .Set(a => a.TimestampType, BitConverter.GetBytes(DateTimeOffset.Now.ToUnixTimeMilliseconds())) .ToAffrows(); }); } /// <summary> /// <see cref="SqlDbType.TinyInt"/> /// </summary> /// <param name="value"></param> [Theory] [InlineData(90)] public void TinyInt(byte value) { var obj = Context.Select<TypeTestModel>(a => a.Id == Id).FirstOrDefault<object>(a => a.TinyIntType); Assert.IsType<byte>(obj); var result = Context.Update<TypeTestModel>(a => a.Id == Id).Set(a => a.TinyIntType, value).ToAffrows(); Assert.Equal(1, result); } /// <summary> /// <see cref="SqlDbType.UniqueIdentifier"/> /// </summary> /// <param name="value"></param> [Theory] [InlineData("efa09cb0-aa7a-4ba8-b412-6aee707daa91")] public void UniqueIdentifier(Guid value) { var obj = Context.Select<TypeTestModel>(a => a.Id == Id).FirstOrDefault<object>(a => a.UniqueIdentifierType); Assert.IsType<Guid>(obj); var result = Context.Update<TypeTestModel>(a => a.Id == Id).Set(a => a.UniqueIdentifierType, value).ToAffrows(); Assert.Equal(1, result); } /// <summary> /// <see cref="SqlDbType.VarBinary"/> /// </summary> /// <param name="value"></param> [Theory] [InlineData(new byte[] { 1, 242, 213 })] public void VarBinary(byte[] value) { var obj = Context.Select<TypeTestModel>(a => a.Id == Id).FirstOrDefault<object>(a => a.VarbinaryType); Assert.IsType<byte[]>(obj); var result = Context.Update<TypeTestModel>(a => a.Id == Id).Set(a => a.VarbinaryType, value).ToAffrows(); Assert.Equal(1, result); } /// <summary> /// <see cref="SqlDbType.VarChar"/> /// </summary> /// <param name="value"></param> [Theory] [InlineData("中国")] public void Varchar(string value) { var obj = Context.Select<TypeTestModel>(a => a.Id == Id).FirstOrDefault<object>(a => a.VarcharType); Assert.IsType<string>(obj); var result = Context.Update<TypeTestModel>(a => a.Id == Id).Set(a => a.VarcharType, value).ToAffrows(); Assert.Equal(1, result); } /// <summary> /// <see cref="SqlDbType.Xml"/> /// </summary> /// <param name="value"></param> [Theory] [InlineData("<testxml>Title</testxml>")] public void Xml(string value) { var obj = Context.Select<TypeTestModel>(a => a.Id == Id).FirstOrDefault<object>(a => a.XmlType); Assert.IsType<string>(obj); var result = Context.Update<TypeTestModel>(a => a.Id == Id).Set(a => a.XmlType, value).ToAffrows(); Assert.Equal(1, result); } } }
using Foundation; using System; using System.CodeDom.Compiler; using UIKit; using CoreGraphics; namespace Mailbox { partial class TableViewController : UITableViewController { EmailServer emailServer = new EmailServer(); public TableViewController (IntPtr handle) : base (handle) { } public override nint RowsInSection(UITableView tableview, nint section) { return emailServer.Email.Count; } public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath) { UITableViewCell cell = new UITableViewCell(CGRect.Empty); var item = emailServer.Email[indexPath.Row]; cell.TextLabel.Text = item.Subject; return cell; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; //using UnityEditor; using System.Text.RegularExpressions; public class PosEntry { public float time; public Vector3 pos; public int id; public int meshnum; } public class CsvParser : MonoBehaviour { public TextAsset csvFile; List <PosEntry> lst=new List<PosEntry>(); // Use this for initialization PosEntry entryFromLine(string line) { Regex CSVParser = new Regex(",(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))"); string[] X = CSVParser.Split(line); PosEntry ret=new PosEntry(); ret.time=float.Parse(X[1]); ret.pos=new Vector3(float.Parse(X[2]),float.Parse(X[3]),float.Parse(X[4])); ret.id=int.Parse(X[5]); ret.meshnum=int.Parse(X[6]); return ret; } void Start () { string meshPath="Assets/csmesh800/cmesh800_"; string fs = csvFile.text; string[] fLines = Regex.Split ( fs, "\n|\r|\r\n" ); int cnt=0; int curMesh=-1; int curId=-1; List<Vector3> verts = new List<Vector3>(); List<Vector2> uvs = new List<Vector2>(); List<Color> clrs = new List<Color>(); List<int> indc = new List<int>(); Mesh curM=null; Vector3 avg=Vector3.zero; float mintime=-1; float maxtime=-1; foreach(string line in fLines) { if(line.Length<2) continue; PosEntry en=entryFromLine(line); lst.Add(en); cnt++; avg+=en.pos; if(maxtime<0||en.time>maxtime) maxtime=en.time; if(mintime<0||en.time<mintime) mintime=en.time; /* if(curMesh!=en.meshnum) { if(curM!=null) { AssetDatabase.CreateAsset(curM, "Assets/csmesh/cmesh_" + curMesh.ToString() + ".asset"); } } if(curMesh==-1) curMesh=en.meshnum; if(curId==-1) curId=en.id; cnt++; if(cnt>100) break;*/ } Debug.Log(mintime); Debug.Log(maxtime); Debug.Log(avg/cnt); avg/=(float)cnt; cnt=0; float td=maxtime-mintime; foreach(PosEntry en in lst) { if(curMesh!=en.meshnum) { //if(curM!=null) // { // curM.vertices=verts.ToArray(); // curM.uv=uvs.ToArray(); // curM.colors=clrs.ToArray(); // curM.SetIndices(indc.ToArray(),MeshTopology.Lines,0); //AssetDatabase.CreateAsset(curM, meshPath + curMesh.ToString() + ".asset"); //} verts.Clear(); uvs.Clear(); clrs.Clear(); indc.Clear(); curMesh=en.meshnum; curM=new Mesh(); cnt=0; } if(curId==en.id) { indc.Add(cnt-1); indc.Add(cnt); } else curId=en.id; verts.Add(en.pos-avg); float shft=(en.time-mintime)/td; uvs.Add(new Vector2(shft,0)); clrs.Add( Color.Lerp(Color.red, Color.green, shft)); cnt++; } //if(curM!=null) // { // curM.vertices=verts.ToArray(); // curM.uv=uvs.ToArray(); // curM.colors=clrs.ToArray(); // curM.SetIndices(indc.ToArray(),MeshTopology.Lines,0); // AssetDatabase.CreateAsset(curM, meshPath + curMesh.ToString() + ".asset"); // } // } // Update is called once per frame void Update () { } }
namespace RefactoringGuru.Creational.AbstractFactory.Interfaces { public interface IAbstractProductA { public string UsefulFunctionA(); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Mecanim : MonoBehaviour { void Start() { } public void SetupRagdoll(bool whatever) { Component[] components = GetComponentsInChildren(typeof(Transform)); foreach(Component c in components) { if(c.GetComponent<Rigidbody>() != null) { c.GetComponent<Rigidbody>().isKinematic = whatever; } } } }
using Microsoft.AspNetCore.Http; namespace AS91892.Data.Validation; /// <summary> /// Valites that a property meets a specified file size /// </summary> public class MaxFileSizeAttribute : ValidationAttribute { private readonly int _maxFileSize; /// <summary> /// Initializes a new instance of the <see cref="MaxFileSizeAttribute"/> class /// </summary> public MaxFileSizeAttribute(int maxFileSize) { _maxFileSize = maxFileSize; } /// <inheritdoc></inheritdoc> protected override ValidationResult? IsValid(object? value, ValidationContext validationContext) { var file = value as IFormFile; if (file is not null) { if (file.Length > _maxFileSize) // check if the file is larger than the max { return new ValidationResult(GetErrorMessage()); } } return ValidationResult.Success; } private string GetErrorMessage() { return $"Maximum allowed file size is { _maxFileSize} bytes."; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Paddle : MonoBehaviour { [SerializeField] float speed; public string input; private float height; void Start() { height = GetComponent<Collider2D>().bounds.size.y; } // Constructor public void Init(string player) { // Set paddle to player input = player; // Change paddle name to player name transform.name = player; } // Update is called once per frame void Update () { // Get velocity based on input float velocity = Input.GetAxis(input) * Time.deltaTime * speed; // Clamp movement to screen space if ((transform.position.y < GameManager.instance.bottomLeft.y + height / 2 && velocity < 0) || (transform.position.y > GameManager.instance.topRight.y - height / 2 && velocity > 0)) { velocity = 0; } // Move paddle transform.Translate(velocity * Vector2.up); } }
using System; using System.Threading; using System.Threading.Tasks; namespace Dfe.Spi.HistoricalDataCapture.Domain.UkrlpClient { public interface IUkrlpClient { Task<byte[]> GetChangesSinceAsync(DateTime sinceTime, string status, CancellationToken cancellationToken); } }
namespace AgroPlan.Property.AgroPlan.Property.Infrastructure.DbConnections { public sealed class QueryConnection { public QueryConnection(string connectionString) { this.Value = connectionString; } public string Value { get; private set;} } }
namespace Turbo.Events.Model { public interface IOnScopedEvent { void On(ScopedEvent e); } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace TestPanda.Api.DomainEntities { public class TestRun { [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int TestRunId { get; private set; } [Required] [MaxLength(50)] public string Title { get; private set; } public TestUser Tester { get; private set; } public IEnumerable<TestPlan> TestPlans { get; private set; } } }
using System; using System.Collections.Generic; using System.Text; public class InvalidSongLengthException : InvalidSongException { public InvalidSongLengthException() { } public InvalidSongLengthException(int seconds , int minutes) : base(seconds , minutes) { this.Seconds = seconds; this.Minutes = minutes; ValidateLenght(seconds, minutes); } private static void ValidateLenght(int seconds, int minutes) { if ((seconds < 0 || seconds > 59) && minutes > 14) { throw new ArgumentException("Invalid song length."); } } }
using ExplicitInterfaces.Contracts; using System; using System.Collections.Generic; namespace ExplicitInterfaces { public class StartUp { static void Main(string[] args) { string text = string.Empty; while ((text = Console.ReadLine()) != "End") { string[] input = text .Split(" ", StringSplitOptions.RemoveEmptyEntries); string name = input[0]; string country = input[1]; int age = int.Parse(input[2]); Citizen citizen = new Citizen(name,country,age); Console.WriteLine(citizen.GetName()); Console.WriteLine(((IResident)citizen).GetName()); } } } }
namespace Assets.Scripts.Xml { public interface IXmlDataProvider { string SerializeObject<T>(object obj); object DeserializeObject<T>(string xmlString); void CreateXmlFileOutput(string fileLocation, string fileName, string data); string LoadDataFromXml(string fileLocation, string fileName); } }
namespace Genbox.SimpleS3.Core.Internals.Enums; internal enum DateTimeFormat { Unknown = 0, Iso8601Date, Iso8601DateTime, Iso8601DateTimeExt, Rfc1123 }
#region Using directives using SimpleFramework.Xml; using System; #endregion namespace SimpleFramework.Xml.Core { public class NamespaceInheritanceTest : ValidationTestCase { [Namespace(Reference="namespace1")] private static class Aaa { [Element(Name="bbb", Required=false)] public Bbb bbb; } [Namespace(Reference="namespace2")] private static class Bbb { [Element(Name="aaa", Required=false)] public Aaa aaa; } [Namespace(Prefix="aaa", Reference="namespace1")] private static class AaaWithPrefix { [Element(Name="bbb", Required=false)] public BbbWithPrefix bbb; } [Namespace(Prefix="bbb", Reference="namespace2")] private static class BbbWithPrefix { [Element(Name="aaa", Required=false)] public AaaWithPrefix aaa; } public void TestNamespace() { Aaa parent = new Aaa(); Bbb child = new Bbb(); parent.bbb = child; Aaa grandchild = new Aaa(); child.aaa = grandchild; grandchild.bbb = new Bbb(); ByteArrayOutputStream tmp = new ByteArrayOutputStream(); Serializer serializer = new Persister(); serializer.write(parent, tmp); String result = new String(tmp.toByteArray()); System.out.println(result); assertElementHasAttribute(result, "/aaa", "xmlns", "namespace1"); assertElementHasAttribute(result, "/aaa/bbb", "xmlns", "namespace2"); assertElementHasAttribute(result, "/aaa/bbb/aaa", "xmlns", "namespace1"); assertElementHasAttribute(result, "/aaa/bbb/aaa/bbb", "xmlns", "namespace2"); assertElementHasNamespace(result, "/aaa", "namespace1"); assertElementHasNamespace(result, "/aaa/bbb", "namespace2"); assertElementHasNamespace(result, "/aaa/bbb/aaa", "namespace1"); assertElementHasNamespace(result, "/aaa/bbb/aaa/bbb", "namespace2"); } public void TestNamespacePrefix() { AaaWithPrefix parent = new AaaWithPrefix(); BbbWithPrefix child = new BbbWithPrefix(); parent.bbb = child; AaaWithPrefix grandchild = new AaaWithPrefix(); child.aaa = grandchild; grandchild.bbb = new BbbWithPrefix(); ByteArrayOutputStream tmp = new ByteArrayOutputStream(); Serializer serializer = new Persister(); serializer.write(parent, tmp); String result = new String(tmp.toByteArray()); System.out.println(result); assertElementHasAttribute(result, "/aaaWithPrefix", "xmlns:aaa", "namespace1"); assertElementHasAttribute(result, "/aaaWithPrefix/bbb", "xmlns:bbb", "namespace2"); assertElementDoesNotHaveAttribute(result, "/aaaWithPrefix/bbb/aaa", "xmlns:aaa", "namespace1"); assertElementDoesNotHaveAttribute(result, "/aaaWithPrefix/bbb/aaa/bbb", "xmlns:bbb", "namespace2"); assertElementHasNamespace(result, "/aaaWithPrefix", "namespace1"); assertElementHasNamespace(result, "/aaaWithPrefix/bbb", "namespace2"); assertElementHasNamespace(result, "/aaaWithPrefix/bbb/aaa", "namespace1"); assertElementHasNamespace(result, "/aaaWithPrefix/bbb/aaa/bbb", "namespace2"); } } }
using System; using Microsoft.AspNetCore.Cryptography.KeyDerivation; namespace Ocelot.Configuration.Authentication { public class HashMatcher : IHashMatcher { public bool Match(string password, string salt, string hash) { byte[] s = Convert.FromBase64String(salt); string hashed = Convert.ToBase64String(KeyDerivation.Pbkdf2( password: password, salt: s, prf: KeyDerivationPrf.HMACSHA256, iterationCount: 10000, numBytesRequested: 256 / 8)); return hashed == hash; } } }
using System.Windows; namespace ModernWpf.Controls.Primitives { public static class ScrollViewerHelper { #region AutoHideScrollBars public static readonly DependencyProperty AutoHideScrollBarsProperty = DependencyProperty.RegisterAttached( "AutoHideScrollBars", typeof(bool), typeof(ScrollViewerHelper)); public static bool GetAutoHideScrollBars(DependencyObject element) { return (bool)element.GetValue(AutoHideScrollBarsProperty); } public static void SetAutoHideScrollBars(DependencyObject element, bool value) { element.SetValue(AutoHideScrollBarsProperty, value); } #endregion } }
using Quartz; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Timer.Web.Core.Models { public class KeyVM { public KeyVM(JobKey jobKey) { Name = jobKey.Name; Group = jobKey.Group; } public KeyVM(TriggerKey triggerKey) { Name = triggerKey.Name; Group = triggerKey.Group; } public string Name { get; private set; } public string Group { get; private set; } } }
using System.Collections.Generic; namespace GeoAPI.Geometries { public interface IGeometryCollection : IGeometry, IEnumerable<IGeometry> { int Count { get; } IGeometry[] Geometries { get; } IGeometry this[int i] { get; } bool IsHomogeneous { get; } } }
using System; using System.Collections.Generic; using System.Linq; using Newtonsoft.Json; namespace EsriJson.Net.Geometry { [JsonObject(MemberSerialization.OptIn)] public class Polyline : EsriJsonObject { [JsonProperty(PropertyName = "paths", Required = Required.Always)] public List<RingPoint[]> Paths { get; set; } public Polyline(List<RingPoint[]> paths) { ValidatePaths(paths); Paths = paths; } public Polyline() { Paths = new List<RingPoint[]>(); } private static void ValidatePaths(IEnumerable<RingPoint[]> paths) { if (paths == null) throw new ArgumentNullException("paths"); if (paths.Select(point => point.Length).Any(length => length < 2)) { throw new ArgumentException("Paths are made up of two or more points. Yours has less."); } } public void AddPath(List<RingPoint[]> paths) { ValidatePaths(paths); foreach (var path in paths) { Paths.Add(path); } } public override string Type { get { return "polyline"; }} } }
using System; using System.Collections.Generic; namespace RimuTec.Faker.Helper { internal static class IntHelper { public static IEnumerable<int> Repeat(int from, int to, Func<int, int> initializer) { var list = new List<int>(); for (var i = from; i <= to; i++) { list.Add(initializer.Invoke(i)); } return list; } } }
using System.Linq; using System.Net.Http; using System.Text.RegularExpressions; namespace Raven.Yabt.TicketImporter.Infrastructure.DTOs { /// <summary> /// Resolves "link" header /// </summary> /// <remarks> /// Based on https://gist.github.com/pimbrouwers/8f78e318ccfefff18f518a483997be29 /// </remarks> internal class LinkHeader { public string? FirstLink { get; private set; } public string? PrevLink { get; private set; } public string? NextLink { get; private set; } public string? LastLink { get; private set; } public static LinkHeader? LinksFromHeader(HttpResponseMessage? httpResponse) { if (httpResponse != null && httpResponse.Headers.TryGetValues("link", out var values)) { return LinksFromHeader(values.FirstOrDefault()); } return null; } public static LinkHeader? LinksFromHeader(string? linkHeaderStr) { LinkHeader? linkHeader = null; if (!string.IsNullOrWhiteSpace(linkHeaderStr)) { string[] linkStrings = linkHeaderStr.Split(','); if (linkStrings.Any()) { linkHeader = new LinkHeader(); foreach (string linkString in linkStrings) { var relMatch = Regex.Match(linkString, "(?<=rel=\").+?(?=\")", RegexOptions.IgnoreCase); var linkMatch = Regex.Match(linkString, "(?<=<).+?(?=>)", RegexOptions.IgnoreCase); if (relMatch.Success && linkMatch.Success) { string rel = relMatch.Value.ToUpper(); string link = linkMatch.Value; switch (rel) { case "FIRST": linkHeader.FirstLink = link; break; case "PREV": linkHeader.PrevLink = link; break; case "NEXT": linkHeader.NextLink = link; break; case "LAST": linkHeader.LastLink = link; break; } } } } } return linkHeader; } } }
using System.Collections.Generic; namespace SynologyClient { public class ListListShare { public int total { get; set; } public int offset { get; set; } public List<SharedFolder> shares { get; set; } } }
namespace Qkmaxware.Astro.Control { /// <summary> /// Interface for any listeners that can subscribe to INDI connection events /// </summary> public interface IIndiListener { /// <summary> /// Listener to connection events /// </summary> /// <param name="server">server connected to</param> void OnConnect(IndiServer server); /// <summary> /// Listener to dis-connection events /// </summary> /// <param name="server">server disconnected from</param> void OnDisconnect(IndiServer server); /// <summary> /// Listener whenever client sends a message /// </summary> /// <param name="message">message sent</param> void OnMessageSent(IndiClientMessage message); /// <summary> /// Listener whenever client receives a message /// </summary> /// <param name="message">message received</param> void OnMessageReceived(IndiDeviceMessage message); /// <summary> /// Listener whenever a new device is defined /// </summary> /// <param name="device">device added</param> void OnAddDevice(IndiDevice device); /// <summary> /// Listener whenever a device is deleted /// </summary> /// <param name="device">device removed</param> void OnRemoveDevice(IndiDevice device); } /// <summary> /// Base class with empty implementations of all listener functions /// </summary> public class BaseIndiListener : IIndiListener { public virtual void OnConnect(IndiServer server) {} public virtual void OnDisconnect(IndiServer server) {} public virtual void OnMessageSent(IndiClientMessage message) {} public virtual void OnMessageReceived(IndiDeviceMessage message) { switch (message) { case IndiSetPropertyMessage smsg: OnSetProperty(smsg); break; case IndiDefinePropertyMessage dmsg: OnDefineProperty(dmsg); break; case IndiDeletePropertyMessage delmsg: OnDeleteProperty(delmsg); break; case IndiNotificationMessage note: OnNotification(note); break; } } public virtual void OnAddDevice(IndiDevice device){} public virtual void OnRemoveDevice(IndiDevice device) {} /// <summary> /// When a define property message is received /// </summary> /// <param name="message">message</param> public virtual void OnDefineProperty(IndiDefinePropertyMessage message){} /// <summary> /// When a delete property message is received /// </summary> /// <param name="message">message</param> public virtual void OnDeleteProperty(IndiDeletePropertyMessage message){} /// <summary> /// When a notification message is received /// </summary> /// <param name="message">message</param> public virtual void OnNotification(IndiNotificationMessage message){} /// <summary> /// When a set property message is received /// </summary> /// <param name="message">message</param> public virtual void OnSetProperty(IndiSetPropertyMessage message){} } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using Touch; namespace Touch.Custom_Forms { public partial class frmHistoryTouch : TouchUserControlBase { protected void Page_Load(object sender, EventArgs e) { ART[] myArray = new ART[6] { new ART("Atripla","26 Jan 2012"), new ART("Reyataz","12 Mar 2012"), new ART("Norvir","07 May 2012"), new ART("Truvada","23 Jun 2012"), new ART("Prezista","19 Sep 2012"), new ART("Isentress","15 Dec 2012") }; rgPriorART.DataSource = myArray; rgPriorART.DataBind(); rgPriorART.Visible = true; } } public class ART { public ART(string Regimen, string Date) { _regimen = Regimen; _date = Date; } private string _regimen; public string Regimen { get { return _regimen; } set { _regimen = value; } } private string _date; public string Date { get { return _date; } set { _date = value; } } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace MenuStripDemo { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void blueToolStripMenuItem_Click(object sender, EventArgs e) { this.BackColor = Color.Aqua; } private void redToolStripMenuItem_Click(object sender, EventArgs e) { this.BackColor = Color.FromArgb(220, 13, 50); } private void orangeToolStripMenuItem_Click(object sender, EventArgs e) { this.BackColor = Color.FromArgb(255, 138, 58); } private void italicToolStripMenuItem_Click(object sender, EventArgs e) { this.Font = new Font("Wingdings", 32); } private void professionalToolStripMenuItem_Click(object sender, EventArgs e) { this.Font = new Font("Tahoma", 12); } } }
using System.Threading.Tasks; using System.Web.Mvc; using MediatR; namespace KenticoContrib.Features.Home { public class HomeController : Controller { private readonly IMediator mediator; public HomeController(IMediator mediator) { this.mediator = mediator; } public async Task<ActionResult> Index() { HomeViewModel viewModel = await mediator.Send(new IndexQuery()); return View(viewModel); } } }
using Newtonsoft.Json; namespace Acklann.Plaid.Management { /// <summary> /// Represents a response from plaid's '/link/token/create' endpoint. Create a link_token. /// </summary> /// <seealso cref="Acklann.Plaid.ResponseBase" /> public class CreateLinkTokenResponse : ResponseBase { /// <summary> /// Gets or sets the link token. /// </summary> /// <value>The link token.</value> [JsonProperty("link_token")] public string LinkToken { get; set; } /// <summary> /// Gets or sets the expiration. /// </summary> /// <value>The expiration.</value> [JsonProperty("expiration")] public string Expiration { get; set; } } }
using System; using GSF.Snap; using GSF.Snap.Storage; using openHistorian.Collections; using GSF.Snap.Tree; using openHistorian.Snap; namespace openHistorian { public class PointStreamSequentialPoints : TreeStream<HistorianKey, HistorianValue> { private ulong m_start; private int m_count; public PointStreamSequentialPoints(int start, int count) { m_start = (ulong)start; m_count = count; } protected override bool ReadNext(HistorianKey key, HistorianValue value) { if (m_count <= 0) { key.Timestamp = 0; key.PointID = 0; value.Value3 = 0; value.Value1 = 0; return false; } m_count--; key.Timestamp = 0; key.PointID = m_start; value.AsSingle = 60.251f; m_start++; return true; } } public class PointStreamSequential : TreeStream<HistorianKey, HistorianValue> { private ulong m_start; private int m_count; private readonly Func<ulong, ulong> m_key1; private readonly Func<ulong, ulong> m_key2; private readonly Func<ulong, ulong> m_value1; private readonly Func<ulong, ulong> m_value2; public PointStreamSequential(int start, int count) : this(start, count, x => 1 * x, x => 2 * x, x => 3 * x, x => 4 * x) { } public PointStreamSequential(int start, int count, Func<ulong, ulong> key1, Func<ulong, ulong> key2, Func<ulong, ulong> value1, Func<ulong, ulong> value2) { m_start = (ulong)start; m_count = count; m_key1 = key1; m_key2 = key2; m_value1 = value1; m_value2 = value2; } protected override bool ReadNext(HistorianKey key, HistorianValue value) { if (m_count <= 0) { key.Timestamp = 0; key.PointID = 0; value.Value3 = 0; value.Value1 = 0; return false; } m_count--; key.Timestamp = m_key1(m_start); key.PointID = m_key2(m_start); value.Value3 = m_value1(m_start); value.Value1 = m_value2(m_start); m_start++; return true; } } public static class PointStreamHelpers { //public static bool AreEqual(this IStream256 source, IStream256 destination) //{ // bool isValidA, isValidB; // ulong akey1, akey2, avalue1, avalue2; // ulong bkey1, bkey2, bvalue1, bvalue2; // while (true) // { // isValidA = source.Read(out akey1, out akey2, out avalue1, out avalue2); // isValidB = destination.Read(out bkey1, out bkey2, out bvalue1, out bvalue2); // if (isValidA != isValidB) // return false; // if (isValidA && isValidB) // { // if (akey1 != bkey1) // return false; // if (akey2 != bkey2) // return false; // if (avalue1 != bvalue1) // return false; // if (avalue2 != bvalue2) // return false; // } // else // { // return true; // } // } //} //public static long Count(this IStream256 stream) //{ // long x = 0; // ulong akey1, akey2, avalue1, avalue2; // while (stream.Read(out akey1, out akey2, out avalue1, out avalue2)) // x++; // return x; //} //public static long Count(this Stream256Base stream) //{ // long x = 0; // while (stream.Read()) // x++; // return x; //} public static long Count<TKey, TValue>(this TreeStream<TKey, TValue> stream) where TKey : class, new() where TValue : class, new() { TKey key = new TKey(); TValue value = new TValue(); long x = 0; while (stream.Read(key, value)) x++; return x; } public static long Count(this SortedTreeTable<HistorianKey, HistorianValue> stream) { using (SortedTreeTableReadSnapshot<HistorianKey, HistorianValue> read = stream.BeginRead()) { SortedTreeScannerBase<HistorianKey, HistorianValue> scan = read.GetTreeScanner(); scan.SeekToStart(); return scan.Count(); } } } }
namespace CryptoMiningSystem { public class LowPerformanceProcessor : Processor { public LowPerformanceProcessor(string model, decimal price, int generation) : base(model, price, generation, 2) { } } }
using System; using ProSuite.Commons.Essentials.CodeAnnotations; namespace ProSuite.Commons.Exceptions { /// <summary> /// Helper class for throwing exceptions. /// </summary> public static class Ex { public static void Throw<T>(string message) where T : Exception { var exception = (T) Activator.CreateInstance(typeof(T), message); throw exception; } [StringFormatMethod("format")] public static void Throw<T>(string format, params object[] args) where T : Exception { var exception = (T) Activator.CreateInstance(typeof(T), string.Format(format, args)); throw exception; } [StringFormatMethod("format")] public static void Throw<T>(Exception inner, string format, params object[] args) where T : Exception { var exception = (T) Activator.CreateInstance(typeof(T), string.Format(format, args), inner); throw exception; } } }
using System.Threading.Tasks; using Microservice.Core.Model; namespace Microservice.Core.Service.Contracts { public interface IQuerableService<TServiceQuery, TSDO> : IService<TSDO> where TServiceQuery : class where TSDO : class { Task<ResourceMultipleResponse<TSDO>> Get(ResourceRequest<TServiceQuery> request); } }
using ACadSharp.Attributes; using ACadSharp.IO.Templates; using CSMath; namespace ACadSharp.Entities { public class Solid3D : Entity { public override ObjectType ObjectType => ObjectType.SOLID3D; public override string ObjectName => DxfFileToken.Entity3DSolid; //100 Subclass marker(AcDbTrace) [DxfCodeValue(10, 20, 30)] public XYZ FirstCorner { get; set; } [DxfCodeValue(11, 21, 31)] public XYZ SecondCorner { get; set; } [DxfCodeValue(12, 22, 32)] public XYZ ThirdCorner { get; set; } //Fourth corner.If only three corners are entered to define the SOLID, then the fourth corner coordinate is the same as the third. [DxfCodeValue(13, 23, 33)] public XYZ FourthCorner { get; set; } /// <summary> /// Specifies the distance a 2D AutoCAD object is extruded above or below its elevation. /// </summary> [DxfCodeValue(39)] public double Thickness { get; set; } = 0.0; public Solid3D() : base() { } internal Solid3D(DxfEntityTemplate template) : base(template) { } } }
using System.Collections.Generic; namespace ImaginationServer.Common { public class ZoneChecksums { public static readonly byte[] VentureExplorer = { 0x7c, 0x08, 0xb8, 0x20 }; public static Dictionary<ZoneId, byte[]> Checksums { get; } = new Dictionary<ZoneId, byte[]> { {ZoneId.VentureExplorer, VentureExplorer} }; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class BoardManager : MonoBehaviour { public static BoardManager Instance { get; set; } public bool[,] allowedMoves; public ChessPiece[,] ChessPieces { get; set; } public ChessPiece selectedPiece; private const float TILE_SIZE = 1.0f; private const float TILE_OFFSET = 0.5f; private int selectionX = -1; private int selectionY = -1; public int boardDimension = 8; public List<GameObject> chessPiecePrefabs; private List<GameObject> alivePieces; public int[] EnPassantMoves { set; get; } private Quaternion pieceOrientation = Quaternion.Euler(0, 180, 0); public bool isWhiteTurn = true; private void Start() { Instance = this; SpawnAllChessPieces(); } private void Update() { UpdateSelection(); DrawChessboard(); if (Input.GetMouseButtonDown(0)) { if (selectionX >= 0 && selectionY >= 0) { if (selectedPiece == null) { SelectPiece(selectionX, selectionY); } else { MovePiece(selectionX, selectionY); } } } } public void SelectPiece(int x, int y) { if (ChessPieces[x, y] == null) { return; } if (ChessPieces[x, y].isWhite != isWhiteTurn) { return; } CheckForMoves(ChessPieces[x, y]); if (!ChessPieces[x, y].hasMoves) { return; } selectedPiece = ChessPieces[x, y]; BoardHighlighting.Instance.Highlight(allowedMoves); } public void CheckForMoves(ChessPiece piece) { bool hasAtLeastOneMove = false; allowedMoves = piece.IsMovePossible(); for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { if (allowedMoves[i, j]) { hasAtLeastOneMove = true; } } } piece.hasMoves = hasAtLeastOneMove; } public void MovePiece(int x, int y) { if (allowedMoves[x, y]) { ChessPiece destinationPiece = ChessPieces[x, y]; if (destinationPiece != null && destinationPiece.isWhite != isWhiteTurn) { //Capture piece //win if captured is king if (destinationPiece.GetType() == typeof(King)) { EndGame(); return; } alivePieces.Remove(destinationPiece.gameObject); Destroy(destinationPiece.gameObject); } if (x == EnPassantMoves[0] && y == EnPassantMoves[1]) { if (isWhiteTurn) { destinationPiece = ChessPieces[x, y - 1]; } else { destinationPiece = ChessPieces[x, y + 1]; } alivePieces.Remove(destinationPiece.gameObject); Destroy(destinationPiece.gameObject); } EnPassantMoves[0] = -1; EnPassantMoves[1] = -1; if (selectedPiece.GetType() == typeof(Pawn)) { if (y == 7) { alivePieces.Remove(selectedPiece.gameObject); Destroy(selectedPiece.gameObject); SpawnChessPiece(1, x, y); selectedPiece = ChessPieces[x, y]; } else if (y == 0) { alivePieces.Remove(selectedPiece.gameObject); Destroy(selectedPiece.gameObject); SpawnChessPiece(7, x, y); selectedPiece = ChessPieces[x, y]; } if (selectedPiece.CurrentY == 1 && y == 3) { EnPassantMoves[0] = x; EnPassantMoves[1] = y - 1; } else if (selectedPiece.CurrentY == 6 && y == 4) { EnPassantMoves[0] = x; EnPassantMoves[1] = y + 1; } } ChessPieces[selectedPiece.CurrentX, selectedPiece.CurrentY] = null; selectedPiece.transform.position = GetTileCenter(x, y); selectedPiece.SetPosition(x, y); ChessPieces[x, y] = selectedPiece; isWhiteTurn = !isWhiteTurn; AILogic.Instance.ToggleAITurn(); if (AILogic.Instance.IsAITurn == true) { AILogic.Instance.StartAITurn(); } } BoardHighlighting.Instance.HideHighlighting(); selectedPiece = null; } private void UpdateSelection() { if (!Camera.main) return; RaycastHit hit; if (Physics.Raycast( Camera.main.ScreenPointToRay(Input.mousePosition), out hit, 25.0f, LayerMask.GetMask("ChessPlane"))) { //Debug.Log(hit.point); selectionX = (int)hit.point.x; selectionY = (int)hit.point.z; } else { selectionX = -1; selectionY = -1; } } private void SpawnChessPiece(int index, int x, int y) { GameObject go = Instantiate( chessPiecePrefabs[index], GetTileCenter(x, y), pieceOrientation ) as GameObject; go.transform.SetParent(transform); ChessPieces[x, y] = go.GetComponent<ChessPiece>(); ChessPieces[x, y].SetPosition(x, y); // assign piece type to each ChessPiece string color; if (ChessPieces[x, y].name.Contains("White")) color = "White"; else color = "Black"; string name = ChessPieces[x, y].name.Substring(0, ChessPieces[x, y].name.IndexOf(color)); ChessPieces[x, y].type = name; alivePieces.Add(go); } private void SpawnAllChessPieces() { alivePieces = new List<GameObject>(); ChessPieces = new ChessPiece[8, 8]; EnPassantMoves = new int[2] { -1, -1 }; // SPAWN the brood!!! //White================================= //King SpawnChessPiece(0, 3, 0); //Queen SpawnChessPiece(1, 4, 0); //Rooks SpawnChessPiece(2, 0, 0); SpawnChessPiece(2, 7, 0); //Bishops SpawnChessPiece(3, 2, 0); SpawnChessPiece(3, 5, 0); //Knights SpawnChessPiece(4, 1, 0); SpawnChessPiece(4, 6, 0); //Pawns for (int i = 0; i < 8; i++) { SpawnChessPiece(5, i, 1); } //Black================================= //King SpawnChessPiece(6, 4, 7); //Queen SpawnChessPiece(7, 3, 7); //Rooks SpawnChessPiece(8, 0, 7); SpawnChessPiece(8, 7, 7); //Bishops SpawnChessPiece(9, 2, 7); SpawnChessPiece(9, 5, 7); //Knights SpawnChessPiece(10, 1, 7); SpawnChessPiece(10, 6, 7); //Pawns for (int i = 0; i < 8; i++) { SpawnChessPiece(11, i, 6); } } private Vector3 GetTileCenter(int x, int y) { Vector3 origin = Vector3.zero; origin.x += (TILE_SIZE * x) + TILE_OFFSET; origin.z += (TILE_SIZE * y) + TILE_OFFSET; return origin; } private void DrawChessboard() { Vector3 widthLine = Vector3.right * 8; Vector3 heightine = Vector3.forward * 8; for (int i = 0; i <= 8; i++) { Vector3 start = Vector3.forward * i; Debug.DrawLine(start, start + widthLine, Color.black); for (int j = 0; j <= 0; j++) { start = Vector3.right * j; Debug.DrawLine(start, start + heightine, Color.black); } } // Draw the selection if(selectionX >= 0 && selectionY >= 0) { Debug.DrawLine( Vector3.forward * selectionY + Vector3.right * selectionX, Vector3.forward * (selectionY + 1) + Vector3.right * (selectionX + 1)); Debug.DrawLine( Vector3.forward * (selectionY + 1) + Vector3.right * selectionX, Vector3.forward * selectionY + Vector3.right * (selectionX + 1)); } } public void WhiteTurn() { isWhiteTurn = true; } public void EndGame() { if (isWhiteTurn) { Debug.Log("White wins."); } else { Debug.Log("Black wins."); } foreach (GameObject go in alivePieces) { Destroy(go); } isWhiteTurn = true; AILogic.instance = null; BoardHighlighting.Instance.HideHighlighting(); SpawnAllChessPieces(); } }
using System.Collections.Generic; using PizzaCity.Domain.Abstracts; namespace PizzaCity.Domain.Models { public class Pizza : PizzaModel { // public Crust Crust { get; set; } // public Size Size { get; set; } // public ICollection<Toppings> Toppings { get; set; } public Pizza() { } public Pizza(Crust c, Size s,List<Toppings> t) { Crust = c; Size = s; Toppings = t; SetPrice(); } protected override void SetName(string n) { this.Name = n; } public override void SetPrice() { double total=0; foreach (var item in Toppings) { total += item.Price; } total += Size.Price; total += Crust.Price; Price = total+8; } protected override void AddCrust(Crust c) { Crust = c; } protected override void AddSize(Size s) { Size=s; } protected override void AddToppings(List<Toppings> t) { Toppings = t; } } }
using System; using System.Collections.Generic; using System.Drawing; #if NETCOREAPP2_1 || NETCOREAPP2_2 || NETCOREAPP3_0 using System.Drawing; #endif #if NET45 using System.Drawing; #endif using System.Globalization; using System.Linq; using System.Text; using System.Xml; using System.Xml.Linq; using Kugar.Core.ExtMethod; using Kugar.Core.ExtMethod.Serialization; namespace Kugar.Core.ExtMethod { public static class FontExt { private static XmlDocument _shareDocument=new XmlDocument(); public static void SerializeToXML(this Font font, XmlNode node) { if (font==null) { return; } node.SetAttribute("Name", font.Name); node.SetAttribute("Size", font.Size.ToString(CultureInfo.InvariantCulture)); node.SetAttribute("Bold", font.Bold.ToString()); node.SetAttribute("Italic", font.Italic.ToString()); bool strikeout = false; #if NET45 || NETCOREAPP2_0 || NETCOREAPP strikeout = font.Strikeout; #endif #if NETSTANDARD2_0 strikeout = font.Strikethrough; #endif node.SetAttribute("Strikeout", strikeout.ToString()); node.SetAttribute("Underline", font.Underline.ToString()); } public static string SerializeToString(this Font font) { if (font==null) { return string.Empty; } var node = _shareDocument.CreateElement("Font"); SerializeToXML(font, node); return node.OuterXml.ToBase64(); //return SerializationExt.SerializeToString(node); } public static Font DeserialFontFromXML(XmlElement node) { if (node==null || node.FirstChild==null) { return null; } node=(XmlElement)node.FirstChild; string familyName = node.GetAttribute("Name"); if (string.IsNullOrWhiteSpace(familyName)) { return null; } float size = float.Parse(node.GetAttribute("Size"), CultureInfo.InvariantCulture); bool bold = bool.Parse(node.GetAttribute("Bold")); bool italic = bool.Parse(node.GetAttribute("Italic")); bool strikeout = bool.Parse(node.GetAttribute("Strikeout")); bool underline = bool.Parse(node.GetAttribute("Underline")); FontStyle fontStyle = FontStyle.Regular; if (bold) fontStyle |= FontStyle.Bold; if (italic) fontStyle |= FontStyle.Italic; if (strikeout) fontStyle |= FontStyle.Strikeout; if (underline) fontStyle |= FontStyle.Underline; Font font = new Font(familyName, size, fontStyle); return font; } public static Font DeserialFontFromString(string fontString) { if (string.IsNullOrWhiteSpace(fontString)) { return null; } var xmlStr = fontString.FromBase64(); var node = _shareDocument.CreateElement("Font"); node.InnerXml = xmlStr; return DeserialFontFromXML(node); } } }
using System; namespace Sawczyn.EFDesigner.EFModel { internal partial class EFModelExplorer { /// <summary>Raises the <see cref="E:System.Windows.Forms.Control.DoubleClick" /> event.</summary> /// <param name="e">An <see cref="T:System.EventArgs" /> that contains the event data. </param> protected override void OnDoubleClick(EventArgs e) { base.OnDoubleClick(e); // let's make this a switch so we can more easily extend it to different element types later switch (SelectedElement) { case ModelClass modelClass: EFModelDocData.OpenFileFor(modelClass); break; case ModelAttribute modelAttribute: EFModelDocData.OpenFileFor(modelAttribute.ModelClass); break; case ModelEnum modelEnum: EFModelDocData.OpenFileFor(modelEnum); break; case ModelEnumValue modelEnumValue: EFModelDocData.OpenFileFor(modelEnumValue.Enum); break; } } } }
using OwlAndJackalope.UX.Runtime.Observers; namespace OwlAndJackalope.UX.Runtime.DetailBinders.Appliers { /// <summary> /// Inherit from this to flag certain binders as Appliers. Appliers are able to apply changes to the /// Details that they bind to. /// </summary> public abstract class BaseDetailApplier : BaseDetailBinder { protected bool IsReadyToSet<T>(MutableDetailObserver<T> observer) { if (!observer.IsSet) { observer.Initialize(_referenceModule.Reference); if (!observer.IsSet) { return false; } } return true; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Trabalho.Modelo { public class Imovel { public int ID { get; set; } public string Categoria { get; set; } public string Status { get; set; } public string Faixa_Area { get; set; } public string Faixa_Area_Privada { get; set; } public string Faixa_Preco_IPTU { get; set; } public string Faixa_Area_Condominio { get; set; } public bool Flg_Planta { get; set; } public bool Flg_Dependencia { get; set; } public bool Flg_Sacada { get; set; } public bool Flg_Portaria { get; set; } public bool Flg_Elevador { get; set; } public string Churrasqueira { get; set; } public string Faixa_Dormintorios { get; set; } public string Faixa_Suites { get; set; } public string Faixa_Vagas { get; set; } public string Faixa_Banheiros { get; set; } public string Faixa_Valor_Venda { get; set; } public string Faixa_Valor_Aluguel { get; set; } public bool Flg_Mostra_mapa { get; set; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Windows.Forms; using LoginServer.Network; namespace LoginServer { public partial class FrmBlockList : Form { /// <summary> /// Quantida de colunas no grid. /// </summary> private const int TotalGridColumn = 5; public FrmBlockList() { InitializeComponent(); } private void FrmBlockList_Load(object sender, EventArgs e) { GridBlock.Font = new Font("Lucida Sans", 9f, FontStyle.Regular); CreateDataFromBlockList(); } /// <summary> /// Cria os dados para ser colocados no grid. /// </summary> private void CreateDataFromBlockList() { var blocks = IpBlockList.IpBlocked; var list = new List<string>(); foreach (var block in blocks.Values) { list.Add(block.Ip + ""); list.Add(block.Time + ""); list.Add(block.AccessCount + ""); list.Add(block.AttemptCount + ""); list.Add(block.Permanent.ToString()); } FillData(ref list); GridBlock.Sort(GridBlock.Columns[0], ListSortDirection.Ascending); } /// <summary> /// Adiciona os dados no grid. /// </summary> /// <param name="items"></param> private void FillData(ref List<string> items) { var row = 0; while (items.Count > 0) { row = GridBlock.Rows.Add(); for (var n = 0; n < TotalGridColumn; n++) { GridBlock.Rows[row].Cells[n].Value = items[n]; } items.RemoveRange(0, TotalGridColumn); } } private void MenuRefresh_Click(object sender, EventArgs e) { GridBlock.Rows.Clear(); CreateDataFromBlockList(); } } }
using System; using System.Data.SqlClient; using System.Data; using Microsoft.VisualStudio.TestTools.UnitTesting; using SQLServerCrypto; namespace SQLServerCryptoTests { [TestClass] [Ignore] // Set instance of SQL Server and remove this attribute. public class SQLServerCryptoMethodsTestsWithSqlServer { private const string SQLSERVERINSTANCE = "."; public static string EncryptByPassPhrase_SQLServer(string passphrase, string cleartext) { var result = string.Empty; using (var sqlConnection = new SqlConnection($"Server={SQLSERVERINSTANCE};Trusted_Connection=yes")) { using (var sqlCommand = new SqlCommand { Connection = sqlConnection }) { sqlCommand.Parameters.Add("@PassPhrase", SqlDbType.VarChar).Value = passphrase; sqlCommand.Parameters.Add("@ClearText", SqlDbType.VarChar, 8000).Value = cleartext; sqlCommand.CommandText = "SELECT EncryptByPassPhrase(@PassPhrase, @ClearText)"; sqlConnection.Open(); result = new HexString((byte[])sqlCommand.ExecuteScalar()); } } return result; } public static string DecryptPassPhrase_SQLServer(string passphrase, HexString cipher) { var result = string.Empty; using (var sqlConnection = new SqlConnection($"Server={SQLSERVERINSTANCE};Trusted_Connection=yes")) { using (var sqlCommand = new SqlCommand { Connection = sqlConnection }) { sqlCommand.Parameters.Add("@PassPhrase", SqlDbType.VarChar).Value = passphrase; sqlCommand.Parameters.Add("@Cipher", SqlDbType.VarBinary).Value = (byte[])cipher; sqlCommand.CommandText = "SELECT cast(DecryptByPassPhrase(@PassPhrase, @Cipher) as varchar)"; sqlConnection.Open(); result = (string)sqlCommand.ExecuteScalar(); } } return result; } [TestMethod] public void SQLServerCryptoMethodsTestsWithSQLServer_EncryptByPassPhraseOnSQLServer_DecryptByPassPhrase_V1() { var passphrase = "test1234"; var cleartext = "Hello world."; var cipherFromSqlServer = EncryptByPassPhrase_SQLServer(passphrase, cleartext); var decryptedText = SQLServerCryptoMethod.DecryptByPassPhrase(passphrase, cipherFromSqlServer); Assert.AreEqual(cleartext, decryptedText); } [TestMethod] public void SQLServerCryptoMethodsTestsWithSqlServer_EncryptByPassPhrase_DecryptByPassPhraseOnSQLServer_V1() { var passphrase = "test1234"; var cleartext = "Hello world."; var cipher = SQLServerCryptoMethod.EncryptByPassPhrase(passphrase, cleartext); var decryptedText = DecryptPassPhrase_SQLServer(passphrase, cipher); Assert.AreEqual(cleartext, decryptedText); } } }
using Newtonsoft.Json.Linq; using Psy.Owin.Security.Keycloak.IdentityModel.Extensions; using System.Collections.Generic; using System.Globalization; using System.Security.Claims; namespace Psy.Owin.Security.Keycloak.IdentityModel.Utilities.ClaimMapping { internal static class ClaimMappings { public static IEnumerable<ClaimLookup> AccessTokenMappings { get; } = new List<ClaimLookup> { new ClaimLookup { ClaimName = Constants.ClaimTypes.Audience, JSelectQuery = "aud" }, new ClaimLookup { ClaimName = Constants.ClaimTypes.Issuer, JSelectQuery = "iss" }, new ClaimLookup { ClaimName = Constants.ClaimTypes.IssuedAt, JSelectQuery = "iat", Transformation = token => ((token.Value<double?>() ?? 1) - 1).ToDateTime().ToString(CultureInfo.InvariantCulture) }, new ClaimLookup { ClaimName = Constants.ClaimTypes.AccessTokenExpiration, JSelectQuery = "exp", Transformation = token => ((token.Value<double?>() ?? 1) - 1).ToDateTime().ToString(CultureInfo.InvariantCulture) }, new ClaimLookup { ClaimName = Constants.ClaimTypes.SubjectId, JSelectQuery = "sub" }, new ClaimLookup { ClaimName = ClaimTypes.Name, JSelectQuery = "preferred_username" }, new ClaimLookup { ClaimName = ClaimTypes.GivenName, JSelectQuery = "given_name" }, new ClaimLookup { ClaimName = ClaimTypes.Surname, JSelectQuery = "family_name" }, new ClaimLookup { ClaimName = ClaimTypes.Email, JSelectQuery = "email" }, new ClaimLookup { ClaimName = ClaimTypes.Role, JSelectQuery = "resource_access.{gid}.roles" } }; public static IEnumerable<ClaimLookup> IdTokenMappings { get; } = new List<ClaimLookup>(); public static IEnumerable<ClaimLookup> RefreshTokenMappings { get; } = new List<ClaimLookup> { new ClaimLookup { ClaimName = Constants.ClaimTypes.RefreshTokenExpiration, JSelectQuery = "exp", Transformation = token => ((token.Value<double?>() ?? 1) - 1).ToDateTime().ToString(CultureInfo.InvariantCulture) } }; } }
using System; namespace Nexus.Link.Libraries.Core.Platform.BusinessEvents { /// <summary> /// Meta data present at publication of all Business Events /// </summary> public class BusinessEventMetaData { /// <summary>A unique id for this specific publication of the event</summary> public string MessageId { get; set; } /// <summary>The technical name of the publishing client</summary> public string PublisherName { get; set; } /// <summary>The name of the entity</summary> public string EntityName { get; set; } /// <summary>The name of the event, in the context of the <see cref="EntityName"/></summary> public string EventName { get; set; } /// <summary>The major version of the event</summary> public int MajorVersion { get; set; } /// <summary>The minor version of the event</summary> public int MinorVersion { get; set; } /// <summary>The timestamp for when the event was published</summary> public DateTimeOffset PublishedAt { get; set; } } }
namespace System.Web.ModelBinding { using System; /// <summary> /// This attribute is the base class for all the value provider attributes that can be specified on /// method parameters to be able to get values from alternate sources like Form, QueryString, ViewState. /// </summary> public abstract class ValueProviderSourceAttribute : Attribute, IValueProviderSource, IModelNameProvider { public abstract IValueProvider GetValueProvider(ModelBindingExecutionContext modelBindingExecutionContext); public virtual string GetModelName() { return null; } } }
using System.Windows.Forms; namespace Wuqi.Webdiyer { public partial class SPHelpForm : Form { public SPHelpForm() { InitializeComponent(); } private void SPHelpForm_Load(object sender, System.EventArgs e) { textBox1.Select(0, 0); } } }
// -- FILE ------------------------------------------------------------------ // name : CalendarTimeRangeTest.cs // project : Itenso Time Period // created : Jani Giannoudis - 2011.02.18 // language : C# 4.0 // environment: .NET 2.0 // copyright : (c) 2011-2012 by Itenso GmbH, Switzerland // ------------------------------------------------------------------------ using System; using Xunit; namespace TimePeriod.Tests { public sealed class CalendarTimeRangeTest : TestUnitBase { [Trait("Category", "CalendarTimeRange")] [Fact] public void CalendarTest() { TimeCalendar calendar = new TimeCalendar(); CalendarTimeRange calendarTimeRange = new CalendarTimeRange( TimeRange.Anytime, calendar ); Assert.Equal( calendarTimeRange.Calendar, calendar ); } // CalendarTest [Trait("Category", "CalendarTimeRange")] [Fact] public void MomentTest() { DateTime testDate = new DateTime( 2000, 10, 1 ); Assert.NotNull(Assert.Throws<NotSupportedException>( () => new CalendarTimeRange(testDate, testDate))); } // MomentTest } // class CalendarTimeRangeTest } // namespace Itenso.TimePeriodTests // -- EOF -------------------------------------------------------------------
using System.Collections.Generic; using Humanizer; using Tewl.Tools; namespace EnterpriseWebLibrary.EnterpriseWebFramework { /// <summary> /// A caption for a figure. /// </summary> public class FigureCaption { internal class CssElementCreator: ControlCssElementCreator { internal static readonly ElementClass Class = new ElementClass( "ewfFig" ); IReadOnlyCollection<CssElement> ControlCssElementCreator.CreateCssElements() { return new[] { new CssElement( "FigureCaption", "figcaption.{0}".FormatWith( Class.ClassName ) ) }; } } internal readonly bool FigureIsTextual; internal readonly IReadOnlyCollection<FlowComponent> Components; /// <summary> /// Creates a caption. /// </summary> /// <param name="components"></param> /// <param name="figureIsTextual">Pass true to place the caption above the content.</param> public FigureCaption( IReadOnlyCollection<FlowComponent> components, bool figureIsTextual = false ) { FigureIsTextual = figureIsTextual; Components = new DisplayableElement( context => new DisplayableElementData( null, () => new DisplayableElementLocalData( "figcaption" ), classes: CssElementCreator.Class, children: components ) ).ToCollection(); } } }
using ZXing; using ZXing.QrCode; using UnityEngine; public class QRGen : MonoBehaviour { private static QRGen _instance; public static QRGen Instance { get { if (_instance == null) { _instance = new QRGen (); } return _instance; } } public void create(string inputString,Texture2D texture){ var qrCodeColors = Write (inputString, texture.width, texture.height); texture.SetPixels32 (qrCodeColors); texture.Apply (); } private Color32[] Write(string content,int width,int height){ var writer = new BarcodeWriter { Format = BarcodeFormat.QR_CODE, Options = new QrCodeEncodingOptions { Height = height, Width = width } }; return writer.Write (content); } }
using Microsoft.AspNet.WebHooks; using Nop.Core.Domain.Catalog; using Nop.Core.Domain.Customers; using Nop.Core.Events; using Nop.Core.Infrastructure; using Nop.Plugin.Api.Services; using Nop.Services.Events; using Nop.Plugin.Api.DTOs.Customers; using Nop.Plugin.Api.Constants; using Nop.Plugin.Api.DTOs.Products; using Nop.Plugin.Api.Helpers; using Nop.Plugin.Api.DTOs.Categories; using Nop.Core.Domain.Orders; using Nop.Plugin.Api.DTOs.Orders; using Nop.Plugin.Api.MappingExtensions; namespace Nop.Plugin.Api.WebHooks { public class WebHookEventConsumer : IConsumer<EntityInserted<Customer>>, IConsumer<EntityUpdated<Customer>>, IConsumer<EntityInserted<Product>>, IConsumer<EntityUpdated<Product>>, IConsumer<EntityInserted<Category>>, IConsumer<EntityUpdated<Category>>, IConsumer<EntityInserted<Order>>, IConsumer<EntityUpdated<Order>> { private IWebHookManager _webHookManager; private ICustomerApiService _customerApiService; private IDTOHelper _dtoHelper; public WebHookEventConsumer() { IWebHookService webHookService = EngineContext.Current.ContainerManager.Resolve<IWebHookService>(); _customerApiService = EngineContext.Current.ContainerManager.Resolve<ICustomerApiService>(); _dtoHelper = EngineContext.Current.ContainerManager.Resolve<IDTOHelper>(); _webHookManager = webHookService.GetHookManager(); } public void HandleEvent(EntityInserted<Customer> eventMessage) { // There is no need to send webhooks for guest customers. if (eventMessage.Entity.IsGuest()) { return; } CustomerDto customer = _customerApiService.GetCustomerById(eventMessage.Entity.Id); _webHookManager.NotifyAllAsync(WebHookNames.CustomerCreated, new { Item = customer }); } public void HandleEvent(EntityUpdated<Customer> eventMessage) { // There is no need to send webhooks for guest customers. if (eventMessage.Entity.IsGuest()) { return; } CustomerDto customer = _customerApiService.GetCustomerById(eventMessage.Entity.Id, true); // In nopCommerce the Customer, Product, Category and Order entities are not deleted. // Instead the Deleted property of the entity is set to true. string webhookEvent = WebHookNames.CustomerUpdated; if(customer.Deleted == true) { webhookEvent = WebHookNames.CustomerDeleted; } _webHookManager.NotifyAllAsync(webhookEvent, new { Item = customer }); } public void HandleEvent(EntityInserted<Product> eventMessage) { ProductDto productDto = _dtoHelper.PrepareProductDTO(eventMessage.Entity); _webHookManager.NotifyAllAsync(WebHookNames.ProductCreated, new { Item = productDto }); } public void HandleEvent(EntityUpdated<Product> eventMessage) { ProductDto productDto = _dtoHelper.PrepareProductDTO(eventMessage.Entity); string webhookEvent = WebHookNames.ProductUpdated; if (productDto.Deleted == true) { webhookEvent = WebHookNames.ProductDeleted; } _webHookManager.NotifyAllAsync(webhookEvent, new { Item = productDto }); } public void HandleEvent(EntityInserted<Category> eventMessage) { CategoryDto categoryDto = _dtoHelper.PrepareCategoryDTO(eventMessage.Entity); _webHookManager.NotifyAllAsync(WebHookNames.CategoryCreated, new { Item = categoryDto }); } public void HandleEvent(EntityUpdated<Category> eventMessage) { CategoryDto categoryDto = _dtoHelper.PrepareCategoryDTO(eventMessage.Entity); string webhookEvent = WebHookNames.CategoryUpdated; if (categoryDto.Deleted == true) { webhookEvent = WebHookNames.CategoryDeleted; } _webHookManager.NotifyAllAsync(webhookEvent, new { Item = categoryDto }); } public void HandleEvent(EntityInserted<Order> eventMessage) { OrderDto orderDto = _dtoHelper.PrepareOrderDTO(eventMessage.Entity); _webHookManager.NotifyAllAsync(WebHookNames.OrderCreated, new { Item = orderDto }); } public void HandleEvent(EntityUpdated<Order> eventMessage) { OrderDto orderDto = _dtoHelper.PrepareOrderDTO(eventMessage.Entity); string webhookEvent = WebHookNames.OrderUpdated; if (orderDto.Deleted == true) { webhookEvent = WebHookNames.OrderDeleted; } _webHookManager.NotifyAllAsync(webhookEvent, new { Item = orderDto }); } } }
using System; using System.Xml.Serialization; using MyToolkit.MachineLearning.WinRT.Activation; using MyToolkit.Mathematics; namespace MyToolkit.MachineLearning.WinRT.Feedforward { public class FeedforwardLayer { internal FeedforwardLayer() { } // used for serialization public FeedforwardLayer(int neuronCount) : this(new ActivationSigmoid(), neuronCount) { } public FeedforwardLayer(ActivationFunction thresholdFunction, int neuronCount) { Fire = new double[neuronCount]; LayerActivationFunction = thresholdFunction; } public ActivationFunction LayerActivationFunction { get; set; } private Matrix _layerMatrix; public Matrix LayerMatrix { get { return _layerMatrix; } set { _layerMatrix = value; if (_layerMatrix != null) { if (_layerMatrix.Rows < 2) throw new Exception("matrix must have at least 2 rows."); if (_layerMatrix != null && Fire == null) Fire = new double[_layerMatrix.Rows - 1]; } } } public bool HasMatrix { get { return LayerMatrix != null; } } public bool IsHiddenLayer { get { return (next != null) && (Previous != null); } } public bool IsInputLayer { get { return Previous == null; } } public bool IsOutputLayer { get { return next == null; } } [XmlIgnore] public int NeuronCount { get { return Fire.Length; } } public double[] Fire { get; set; } [XmlIgnore] public FeedforwardLayer Previous { get; set; } private FeedforwardLayer next; [XmlIgnore] public FeedforwardLayer Next { get { return next; } set { next = value; if (LayerMatrix == null) // add one to the neuron count to provide a threshold value in row 0 LayerMatrix = new Matrix(NeuronCount + 1, next.NeuronCount); } } [XmlIgnore] public int MatrixSize { get { return _layerMatrix == null ? 0 : _layerMatrix.Size; } } public FeedforwardLayer CloneStructure() { return new FeedforwardLayer(LayerActivationFunction, NeuronCount); } public double[] ComputeOutputs(double[] pattern) { if (pattern != null) { for (var i = 0; i < NeuronCount; i++) Fire[i] = pattern[i]; } for (var i = 0; i < next.NeuronCount; i++) { var sum = GetDotProductOfColumnWithOneFakeColumn(LayerMatrix, i, Fire); next.Fire[i] = LayerActivationFunction.Activate(sum); } return Fire; } private double GetDotProductOfColumnWithOneFakeColumn(Matrix matrix, int col, double[] b) { var result = 0.0; for (var row = 0; row < matrix.Rows - 1; row++) result += matrix.Data[row, col] * b[row]; result += matrix.Data[matrix.Rows - 1, col] * 1; // fake column = 1 return result; } public void Prune(int neuron) { if (_layerMatrix != null) LayerMatrix = LayerMatrix.DeleteRow(neuron); // delete a row on this matrix if (Previous != null) { if (Previous.LayerMatrix != null) Previous.LayerMatrix = Previous.LayerMatrix.DeleteColumn(neuron); // delete a column on the previous } } public void Reset() { if (LayerMatrix != null) LayerMatrix.Ramdomize(-1, 1); } public override string ToString() { return "FeedforwardLayer: NeuronCount = " + NeuronCount; } } }
using Unity.Collections; namespace TinyMsgPack { public unsafe class MsgPackReader { private NativeSlice<byte> _buffer; private int _offset; public MsgPackReader(NativeSlice<byte> slice) { _buffer = slice; _offset = 0; } public MsgPackReader(NativeArray<byte> array) { _buffer = array; _offset = 0; } public bool TryReadNil() { bool isNil = ReadNext() == MsgPackCode.Nil; if(!isNil) _offset--; return isNil; } public bool ReadArrayHeader(out int length) { length = 0; byte code = ReadNext(); if (code == MsgPackCode.Nil) return false; if (code >= MsgPackCode.MinFixArray && code <= MsgPackCode.MaxFixArray) length = code - MsgPackCode.MinFixArray; else if (code == MsgPackCode.Array16) length = ReadRawBigEndian16(); else if (code == MsgPackCode.Array32) length = (int) ReadRawBigEndian32(); else throw new TinyMsgPackDeserializeException($"MsgPackReader - Invalid code {code}. Expected array."); return true; } public bool ReadMapHeader(out int length) { length = 0; byte code = ReadNext(); if (code == MsgPackCode.Nil) return false; if (code >= MsgPackCode.MinFixMap && code <= MsgPackCode.MaxFixMap) length = code - MsgPackCode.MinFixMap; else if (code == MsgPackCode.Map16) length = ReadRawBigEndian16(); else if (code == MsgPackCode.Map32) length = (int) ReadRawBigEndian32(); else throw new TinyMsgPackDeserializeException($"MsgPackReader - Invalid code {code}. Expected map."); return true; } public string ReadString() { byte code = ReadNext(); if (code == MsgPackCode.Nil) return null; int length = 0; if (code >= MsgPackCode.MinFixStr && code <= MsgPackCode.MaxFixStr) length = code - MsgPackCode.MinFixStr; else if (code == MsgPackCode.Str8) length = ReadRaw8(); else if (code == MsgPackCode.Str16) length = ReadRawBigEndian16(); else if (code == MsgPackCode.Str32) length = (int) ReadRawBigEndian32(); else throw new TinyMsgPackDeserializeException( $"{nameof(ReadString)} - invalid code {code}. Expected string."); if (length < 0) throw new TinyMsgPackDeserializeException( $"{nameof(ReadString)} - invalid string length {length}"); return StringUtils.Decode(ReadNext(length)); } public byte ReadUInt8() { byte code = ReadNext(); if (code <= MsgPackCode.MaxFixInt) return code; if (code == MsgPackCode.Float32) { var value = ReadRawBigEndian32(); return (byte) *(float*) &value; } if (code == MsgPackCode.Float64) { var value = ReadRawBigEndian64(); return (byte) *(double*) &value; } if (code == MsgPackCode.Int8) return ReadRaw8(); if (code == MsgPackCode.UInt8) return ReadRaw8(); if (code == MsgPackCode.Int16) return (byte) ReadRawBigEndian16(); if (code == MsgPackCode.UInt16) return (byte) ReadRawBigEndian16(); if (code == MsgPackCode.Int32) return (byte) ReadRawBigEndian32(); if (code == MsgPackCode.UInt32) return (byte) ReadRawBigEndian32(); if (code == MsgPackCode.Int64) return (byte) ReadRawBigEndian64(); if (code == MsgPackCode.UInt64) return (byte) ReadRawBigEndian64(); throw new TinyMsgPackDeserializeException($"MsgPackReader - Invalid code {code}. Expected number"); } public ushort ReadUInt16() { byte code = ReadNext(); if (code <= MsgPackCode.MaxFixInt) return code; if (code == MsgPackCode.Float32) { var value = ReadRawBigEndian32(); return (ushort) *(float*) &value; } if (code == MsgPackCode.Float64) { var value = ReadRawBigEndian64(); return (ushort) *(double*) &value; } if (code == MsgPackCode.Int8) return ReadRaw8(); if (code == MsgPackCode.UInt8) return ReadRaw8(); if (code == MsgPackCode.Int16) return ReadRawBigEndian16(); if (code == MsgPackCode.UInt16) return ReadRawBigEndian16(); if (code == MsgPackCode.Int32) return (ushort) ReadRawBigEndian32(); if (code == MsgPackCode.UInt32) return (ushort) ReadRawBigEndian32(); if (code == MsgPackCode.Int64) return (ushort) ReadRawBigEndian64(); if (code == MsgPackCode.UInt64) return (ushort) ReadRawBigEndian64(); throw new TinyMsgPackDeserializeException($"MsgPackReader - Invalid code {code}. Expected number"); } public uint ReadUInt32() { byte code = ReadNext(); if (code <= MsgPackCode.MaxFixInt) return code; if (code == MsgPackCode.Float32) { var value = ReadRawBigEndian32(); return (uint) *(float*) &value; } if (code == MsgPackCode.Float64) { var value = ReadRawBigEndian64(); return (uint) *(double*) &value; } if (code == MsgPackCode.Int8) return ReadRaw8(); if (code == MsgPackCode.UInt8) return ReadRaw8(); if (code == MsgPackCode.Int16) return ReadRawBigEndian16(); if (code == MsgPackCode.UInt16) return ReadRawBigEndian16(); if (code == MsgPackCode.Int32) return ReadRawBigEndian32(); if (code == MsgPackCode.UInt32) return ReadRawBigEndian32(); if (code == MsgPackCode.Int64) return (uint) ReadRawBigEndian64(); if (code == MsgPackCode.UInt64) return (uint) ReadRawBigEndian64(); throw new TinyMsgPackDeserializeException($"MsgPackReader - Invalid code {code}. Expected number"); } public ulong ReadUInt64() { byte code = ReadNext(); if (code <= MsgPackCode.MaxFixInt) return code; if (code == MsgPackCode.Float32) { var value = ReadRawBigEndian32(); return (ulong) *(float*) &value; } if (code == MsgPackCode.Float64) { var value = ReadRawBigEndian64(); return (ulong) *(double*) &value; } if (code == MsgPackCode.Int8) return ReadRaw8(); if (code == MsgPackCode.UInt8) return ReadRaw8(); if (code == MsgPackCode.Int16) return ReadRawBigEndian16(); if (code == MsgPackCode.UInt16) return ReadRawBigEndian16(); if (code == MsgPackCode.Int32) return ReadRawBigEndian32(); if (code == MsgPackCode.UInt32) return ReadRawBigEndian32(); if (code == MsgPackCode.Int64) return ReadRawBigEndian64(); if (code == MsgPackCode.UInt64) return ReadRawBigEndian64(); throw new TinyMsgPackDeserializeException($"MsgPackReader - Invalid code {code}. Expected number"); } public sbyte ReadInt8() => (sbyte) ReadUInt8(); public short ReadInt16() => (short) ReadUInt16(); public int ReadInt32() => (int) ReadUInt32(); public long ReadInt64() => (long) ReadUInt64(); public float ReadSingle() { byte code = ReadNext(); if (code <= MsgPackCode.MaxFixInt) return code; if (code == MsgPackCode.Float32) { var value = ReadRawBigEndian32(); return *(float*) &value; } if (code == MsgPackCode.Float64) { var value = ReadRawBigEndian64(); return (float) *(double*) &value; } if (code == MsgPackCode.Int8) return (sbyte) ReadRaw8(); if (code == MsgPackCode.UInt8) return ReadRaw8(); if (code == MsgPackCode.Int16) return (short) ReadRawBigEndian16(); if (code == MsgPackCode.UInt16) return ReadRawBigEndian16(); if (code == MsgPackCode.Int32) return (int) ReadRawBigEndian32(); if (code == MsgPackCode.UInt32) return ReadRawBigEndian32(); if (code == MsgPackCode.Int64) return (long) ReadRawBigEndian64(); if (code == MsgPackCode.UInt64) return ReadRawBigEndian64(); throw new TinyMsgPackDeserializeException($"MsgPackReader - Invalid code {code}. Expected number"); } public double ReadDouble() { byte code = ReadNext(); if (code <= MsgPackCode.MaxFixInt) return code; if (code == MsgPackCode.Float32) { var value = ReadRawBigEndian32(); return *(float*) &value; } if (code == MsgPackCode.Float64) { var value = ReadRawBigEndian64(); return *(double*) &value; } if (code == MsgPackCode.Int8) return (sbyte) ReadRaw8(); if (code == MsgPackCode.UInt8) return ReadRaw8(); if (code == MsgPackCode.Int16) return (short) ReadRawBigEndian16(); if (code == MsgPackCode.UInt16) return ReadRawBigEndian16(); if (code == MsgPackCode.Int32) return (int) ReadRawBigEndian32(); if (code == MsgPackCode.UInt32) return ReadRawBigEndian32(); if (code == MsgPackCode.Int64) return (long) ReadRawBigEndian64(); if (code == MsgPackCode.UInt64) return ReadRawBigEndian64(); throw new TinyMsgPackDeserializeException($"MsgPackReader - Invalid code {code}. Expected number"); } public byte ReadRaw8() => ReadNext(); public ushort ReadRawBigEndian16() { var data = ReadNext(2); return (ushort) ((data[0] << 8) | (data[1])); } public uint ReadRawBigEndian32() { var data = ReadNext(4); return (uint) ((data[0] << 24) | (data[1] << 16) | (data[2] << 8) | (data[3])); } public ulong ReadRawBigEndian64() { var data = ReadNext(8); return ((ulong) data[0] << 56) | ((ulong) data[1] << 48) | ((ulong) data[2] << 40) | ((ulong) data[3] << 32) | ((ulong) data[4] << 24) | ((ulong) data[5] << 16) | ((ulong) data[6] << 8) | data[7]; } private byte ReadNext() { if (_offset + 1 > _buffer.Length) throw new TinyMsgPackDeserializeException("MsgPackReader - out of buffer range"); var ret = _buffer[_offset]; _offset++; return ret; } private NativeSlice<byte> ReadNext(int length) { if (_offset + length > _buffer.Length) throw new TinyMsgPackDeserializeException("MsgPackReader - out of buffer range"); var slice = _buffer.Slice(_offset, length); _offset += length; return slice; } } }
using System; using System.Collections.Generic; using System.Runtime.InteropServices.ComTypes; using Car.Business.Interfaces; using Car.Domain.Entities; using Car.Services.Interfaces; namespace Car.Services { public class CarServices : ICarServices { private readonly ICarBusiness _carBusiness; public CarServices(ICarBusiness carBusiness) { _carBusiness = carBusiness; } public void Delete(Guid key) { _carBusiness.Delete(key); } public CarEntity Insert(CarEntity car) { return _carBusiness.Insert(car); } public List<CarEntity> GetAll() { return _carBusiness.GetAll(); } public List<CarEntity> GetByBrand(string brand) { return _carBusiness.GetByBrand(brand); } } }
using SMA.Backup.Source.Model; using SMA.Backup.Source.Framework; using System.Threading.Tasks; using SMA.Backup.Source.Configuration; namespace SMA.Backup.Source.Handler { public class SourceHandler : ISourceHandler { private readonly ISqlServerSource _sqlServerSource; private readonly IMongoDbSource _mongoDbSource; public SourceHandler(ISqlServerSource sqlServerSource, IMongoDbSource mongoDbSource) { _sqlServerSource = sqlServerSource; _mongoDbSource = mongoDbSource; } public Task<OutputModel> CreateBackup(ISourceConfiguration configuration) { if (configuration is SqlServerConfiguration) return _sqlServerSource.Backup(configuration); if (configuration is MongoDbConfiguration) return _mongoDbSource.Backup(configuration); return new Task<OutputModel>(SourceNullOutputModel.Instance); } } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Security.AccessControl; using System.Security.Principal; using System.Text; using System.Text.RegularExpressions; using BuildXL.Native.IO; using BuildXL.Utilities; using Microsoft.Win32.SafeHandles; using Test.BuildXL.TestUtilities.Xunit; using Xunit; using static BuildXL.Native.IO.Windows.FileUtilitiesWin; using NativeLogEventId = BuildXL.Native.Tracing.LogEventId; namespace Test.BuildXL.Storage { [TestClassIfSupported(requiresWindowsBasedOperatingSystem: true)] public sealed class FileUtilitiesUnsafeTests : TemporaryStorageTestBase { public FileUtilitiesUnsafeTests() { RegisterEventSource(global::BuildXL.Native.ETWLogger.Log); } [Fact] public void DeleteDirectoryContentsHandleOpen() { string directory = Path.Combine(TemporaryDirectory, "directoryToDelete"); Directory.CreateDirectory(directory); string openFile = Path.Combine(directory, "openfileDelDirContents.txt"); using (Stream s = new FileStream(openFile, FileMode.Create)) { s.Write(new byte[] { 1, 2, 3 }, 0, 3); try { FileUtilities.DeleteDirectoryContents(directory); XAssert.IsTrue(false, "Unreachable"); } catch (BuildXLException ex) { XAssert.IsTrue(ex.LogEventMessage.Contains(FileUtilitiesMessages.FileDeleteFailed + NormalizeDirectoryPath(openFile)), ex.LogEventMessage); XAssert.IsTrue(ex.LogEventMessage.Contains("Handle was used by"), ex.LogEventMessage); } } // Try again with the handle closed. There should be no crash. FileUtilities.DeleteDirectoryContents(directory); // Clean up files so we don't leave undeletable files on disk FileUtilities.DeleteDirectoryContents(directory, deleteRootDirectory: true); } [Fact] public void CreateReplacementFileRecreatesWhenDenyWriteACLPresent() { const string Target = @"Target"; FileId originalId; using (FileStream original = File.Create(GetFullPath(Target))) { originalId = FileUtilities.ReadFileUsnByHandle(original.SafeFileHandle).Value.FileId; } AddDenyWriteACL(GetFullPath(Target)); using (FileStream fs = FileUtilities.CreateReplacementFile(GetFullPath(Target), FileShare.Read | FileShare.Delete)) { XAssert.IsNotNull(fs); XAssert.AreNotEqual(originalId, FileUtilities.ReadFileUsnByHandle(fs.SafeFileHandle).Value.FileId, "File was truncated rather than replaced"); XAssert.AreEqual(0, fs.Length); fs.WriteByte(1); } } [Fact] public void CreateReplacementFileRecreatesAfterRemovingReadonlyFlag() { const string Target = @"Target"; FileId originalId; using (FileStream original = File.Create(GetFullPath(Target))) { originalId = FileUtilities.ReadFileUsnByHandle(original.SafeFileHandle).Value.FileId; } SetReadonlyFlag(GetFullPath(Target)); using (FileStream fs = FileUtilities.CreateReplacementFile(GetFullPath(Target), FileShare.Read | FileShare.Delete)) { XAssert.IsNotNull(fs); XAssert.AreNotEqual(originalId, FileUtilities.ReadFileUsnByHandle(fs.SafeFileHandle).Value.FileId, "File was truncated rather than replaced"); XAssert.AreEqual(0, fs.Length); fs.WriteByte(1); } } [Fact] public void CreateReplacementFileReplacesAfterRemovingReadonlyFlagIfDenyWriteACLPresent() { const string Target = @"Target"; FileId originalId; using (FileStream original = File.Create(GetFullPath(Target))) { originalId = FileUtilities.ReadFileUsnByHandle(original.SafeFileHandle).Value.FileId; } SetReadonlyFlag(GetFullPath(Target)); AddDenyWriteACL(GetFullPath(Target)); using (FileStream fs = FileUtilities.CreateReplacementFile(GetFullPath(Target), FileShare.Read | FileShare.Delete)) { XAssert.IsNotNull(fs); XAssert.AreNotEqual(originalId, FileUtilities.ReadFileUsnByHandle(fs.SafeFileHandle).Value.FileId, "File was truncated rather than replaced"); XAssert.AreEqual(0, fs.Length); fs.WriteByte(1); } } [Fact] public void RetryEmptyDirectoryDelete() { // Create an empty directory string dir = Path.Combine(TemporaryDirectory, "dir"); Directory.CreateDirectory(dir); SafeFileHandle childHandle = null; FileUtilities.TryCreateOrOpenFile( dir, FileDesiredAccess.GenericRead, FileShare.Read, FileMode.Open, FileFlagsAndAttributes.FileFlagBackupSemantics, out childHandle); using (childHandle) { Exception exception = null; try { // Fails because of handle open to /dir FileUtilities.DeleteDirectoryContents(dir, deleteRootDirectory: true); } catch (Exception e) { exception = e; } XAssert.IsNotNull(exception); XAssert.IsTrue(FileUtilities.Exists(dir)); } AssertVerboseEventLogged(NativeLogEventId.RetryOnFailureException, Helpers.DefaultNumberOfAttempts); FileUtilities.DeleteDirectoryContents(dir, deleteRootDirectory: true); XAssert.IsFalse(FileUtilities.Exists(dir)); } /// <summary> /// Check that <see cref="FileUtilities.DeleteDirectoryContents(string, bool, System.Func{string,bool}(string))"/> retries /// on ERROR_DIR_NOT_EMPTY when deleting an empty directory immediately after verifying the deletion of that same directories contents /// </summary> /// <remarks> /// When attempting to recursively delete directory contents, there may be times when /// we successfully delete a file or subdirectory then immediately try to delete the parent directory /// and receive ERROR_DIR_NOT_EMPTY due to Windows marking the deleted file or subdirectory as pending /// deletion. In these cases, we should back off and retry. /// <see cref="FileUtilities.IsPendingDelete(SafeFileHandle)"/> for more information. /// </remarks> [Fact] public void RetryDeleteDirectoryContentsIfContentsPendingDelete() { try { // Need to disable POSIX delete to reproduce the Windows pending deletion state, // which does not exist in POSIX FileUtilities.PosixDeleteMode = PosixDeleteMode.NoRun; string dir = Path.Combine(TemporaryDirectory, "dir"); Directory.CreateDirectory(dir); string nestedFile = Path.Combine(dir, "nestedFile"); File.WriteAllText(nestedFile, "asdf"); SafeFileHandle nestedFileHandle; FileUtilities.TryCreateOrOpenFile( nestedFile, FileDesiredAccess.GenericWrite, FileShare.ReadWrite | FileShare.Delete, FileMode.Open, FileFlagsAndAttributes.None, out nestedFileHandle); // Hold open a handle to \file, but allow all file sharing permissions using (nestedFileHandle) { // Sanity check that pending delete doesn't always return true XAssert.IsFalse(FileUtilities.IsPendingDelete(nestedFileHandle)); Exception exception = null; try { // Fails because of the open file that cannot be deleted FileUtilities.DeleteDirectoryContents(dir, true); } catch (BuildXLException e) { exception = e; XAssert.IsTrue(e.Message.StartsWith(FileUtilitiesMessages.DeleteDirectoryContentsFailed + NormalizeDirectoryPath(dir))); // Rebuild the exception message using StringBuilder to handle breaklines StringBuilder builder = new StringBuilder(); builder.AppendLine(NormalizeDirectoryPath(nestedFile)); builder.AppendLine(FileUtilitiesMessages.NoProcessesUsingHandle); builder.AppendLine(FileUtilitiesMessages.PathMayBePendingDeletion); XAssert.IsTrue(e.Message.Contains(builder.ToString())); } XAssert.IsTrue(exception != null); // Check the open handle forced the file to be placed on the Windows pending deletion queue XAssert.IsTrue(FileUtilities.IsPendingDelete(nestedFileHandle)); } // After the file handle is closed, the delete goes through XAssert.IsFalse(File.Exists(nestedFile)); // Check for retries and ERROR_DIR_NOT_EMPTY AssertVerboseEventLogged(NativeLogEventId.RetryOnFailureException, Helpers.DefaultNumberOfAttempts); string logs = EventListener.GetLog(); var numMatches = Regex.Matches(logs, Regex.Escape("Native: RemoveDirectoryW for RemoveDirectory failed (0x91: The directory is not empty")).Count; XAssert.AreEqual(Helpers.DefaultNumberOfAttempts, numMatches); } finally { // Re-enable POSIX delete for the remainder of tests FileUtilities.PosixDeleteMode = PosixDeleteMode.RunFirst; } } [Fact] public void TestFindAllOpenHandlesInDirectory() { string topDir = Path.Combine(TemporaryDirectory, "top"); Directory.CreateDirectory(topDir); string nestedDir = Path.Combine(topDir, "nestedDir"); Directory.CreateDirectory(nestedDir); // top-level file handle to look for string nestedFile = Path.Combine(topDir, "nestedFile"); File.WriteAllText(nestedFile, "asdf"); // recursive file handle to look for string doubleNestedFile = Path.Combine(nestedDir, "doubleNestedFile"); File.WriteAllText(doubleNestedFile, "hjkl"); string openHandles; string openHandleNestedFile = FileUtilitiesMessages.ActiveHandleUsage + nestedFile; string openHandleDoubleNestedFile = FileUtilitiesMessages.ActiveHandleUsage + doubleNestedFile; // Hold open handles to both files using (new FileStream(nestedFile, FileMode.Open)) { using (new FileStream(doubleNestedFile, FileMode.Open)) { openHandles = FileUtilities.FindAllOpenHandlesInDirectory(topDir); XAssert.IsTrue(openHandles.Contains(openHandleNestedFile)); XAssert.IsTrue(openHandles.Contains(openHandleDoubleNestedFile)); } } openHandles = FileUtilities.FindAllOpenHandlesInDirectory(topDir); XAssert.IsFalse(openHandles.Contains(openHandleNestedFile)); XAssert.IsFalse(openHandles.Contains(openHandleDoubleNestedFile)); } /// <summary> /// If a file or directory is on the Windows pending deletion queue, /// no process will report having an open handle /// </summary> [FactIfSupported(requiresHeliumDriversNotAvailable: true)] public void FailToFindAllOpenHandlesPendingDeletion() { string dir = Path.Combine(TemporaryDirectory, "dir"); Directory.CreateDirectory(dir); string file = Path.Combine(dir, "file"); File.WriteAllText(file, "asdf"); SafeFileHandle fileHandle; FileUtilities.TryCreateOrOpenFile( file, FileDesiredAccess.GenericWrite, FileShare.ReadWrite | FileShare.Delete, FileMode.Open, FileFlagsAndAttributes.None, out fileHandle); // Hold open a handle to \file, but allow all file sharing permissions using (fileHandle) { XAssert.IsFalse(FileUtilities.IsPendingDelete(fileHandle)); // This will succeed without throwing an exception File.Delete(file); // But the open handle forces the file to be placed on a pending deletion queue XAssert.IsTrue(FileUtilities.IsPendingDelete(fileHandle)); // Fail to detect open handles for files pending deletion HashSet<string> deletedPaths = new HashSet<string>() { file }; string openHandles = FileUtilities.FindAllOpenHandlesInDirectory(TemporaryDirectory, pathsPossiblyPendingDelete: deletedPaths); // Rebuild the exception message using StringBuilder to handle breaklines StringBuilder builder = new StringBuilder(); builder.AppendLine(file); builder.AppendLine(FileUtilitiesMessages.NoProcessesUsingHandle); builder.AppendLine(FileUtilitiesMessages.PathMayBePendingDeletion); // Before Windows 10 Version 1903, attempting to create a file handle to a file pending deletion would throw an access exception, including calling File.Exists // With Windows 10 Version 1903 and later, creating handles to files on the pending deletion queue does not throw exceptions and pending deletion files are considered deleted by File.Exists // This change in behavior is NOT true for directories, see testing below for the directory behavior XAssert.IsTrue(openHandles.Contains(builder.ToString()) || /* Check for Windows 10 Version 1903 and later */ !File.Exists(file)); XAssert.IsFalse(openHandles.Contains(FileUtilitiesMessages.ActiveHandleUsage + file)); } XAssert.IsFalse(File.Exists(file)); SafeFileHandle dirHandle; FileUtilities.TryCreateOrOpenFile( dir, FileDesiredAccess.GenericWrite, FileShare.ReadWrite | FileShare.Delete, FileMode.Open, FileFlagsAndAttributes.FileFlagBackupSemantics, out dirHandle); // Hold open a handle to \dir, but allow all sharing permissions using (dirHandle) { XAssert.IsFalse(FileUtilities.IsPendingDelete(dirHandle)); // This will succeed without throwing an exception Directory.Delete(dir); // But the open handle forces the directory to be placed on a pending deletion queue XAssert.IsTrue(FileUtilities.IsPendingDelete(dirHandle)); // Fail to detect open handles for dirs pending deletion HashSet<string> deletedPaths = new HashSet<string>() { dir }; string openHandles = FileUtilities.FindAllOpenHandlesInDirectory(TemporaryDirectory, pathsPossiblyPendingDelete: deletedPaths); // Rebuild the exception message using StringBuilder to handle breaklines StringBuilder builder = new StringBuilder(); builder.AppendLine(dir); builder.AppendLine(FileUtilitiesMessages.NoProcessesUsingHandle); builder.AppendLine(FileUtilitiesMessages.PathMayBePendingDeletion); // Windows 10 Version 2004 unified the pending deletion queue behavior for files and directories. // With Windows 10 Version 2004 and later, directories that are in pending deletion queue are not discoverable by FindFirstFileW WinAPI // and are considered deleted by Directory.Exists(dir). XAssert.IsTrue(openHandles.Contains(builder.ToString()) || /* Check for Windows 10 Version 2004 and later */ !Directory.Exists(dir)); XAssert.IsFalse(openHandles.Contains(FileUtilitiesMessages.ActiveHandleUsage + dir)); } XAssert.IsFalse(Directory.Exists(dir)); } [Fact] public void TestDeleteDirectoryContentsWithExclusions() { // \topDir string topDir = Path.Combine(TemporaryDirectory, "top"); Directory.CreateDirectory(topDir); // \topDir\nestedDir string nestedDir = Path.Combine(topDir, "nestedDir"); Directory.CreateDirectory(nestedDir); // \topDir\nestedFile string nestedFile = Path.Combine(topDir, "nestedFile"); File.WriteAllText(nestedFile, "asdf"); // \topDir\nestedDir\doubleNestedFile string doubleNestedFile = Path.Combine(nestedDir, "doubleNestedFile"); File.WriteAllText(doubleNestedFile, "hjkl"); FileUtilities.DeleteDirectoryContents( path: topDir, deleteRootDirectory: true, shouldDelete: (path) => { // exclude \nestedDir\* return !path.Contains(nestedDir); }); // Even though deleteRootDirectory was marked as true, // \topDir should still exist because \topDir\nestedDir was excluded XAssert.IsTrue(Directory.Exists(topDir)); // Successfully delete non-excluded file XAssert.IsFalse(File.Exists(nestedFile)); // Excluded entries stay XAssert.IsTrue(Directory.Exists(nestedDir)); XAssert.IsTrue(File.Exists(doubleNestedFile)); } /// <summary> /// A stress test that rapidly creates and deletes directories, /// a worst case scenario for successfully deleting directories in Windows. /// This passes, but is disabled since it takes a significant amount of time. /// </summary> [Fact(Skip = "Long running test")] public void PosixDeleteDirectoryStressTest() { FileUtilities.PosixDeleteMode = PosixDeleteMode.RunFirst; string target = Path.Combine(TemporaryDirectory, "loop"); string nested = Path.Combine(target, "nested"); for (int i = 0; i < 100000; ++i) { Directory.CreateDirectory(target); Directory.CreateDirectory(nested); FileUtilities.DeleteDirectoryContents(target, deleteRootDirectory: true); } } /// <summary> /// A stress test that rapidly creates and deletes directories, /// a worst case scenario for successfully deleting directories in Windows. /// This passes, but is disabled since it takes a significant amount of time. /// </summary> /// <remarks> /// The move-delete stress test takes noticably longer than the POSIX-delete stress test. /// This may be worth looking into for performance. /// </remarks> [Fact(Skip = "Long running test")] public void MoveDeleteDirectoryStressTest() { try { FileUtilities.PosixDeleteMode = PosixDeleteMode.NoRun; string target = Path.Combine(TemporaryDirectory, "loop"); string nested = Path.Combine(target, "nested"); for (int i = 0; i < 100000; ++i) { Directory.CreateDirectory(target); Directory.CreateDirectory(nested); FileUtilities.DeleteDirectoryContents(target, deleteRootDirectory: true, tempDirectoryCleaner: MoveDeleteCleaner); } } finally { FileUtilities.PosixDeleteMode = PosixDeleteMode.RunFirst; } } /// <summary> /// A stress test that rapidly creates and deletes directories, /// a worst case scenario for successfully deleting directories in Windows. /// This passes, but is disabled since it takes a significant amount of time (minutes). /// </summary> /// <remarks> /// This test does not test any BuildXL code, but exists to document the behavior /// of Windows deletes. /// </remarks> [Theory(Skip = "Long running test")] [InlineData(100000)] public void DeleteDirectoryStressTest(int numDirs) { string target = Path.Combine(TemporaryDirectory, "loop"); string nested = Path.Combine(target, "nested"); Exception exception = null; try { for (int i = 0; i < numDirs; ++i) { Directory.CreateDirectory(target); Directory.CreateDirectory(nested); Directory.Delete(target, recursive: true); } } catch (UnauthorizedAccessException ex) { // Access denied when trying to create \nested. Directory.CreateDirectory(nested) // likely could not obtain a handle to the directory while it was pending deletion. exception = ex; } catch (DirectoryNotFoundException ex) { // Cannot find part of path when trying to create \nested (immediately after creating \target) // This implies CreateDirectory(target) failed without throwing any exceptions. The directory likely // existed during CreateDirectory(target), but was deleted before Directory.CreateDirectory(nested) // completed. exception = ex; } XAssert.IsFalse(exception == null); // exception occurs during creation of one of the directories XAssert.IsTrue(exception.StackTrace.ToString().Contains("System.IO.Directory.InternalCreateDirectoryHelper")); } /// <summary> /// Sanity check that links to running executables are tricky to delete. /// </summary> /// <remarks> /// BuildXL's CreateHardlink method relies on CreateHardlinkW, which requires WriteAttributes access on the file. /// </remarks> [Fact] public void TrivialDeleteFailsForLinkToRunningExecutable() { string exeLink = GetFullPath("DummyWaiterLink"); XAssert.IsTrue(CreateHardLinkIfSupported(link: exeLink, linkTarget: DummyWaiter.GetDummyWaiterExeLocation())); using (var waiter = DummyWaiter.RunAndWait()) { try { File.Delete(exeLink); XAssert.Fail("Expected deletion to fail due to the executable being loaded and running."); } catch (UnauthorizedAccessException) { // expected. } catch (IOException) { // expected. } } // Should succeed when the executable is no longer running. FileUtilities.DeleteFile(exeLink); } /// <remarks> /// BuildXL's CreateHardlink method relies on CreateHardlinkW, which requires WriteAttributes access on the file. /// </remarks> [Fact] public void CreateReplacementFileCanReplaceRunningExecutableLink() { string exeLink = GetFullPath("DummyWaiterLink"); XAssert.IsTrue(CreateHardLinkIfSupported(link: exeLink, linkTarget: DummyWaiter.GetDummyWaiterExeLocation())); using (var waiter = DummyWaiter.RunAndWait()) { using (FileStream fs = FileUtilities.CreateReplacementFile(exeLink, FileShare.Delete)) { XAssert.AreEqual(0, fs.Length); } } } /// <remarks> /// BuildXL's CreateHardlink method relies on CreateHardlinkW, which requires WriteAttributes access on the file. /// </remarks> [Fact] public void MoveTempDeletionCanReplaceRunningExecutable() { // Make a copy of DummyWaiter.exe to use as the test subject for deleting a running executable. // Keep the copy in the same directory as the original since it will need runtime dlls string dummyWaiterLocation = DummyWaiter.GetDummyWaiterExeLocation(); string exeCopy = dummyWaiterLocation + ".copy.exe"; File.Copy(dummyWaiterLocation, exeCopy); using (var waiter = DummyWaiter.RunAndWait(exeCopy)) { BuildXLException caughtException = null; try { FileUtilities.DeleteFile(exeCopy); } catch (BuildXLException ex) { caughtException = ex; } XAssert.IsNotNull(caughtException, "Expected deletion without a tempCleaner to fail"); XAssert.IsTrue(File.Exists(exeCopy)); caughtException = null; try { FileUtilities.DeleteFile(exeCopy, tempDirectoryCleaner: MoveDeleteCleaner); } catch (BuildXLException ex) { caughtException = ex; } XAssert.IsNull(caughtException, "Expected deletion with a MoveDeleteCleaner to succeed"); XAssert.IsFalse(File.Exists(exeCopy)); } } /// <remarks> /// BuildXL's CreateHardlink method relies on CreateHardlinkW, which requires WriteAttributes access on the file. /// </remarks> [Fact] public void CanDeleteRunningExecutableLink() { string exeLink = GetFullPath("DummyWaiterLink"); XAssert.IsTrue(CreateHardLinkIfSupported(link: exeLink, linkTarget: DummyWaiter.GetDummyWaiterExeLocation())); using (var waiter = DummyWaiter.RunAndWait()) { XAssert.IsTrue(File.Exists(exeLink)); FileUtilities.DeleteFile(exeLink); XAssert.IsFalse(File.Exists(exeLink)); } } [Fact] public void CanDeleteReadonlyFile() { string file = GetFullPath("File"); File.WriteAllText(file, string.Empty); SetReadonlyFlag(file); XAssert.IsTrue(File.Exists(file)); FileUtilities.DeleteFile(file); XAssert.IsFalse(File.Exists(file)); } [FactIfSupported(requiresAdmin: true)] public void CanDeleteFileWithDenyACL() { string file = GetFullPath("File with space"); string directory = Path.GetDirectoryName(file); File.WriteAllText(file, string.Empty); try { FileInfo fi = new FileInfo(file); FileSecurity accessControl = fi.GetAccessControl(AccessControlSections.All); accessControl.PurgeAccessRules(WindowsIdentity.GetCurrent().User); accessControl.AddAccessRule(new FileSystemAccessRule(WindowsIdentity.GetCurrent().User, FileSystemRights.FullControl, AccessControlType.Deny)); fi.SetAccessControl(accessControl); DirectoryInfo di = new DirectoryInfo(directory); DirectorySecurity ds = di.GetAccessControl(AccessControlSections.All); ds.PurgeAccessRules(WindowsIdentity.GetCurrent().User); ds.AddAccessRule(new FileSystemAccessRule(WindowsIdentity.GetCurrent().User, FileSystemRights.CreateFiles, AccessControlType.Deny)); di.SetAccessControl(ds); XAssert.IsTrue(File.Exists(file)); FileUtilities.DeleteFile(file); XAssert.IsFalse(File.Exists(file)); } finally { DirectoryInfo di = new DirectoryInfo(directory); DirectorySecurity ds = di.GetAccessControl(AccessControlSections.All); ds.PurgeAccessRules(WindowsIdentity.GetCurrent().User); ds.AddAccessRule(new FileSystemAccessRule(WindowsIdentity.GetCurrent().User, FileSystemRights.FullControl, AccessControlType.Allow)); di.SetAccessControl(ds); di.Delete(true); } } [FactIfSupported(requiresAdmin: true)] public void CanDeleteReadonlyDenyWriteAttribute() { string file = GetFullPath("File"); string directory = Path.GetDirectoryName(file); File.WriteAllText(file, string.Empty); // Make the file readonly & deny modifying attributes FileInfo fi = new FileInfo(file); fi.IsReadOnly = true; FileSecurity accessControl = fi.GetAccessControl(AccessControlSections.All); accessControl.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), FileSystemRights.WriteAttributes, AccessControlType.Deny)); fi.SetAccessControl(accessControl); // see if we can delete it XAssert.IsTrue(File.Exists(file)); FileUtilities.DeleteFile(file); XAssert.IsFalse(File.Exists(file)); } [Fact] public void TestTryMoveDelete() { string file = Path.Combine(TemporaryDirectory, "file"); File.WriteAllText(file, "asdf"); string trashDirectory = Path.Combine(TemporaryDirectory, "trash"); Directory.CreateDirectory(trashDirectory); using (new FileStream(file, FileMode.Open, FileAccess.ReadWrite, FileShare.Delete)) { FileUtilities.TryMoveDelete(file, trashDirectory); } // Check the file was deleted/moved XAssert.IsFalse(File.Exists(file)); // Check the trash directory the file was moved to is empty XAssert.IsTrue(Directory.GetDirectories(trashDirectory).Length + Directory.GetFiles(trashDirectory).Length == 0); } /// <summary> /// In previous versions of Windows, if any handle to a hardlink is open without FileShare Delete mode, /// no hardlink to the same underlying file can be deleted /// This appears to be fixed in RS3, so this test has inconsistent results on different OSes (it passes in RS3) /// </summary> [Fact(Skip = "Skip")] public void CanDeleteWithOtherOpenHardlinks() { string hardlink1 = Path.Combine(TemporaryDirectory, "hardlink1"); File.WriteAllText(hardlink1, "asdf"); string hardlink2 = Path.Combine(TemporaryDirectory, "hardlink2"); XAssert.IsTrue(CreateHardLinkIfSupported(hardlink2, hardlink1)); // Open a handle to hardlink2 without FileShare Delete mode using (new FileStream(hardlink2, FileMode.Open, FileAccess.Read, FileShare.Read)) { BuildXLException exception = null; try { FileUtilities.DeleteFile(hardlink1); } catch (BuildXLException ex) { exception = ex; } // Successfully delete file XAssert.IsTrue(exception == null); XAssert.IsFalse(File.Exists(hardlink1)); } } /// <remarks> /// BuildXL's CreateHardlink method relies on CreateHardlinkW, which requires WriteAttributes access on the file. /// </remarks> [Fact] public void DeleteDirectoryContents() { string rootDir = GetFullPath("Directory"); Directory.CreateDirectory(rootDir); Directory.CreateDirectory(Path.Combine(rootDir, "subdir1")); Directory.CreateDirectory(Path.Combine(rootDir, "subdir2")); // Create a readonly file string nestedFile = Path.Combine(rootDir, "subdir1", "File.txt"); File.WriteAllText(nestedFile, "asdf"); File.SetAttributes(nestedFile, FileAttributes.ReadOnly); // And a normal file File.WriteAllText(Path.Combine(rootDir, "File.txt"), "asdf"); string exeLink = Path.Combine(rootDir, "hardlink"); XAssert.IsTrue(CreateHardLinkIfSupported(link: exeLink, linkTarget: DummyWaiter.GetDummyWaiterExeLocation())); // Add a hardlink using (var waiter = DummyWaiter.RunAndWait()) { FileUtilities.DeleteDirectoryContents(rootDir); } XAssert.AreEqual(0, Directory.GetFileSystemEntries(rootDir).Length); } /// <summary> /// Tests that <see cref="FileUtilities.Exists(string)"/> returns true positives (file exists when it does), /// where <see cref="File.Exists(string)"/> returns false negatives (file does not exist when it does) /// </summary> [Fact] public void FileUtilitiesExists() { string directory = Path.Combine(TemporaryDirectory, "directory"); Directory.CreateDirectory(directory); string file = Path.Combine(directory, "openfileExists.txt"); File.WriteAllText(file, "asdf"); // Path leads to directory XAssert.IsTrue(FileUtilities.Exists(directory)); XAssert.IsFalse(File.Exists(directory)); // Path is normalized with characters File.Exists considers invalid XAssert.IsTrue(FileUtilities.Exists(@"\\?\" + file)); bool expectedExistenceForLongPath = LongPathsSupported; XAssert.AreEqual(expectedExistenceForLongPath, File.Exists(@"\\?\" + file)); // Remove access permissions to the file var fi = new FileInfo(file); FileSecurity fileSecurity = fi.GetAccessControl(); fileSecurity.AddAccessRule(new FileSystemAccessRule($@"{Environment.UserDomainName}\{Environment.UserName}", FileSystemRights.FullControl, AccessControlType.Deny)); fi.SetAccessControl(fileSecurity); Exception exception = null; try { File.ReadAllText(file); } catch (UnauthorizedAccessException ex) { exception = ex; } // File access successfully removed XAssert.IsNotNull(exception); // Both versions will return correctly XAssert.IsTrue(FileUtilities.Exists(file)); XAssert.IsTrue(File.Exists(file)); // don't leave inaccessible file around FileUtilities.DeleteFile(file, tempDirectoryCleaner: MoveDeleteCleaner); } /// <remarks> /// BuildXL's CreateHardlink method relies on CreateHardlinkW, which requires WriteAttributes access on the file. /// </remarks> [Fact] public void DeleteDirectoryContentsLongPath() { string originalRoot = GetFullPath("testRoot"); // Create a directory with a path that's too long to normally delete StringBuilder sb = new StringBuilder(); for (int i = 0; i < 100; i++) { sb.Append("a"); } string rootDir = @"\\?\" + originalRoot; XAssert.IsTrue(CreateDirectoryW(rootDir, IntPtr.Zero)); rootDir = rootDir + "\\" + sb.ToString(); XAssert.IsTrue(CreateDirectoryW(rootDir, IntPtr.Zero)); rootDir = rootDir + "\\" + sb.ToString(); XAssert.IsTrue(CreateDirectoryW(rootDir, IntPtr.Zero)); // Write some files in the directory. Set their attributes as readonly to exercise the related logic in DeleteFile string shorterPath = Path.Combine(originalRoot, "myFile.txt"); File.WriteAllText(shorterPath, "foo"); File.SetAttributes(shorterPath, FileAttributes.ReadOnly); // And a file with a filename longer than maxpath string longerPath = rootDir + @"\myFile.txt"; SafeFileHandle fileHandle; var result = FileUtilities.TryCreateOrOpenFile( longerPath, FileDesiredAccess.GenericWrite, FileShare.Delete, FileMode.Create, FileFlagsAndAttributes.FileAttributeNormal, out fileHandle); XAssert.IsTrue(result.Succeeded); using (FileStream stream = new FileStream(fileHandle, FileAccess.Write)) { stream.WriteByte(255); } FileUtilities.SetFileAttributes(longerPath, FileAttributes.ReadOnly); string exeLink = Path.Combine(rootDir, "hardlink"); XAssert.IsTrue(CreateHardLinkIfSupported(link: exeLink, linkTarget: DummyWaiter.GetDummyWaiterExeLocation())); // Add a hardlink. Perform deletion attempts while the hardlink target is in use using (var waiter = DummyWaiter.RunAndWait()) { // Attempt to delete with the managed API. This should fail because it contains nested paths that are too long bool isPathTooLong = false; try { Directory.Delete(rootDir, recursive: true); } catch (UnauthorizedAccessException) { // expected: when the long paths are supported, then // CreateHardLinkW would be finished successfully, // and directory deletion will fail because the executable is still running. } catch (PathTooLongException) { isPathTooLong = true; } // Expect failure only if long paths are not supported by the current .NET Framework version. bool expectedIsPathTooLong = !LongPathsSupported; XAssert.AreEqual(expectedIsPathTooLong, isPathTooLong, "Expected to encounter a PathTooLongException. If no exception is thrown by the System.IO method, this test isn't validating anything"); // Now use the native API. This should succeed FileUtilities.DeleteDirectoryContents(originalRoot); } XAssert.IsTrue(Directory.Exists(originalRoot)); XAssert.AreEqual(0, Directory.GetFileSystemEntries(originalRoot).Length); } [Fact] public void CreateHardlinkSupportsLongPath() { var rootDir = Path.Combine(TemporaryDirectory, "dir"); var longPath = Enumerable.Range(0, NativeIOConstants.MaxDirectoryPath).Aggregate(rootDir, (path, _) => Path.Combine(path, "dir")); FileUtilities.CreateDirectory(longPath); var file = Path.Combine(longPath, "out.txt"); var link = Path.Combine(longPath, "hardlink"); SafeFileHandle fileHandle; var result = FileUtilities.TryCreateOrOpenFile( file, FileDesiredAccess.GenericWrite, FileShare.Delete, FileMode.Create, FileFlagsAndAttributes.FileAttributeNormal, out fileHandle); XAssert.IsTrue(result.Succeeded); using (FileStream stream = new FileStream(fileHandle, FileAccess.Write)) { stream.WriteByte(255); } XAssert.IsTrue(CreateHardLinkIfSupported(link: link, linkTarget: file)); FileUtilities.DeleteDirectoryContents(rootDir, deleteRootDirectory: true); } [Fact] public void TryFindOpenHandlesToFileWithFormatString() { var fileNameWithCurly = Path.Combine(TemporaryDirectory, "fileWith{curly}InName"); XAssert.IsTrue(FileUtilities.TryFindOpenHandlesToFile(fileNameWithCurly, out var diag)); } [Fact] public void LongPathAccessControlTest() { // Skip this test if running on .NET Framework with vstest // Reason: new FileInfo(longPath) fails with PathTooLongException (interestingly, it works fine when executed by xunit) if (!OperatingSystemHelper.IsDotNetCore && IsRunningInVsTestTestHost()) { return; } var rootDir = Path.Combine(TemporaryDirectory, "dir"); var longPath = Enumerable.Range(0, NativeIOConstants.MaxDirectoryPath).Aggregate(rootDir, (path, _) => Path.Combine(path, "dir")); var file = Path.Combine(longPath, "fileWithWriteAccess.txt"); FileUtilities.CreateDirectory(longPath); SafeFileHandle fileHandle; var result = FileUtilities.TryCreateOrOpenFile( file, FileDesiredAccess.GenericWrite, FileShare.Delete, FileMode.Create, FileFlagsAndAttributes.FileAttributeNormal, out fileHandle); XAssert.IsTrue(result.Succeeded); FileUtilities.SetFileAccessControl(file, FileSystemRights.WriteAttributes, true); XAssert.IsTrue(FileUtilities.HasWritableAccessControl(file)); // Delete the created directory fileHandle.Close(); FileUtilities.DeleteDirectoryContents(rootDir, deleteRootDirectory: true); XAssert.FileDoesNotExist(file); } private static void SetReadonlyFlag(string path) { File.SetAttributes(path, FileAttributes.Normal | FileAttributes.ReadOnly); } private static void AddDenyWriteACL(string path) { AddDenyACL(path, FileSystemRights.WriteData | FileSystemRights.AppendData); } private static void AddDenyACL(string path, FileSystemRights deny) { ModifyDenyACL(path, deny, add: true); } private static void ModifyDenyACL(string path, FileSystemRights deny, bool add) { var fileInfo = new FileInfo(path); var security = fileInfo.GetAccessControl(); var rule = new FileSystemAccessRule( new SecurityIdentifier(WellKnownSidType.WorldSid, null), deny, AccessControlType.Deny); if (add) { security.AddAccessRule(rule); } else { security.RemoveAccessRule(rule); } fileInfo.SetAccessControl(security); } [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, ExactSpelling = true)] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool CreateDirectoryW( string lpPathName, IntPtr lpSecurityAttributes); private static bool CreateHardLinkIfSupported(string link, string linkTarget) { CreateHardLinkStatus status = FileUtilities.TryCreateHardLink(link: link, linkTarget: linkTarget); if (status == CreateHardLinkStatus.Success) { return true; } if (status == CreateHardLinkStatus.FailedSinceNotSupportedByFilesystem && !OperatingSystemHelper.IsUnixOS) { return false; } if(status == CreateHardLinkStatus.Failed) { return false; } XAssert.Fail("Creating a hardlink failed unexpectedly: {0:G}", status); return false; } /// <summary> /// Returns true if paths longer then 260 characters are supported. /// </summary> private static bool LongPathsSupported { get; } = GetLongPathSupport(); private static bool GetLongPathSupport() { string longString = new string('a', NativeIOConstants.MaxPath + 1); try { string path = $@"\\?\c:\foo{longString}.txt"; var directoryName = System.IO.Path.GetDirectoryName(path); return true; } catch (PathTooLongException) { return false; } } private string NormalizeDirectoryPath(string path) { return new global::BuildXL.Native.IO.Windows.FileUtilitiesWin(LoggingContext).NormalizeDirectoryPath(path); } } }
using Masny.TimeTracker.Data.Models; using Masny.TimeTracker.Logic.Interfaces; using Masny.TimeTracker.WebApi.Contracts.Requests; using Masny.TimeTracker.WebApi.Contracts.Responses; using Masny.TimeTracker.WebApi.Settings; using Masny.TimeTracker.WebApp.Shared.Models; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Options; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Masny.TimeTracker.WebApi.Controllers { [Route("api/[controller]")] [ApiController] public class UserController : ControllerBase { private SignInManager<User> _signInManager; private UserManager<User> _userManager; private IJwtService _jwtService; private readonly AppSettings _appSettings; public UserController( SignInManager<User> signInManager, UserManager<User> userManager, IJwtService jwtService, IOptions<AppSettings> appSettings) { _signInManager = signInManager ?? throw new ArgumentNullException(nameof(signInManager)); _userManager = userManager ?? throw new ArgumentNullException(nameof(userManager)); _jwtService = jwtService ?? throw new ArgumentNullException(nameof(jwtService)); if (appSettings is null) { throw new ArgumentNullException(nameof(appSettings)); } _appSettings = appSettings.Value; } [HttpPost("login")] public async Task<IActionResult> LoginAsync(UserLoginRequest model) { var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, false, false); if (!result.Succeeded) { return BadRequest(new { message = "Email or password is incorrect" }); } var user = await _userManager.FindByEmailAsync(model.Email); var token = _jwtService.GenerateJwtToken(user.Id, _appSettings.Secret); var userRoles = await _userManager.GetRolesAsync(user); var response = new AuthenticateResponse(user, token, userRoles); return Ok(response); } [HttpPost("registration")] public async Task<IActionResult> RegistrationAsync(UserRegistationRequest request) { var user = new User { Email = request.Email, UserName = request.Email, FullName = request.FullName, IsActive = true, }; var result = await _userManager.CreateAsync(user, request.Password); await _userManager.AddToRoleAsync(user, "User"); if (!result.Succeeded) { //foreach (var error in result.Errors) //{ // ModelState.AddModelError("errors", error.Description); //} //return BadRequest(ModelState); return BadRequest(new ErrorResponse<string> { Message = "Can't registration new user.", Errors = result.Errors.Select(error => error.Description) }); } var token = _jwtService.GenerateJwtToken(user.Id, _appSettings.Secret); var userRoles = await _userManager.GetRolesAsync(user); var response = new AuthenticateResponse(user, token, userRoles); return Ok(response); } // UNDONE: DELETE IT [HttpPost("test")] public async Task<IActionResult> TestAsync() { var email = "test@test.test"; var user = await _userManager.FindByEmailAsync(email); var token = _jwtService.GenerateJwtToken(user.Id, _appSettings.Secret); var userRoles = await _userManager.GetRolesAsync(user); var response = new AuthenticateResponse(user, token, userRoles); return Ok(response); } } }
public class PhaseProgressEvent : GameEvent { public float progress; public PhaseProgressEvent(float progress) { this.progress = progress; } }
using UnityEngine; using UnityEngine.TextCore; using System.Collections.Generic; using System.Linq; namespace TMPro { public class TMP_SpriteAsset : TMP_Asset { internal Dictionary<uint, int> m_UnicodeLookup; internal Dictionary<int, int> m_NameLookup; internal Dictionary<uint, int> m_GlyphIndexLookup; /// <summary> /// The version of the sprite asset class. /// Version 1.1.0 updates the asset data structure to be compatible with new font asset structure. /// </summary> public string version { get { return m_Version; } internal set { m_Version = value; } } [SerializeField] private string m_Version; // The texture which contains the sprites. public Texture spriteSheet; public List<TMP_SpriteCharacter> spriteCharacterTable { get { if (m_GlyphIndexLookup == null) UpdateLookupTables(); return m_SpriteCharacterTable; } internal set { m_SpriteCharacterTable = value; } } [SerializeField] private List<TMP_SpriteCharacter> m_SpriteCharacterTable = new List<TMP_SpriteCharacter>(); public List<TMP_SpriteGlyph> spriteGlyphTable { get { return m_SpriteGlyphTable; } internal set { m_SpriteGlyphTable = value; } } [SerializeField] private List<TMP_SpriteGlyph> m_SpriteGlyphTable = new List<TMP_SpriteGlyph>(); // List which contains the SpriteInfo for the sprites contained in the sprite sheet. public List<TMP_Sprite> spriteInfoList; /// <summary> /// Dictionary used to lookup the index of a given sprite based on a Unicode value. /// </summary> //private Dictionary<int, int> m_SpriteUnicodeLookup; /// <summary> /// List which contains the Fallback font assets for this font. /// </summary> [SerializeField] public List<TMP_SpriteAsset> fallbackSpriteAssets; internal bool m_IsSpriteAssetLookupTablesDirty = false; void Awake() { // Check version number of sprite asset to see if it needs to be upgraded. if (this.material != null && string.IsNullOrEmpty(m_Version)) UpgradeSpriteAsset(); } #if UNITY_EDITOR /// <summary> /// /// </summary> void OnValidate() { //Debug.Log("Sprite Asset [" + name + "] has changed."); //UpdateLookupTables(); //TMPro_EventManager.ON_SPRITE_ASSET_PROPERTY_CHANGED(true, this); } #endif /// <summary> /// Create a material for the sprite asset. /// </summary> /// <returns></returns> Material GetDefaultSpriteMaterial() { //isEditingAsset = true; ShaderUtilities.GetShaderPropertyIDs(); // Add a new material Shader shader = Shader.Find("TextMeshPro/Sprite"); Material tempMaterial = new Material(shader); tempMaterial.SetTexture(ShaderUtilities.ID_MainTex, spriteSheet); tempMaterial.hideFlags = HideFlags.HideInHierarchy; #if UNITY_EDITOR UnityEditor.AssetDatabase.AddObjectToAsset(tempMaterial, this); UnityEditor.AssetDatabase.ImportAsset(UnityEditor.AssetDatabase.GetAssetPath(this)); #endif //isEditingAsset = false; return tempMaterial; } /// <summary> /// Function to update the sprite name and unicode lookup tables. /// This function should be called when a sprite's name or unicode value changes or when a new sprite is added. /// </summary> public void UpdateLookupTables() { //Debug.Log("Updating [" + this.name + "] Lookup tables."); // Check version number of sprite asset to see if it needs to be upgraded. if (this.material != null && string.IsNullOrEmpty(m_Version)) UpgradeSpriteAsset(); // Initialize / Clear glyph index lookup dictionary. if (m_GlyphIndexLookup == null) m_GlyphIndexLookup = new Dictionary<uint, int>(); else m_GlyphIndexLookup.Clear(); for (int i = 0; i < m_SpriteGlyphTable.Count; i++) { uint glyphIndex = m_SpriteGlyphTable[i].index; if (m_GlyphIndexLookup.ContainsKey(glyphIndex) == false) m_GlyphIndexLookup.Add(glyphIndex, i); } if (m_NameLookup == null) m_NameLookup = new Dictionary<int, int>(); else m_NameLookup.Clear(); if (m_UnicodeLookup == null) m_UnicodeLookup = new Dictionary<uint, int>(); else m_UnicodeLookup.Clear(); for (int i = 0; i < m_SpriteCharacterTable.Count; i++) { int nameHashCode = m_SpriteCharacterTable[i].hashCode; if (m_NameLookup.ContainsKey(nameHashCode) == false) m_NameLookup.Add(nameHashCode, i); uint unicode = m_SpriteCharacterTable[i].unicode; if (m_UnicodeLookup.ContainsKey(unicode) == false) m_UnicodeLookup.Add(unicode, i); // Update glyph reference which is not serialized uint glyphIndex = m_SpriteCharacterTable[i].glyphIndex; int index; if (m_GlyphIndexLookup.TryGetValue(glyphIndex, out index)) m_SpriteCharacterTable[i].glyph = m_SpriteGlyphTable[index]; } m_IsSpriteAssetLookupTablesDirty = false; } /// <summary> /// Function which returns the sprite index using the hashcode of the name /// </summary> /// <param name="hashCode"></param> /// <returns></returns> public int GetSpriteIndexFromHashcode(int hashCode) { if (m_NameLookup == null) UpdateLookupTables(); int index; if (m_NameLookup.TryGetValue(hashCode, out index)) return index; return -1; } /// <summary> /// Returns the index of the sprite for the given unicode value. /// </summary> /// <param name="unicode"></param> /// <returns></returns> public int GetSpriteIndexFromUnicode (uint unicode) { if (m_UnicodeLookup == null) UpdateLookupTables(); int index; if (m_UnicodeLookup.TryGetValue(unicode, out index)) return index; return -1; } /// <summary> /// Returns the index of the sprite for the given name. /// </summary> /// <param name="name"></param> /// <returns></returns> public int GetSpriteIndexFromName (string name) { if (m_NameLookup == null) UpdateLookupTables(); int hashCode = TMP_TextUtilities.GetSimpleHashCode(name); return GetSpriteIndexFromHashcode(hashCode); } /// <summary> /// Used to keep track of which Sprite Assets have been searched. /// </summary> private static List<int> k_searchedSpriteAssets; /// <summary> /// Search through the given sprite asset and its fallbacks for the specified sprite matching the given unicode character. /// </summary> /// <param name="spriteAsset">The font asset to search for the given character.</param> /// <param name="unicode">The character to find.</param> /// <param name="glyph">out parameter containing the glyph for the specified character (if found).</param> /// <returns></returns> public static TMP_SpriteAsset SearchForSpriteByUnicode(TMP_SpriteAsset spriteAsset, uint unicode, bool includeFallbacks, out int spriteIndex) { // Check to make sure sprite asset is not null if (spriteAsset == null) { spriteIndex = -1; return null; } // Get sprite index for the given unicode spriteIndex = spriteAsset.GetSpriteIndexFromUnicode(unicode); if (spriteIndex != -1) return spriteAsset; // Initialize list to track instance of Sprite Assets that have already been searched. if (k_searchedSpriteAssets == null) k_searchedSpriteAssets = new List<int>(); k_searchedSpriteAssets.Clear(); // Get instance ID of sprite asset and add to list. int id = spriteAsset.GetInstanceID(); k_searchedSpriteAssets.Add(id); // Search potential fallback sprite assets if includeFallbacks is true. if (includeFallbacks && spriteAsset.fallbackSpriteAssets != null && spriteAsset.fallbackSpriteAssets.Count > 0) return SearchForSpriteByUnicodeInternal(spriteAsset.fallbackSpriteAssets, unicode, includeFallbacks, out spriteIndex); // Search default sprite asset potentially assigned in the TMP Settings. if (includeFallbacks && TMP_Settings.defaultSpriteAsset != null) return SearchForSpriteByUnicodeInternal(TMP_Settings.defaultSpriteAsset, unicode, includeFallbacks, out spriteIndex); spriteIndex = -1; return null; } /// <summary> /// Search through the given list of sprite assets and fallbacks for a sprite whose unicode value matches the target unicode. /// </summary> /// <param name="spriteAssets"></param> /// <param name="unicode"></param> /// <param name="includeFallbacks"></param> /// <param name="spriteIndex"></param> /// <returns></returns> private static TMP_SpriteAsset SearchForSpriteByUnicodeInternal(List<TMP_SpriteAsset> spriteAssets, uint unicode, bool includeFallbacks, out int spriteIndex) { for (int i = 0; i < spriteAssets.Count; i++) { TMP_SpriteAsset temp = spriteAssets[i]; if (temp == null) continue; int id = temp.GetInstanceID(); // Skip over the fallback sprite asset if it has already been searched. if (k_searchedSpriteAssets.Contains(id)) continue; // Add to list of font assets already searched. k_searchedSpriteAssets.Add(id); temp = SearchForSpriteByUnicodeInternal(temp, unicode, includeFallbacks, out spriteIndex); if (temp != null) return temp; } spriteIndex = -1; return null; } /// <summary> /// Search the given sprite asset and fallbacks for a sprite whose unicode value matches the target unicode. /// </summary> /// <param name="spriteAsset"></param> /// <param name="unicode"></param> /// <param name="includeFallbacks"></param> /// <param name="spriteIndex"></param> /// <returns></returns> private static TMP_SpriteAsset SearchForSpriteByUnicodeInternal(TMP_SpriteAsset spriteAsset, uint unicode, bool includeFallbacks, out int spriteIndex) { // Get sprite index for the given unicode spriteIndex = spriteAsset.GetSpriteIndexFromUnicode(unicode); if (spriteIndex != -1) return spriteAsset; if (includeFallbacks && spriteAsset.fallbackSpriteAssets != null && spriteAsset.fallbackSpriteAssets.Count > 0) return SearchForSpriteByUnicodeInternal(spriteAsset.fallbackSpriteAssets, unicode, includeFallbacks, out spriteIndex); spriteIndex = -1; return null; } /// <summary> /// Search the given sprite asset and fallbacks for a sprite whose hash code value of its name matches the target hash code. /// </summary> /// <param name="spriteAsset">The Sprite Asset to search for the given sprite whose name matches the hashcode value</param> /// <param name="hashCode">The hash code value matching the name of the sprite</param> /// <param name="includeFallbacks">Include fallback sprite assets in the search</param> /// <param name="spriteIndex">The index of the sprite matching the provided hash code</param> /// <returns>The Sprite Asset that contains the sprite</returns> public static TMP_SpriteAsset SearchForSpriteByHashCode(TMP_SpriteAsset spriteAsset, int hashCode, bool includeFallbacks, out int spriteIndex) { // Make sure sprite asset is not null if (spriteAsset == null) { spriteIndex = -1; return null; } spriteIndex = spriteAsset.GetSpriteIndexFromHashcode(hashCode); if (spriteIndex != -1) return spriteAsset; // Initialize list to track instance of Sprite Assets that have already been searched. if (k_searchedSpriteAssets == null) k_searchedSpriteAssets = new List<int>(); k_searchedSpriteAssets.Clear(); int id = spriteAsset.GetInstanceID(); // Add to list of font assets already searched. k_searchedSpriteAssets.Add(id); if (includeFallbacks && spriteAsset.fallbackSpriteAssets != null && spriteAsset.fallbackSpriteAssets.Count > 0) return SearchForSpriteByHashCodeInternal(spriteAsset.fallbackSpriteAssets, hashCode, includeFallbacks, out spriteIndex); // Search default sprite asset potentially assigned in the TMP Settings. if (includeFallbacks && TMP_Settings.defaultSpriteAsset != null) return SearchForSpriteByHashCodeInternal(TMP_Settings.defaultSpriteAsset, hashCode, includeFallbacks, out spriteIndex); spriteIndex = -1; return null; } /// <summary> /// Search through the given list of sprite assets and fallbacks for a sprite whose hash code value of its name matches the target hash code. /// </summary> /// <param name="spriteAssets"></param> /// <param name="hashCode"></param> /// <param name="searchFallbacks"></param> /// <param name="spriteIndex"></param> /// <returns></returns> private static TMP_SpriteAsset SearchForSpriteByHashCodeInternal(List<TMP_SpriteAsset> spriteAssets, int hashCode, bool searchFallbacks, out int spriteIndex) { // Search through the list of sprite assets for (int i = 0; i < spriteAssets.Count; i++) { TMP_SpriteAsset temp = spriteAssets[i]; if (temp == null) continue; int id = temp.GetInstanceID(); // Skip over the fallback sprite asset if it has already been searched. if (k_searchedSpriteAssets.Contains(id)) continue; // Add to list of font assets already searched. k_searchedSpriteAssets.Add(id); temp = SearchForSpriteByHashCodeInternal(temp, hashCode, searchFallbacks, out spriteIndex); if (temp != null) return temp; } spriteIndex = -1; return null; } /// <summary> /// Search through the given sprite asset and fallbacks for a sprite whose hash code value of its name matches the target hash code. /// </summary> /// <param name="spriteAsset"></param> /// <param name="hashCode"></param> /// <param name="searchFallbacks"></param> /// <param name="spriteIndex"></param> /// <returns></returns> private static TMP_SpriteAsset SearchForSpriteByHashCodeInternal(TMP_SpriteAsset spriteAsset, int hashCode, bool searchFallbacks, out int spriteIndex) { // Get the sprite for the given hash code. spriteIndex = spriteAsset.GetSpriteIndexFromHashcode(hashCode); if (spriteIndex != -1) return spriteAsset; if (searchFallbacks && spriteAsset.fallbackSpriteAssets != null && spriteAsset.fallbackSpriteAssets.Count > 0) return SearchForSpriteByHashCodeInternal(spriteAsset.fallbackSpriteAssets, hashCode, searchFallbacks, out spriteIndex); spriteIndex = -1; return null; } /// <summary> /// Sort the sprite glyph table by glyph index. /// </summary> public void SortGlyphTable() { if (m_SpriteGlyphTable == null || m_SpriteGlyphTable.Count == 0) return; m_SpriteGlyphTable = m_SpriteGlyphTable.OrderBy(item => item.index).ToList(); } /// <summary> /// Sort the sprite character table by Unicode values. /// </summary> internal void SortCharacterTable() { if (m_SpriteCharacterTable != null && m_SpriteCharacterTable.Count > 0) m_SpriteCharacterTable = m_SpriteCharacterTable.OrderBy(c => c.unicode).ToList(); } /// <summary> /// Sort both sprite glyph and character tables. /// </summary> internal void SortGlyphAndCharacterTables() { SortGlyphTable(); SortCharacterTable(); } /// <summary> /// Internal method used to upgrade sprite asset. /// </summary> private void UpgradeSpriteAsset() { m_Version = "1.1.0"; Debug.Log("Upgrading sprite asset [" + this.name + "] to version " + m_Version + ".", this); // Convert legacy glyph and character tables to new format m_SpriteCharacterTable.Clear(); m_SpriteGlyphTable.Clear(); for (int i = 0; i < spriteInfoList.Count; i++) { TMP_Sprite oldSprite = spriteInfoList[i]; TMP_SpriteGlyph spriteGlyph = new TMP_SpriteGlyph(); spriteGlyph.index = (uint)i; spriteGlyph.sprite = oldSprite.sprite; spriteGlyph.metrics = new GlyphMetrics(oldSprite.width, oldSprite.height, oldSprite.xOffset, oldSprite.yOffset, oldSprite.xAdvance); spriteGlyph.glyphRect = new GlyphRect((int)oldSprite.x, (int)oldSprite.y, (int)oldSprite.width, (int)oldSprite.height); spriteGlyph.scale = 1.0f; spriteGlyph.atlasIndex = 0; m_SpriteGlyphTable.Add(spriteGlyph); TMP_SpriteCharacter spriteCharacter = new TMP_SpriteCharacter((uint)oldSprite.unicode, spriteGlyph); spriteCharacter.name = oldSprite.name; spriteCharacter.scale = oldSprite.scale; m_SpriteCharacterTable.Add(spriteCharacter); } // Clear legacy glyph info list. //spriteInfoList.Clear(); UpdateLookupTables(); #if UNITY_EDITOR UnityEditor.EditorUtility.SetDirty(this); UnityEditor.AssetDatabase.SaveAssets(); #endif } } }
using UnityEngine; using System.Collections; public class FpsHudAmmo : MonoBehaviour { static FpsHudAmmo instance = null; public static FpsHudAmmo Instance { get { if (instance == null) { instance = FindObjectOfType(typeof(FpsHudAmmo)) as FpsHudAmmo; } return instance; } } public int ClipAmmo { get { return clipAmmo; } set { value = Mathf.Clamp(value, 0, clipAmmoMax); if (clipAmmo != value) { clipAmmo = value; UpdateClip(); } } } public int ClipAmmoMax { get { return clipAmmoMax; } set { value = Mathf.Clamp(value, 0, 999); if (clipAmmoMax != value) { clipAmmoMax = value; UpdateClip(); } } } public int TotalAmmo { get { return totalAmmo; } set { value = Mathf.Clamp(value, 0, 999); if (totalAmmo != value) { totalAmmo = value; UpdateTotal(); } } } [SerializeField] TextMesh clipBars; [SerializeField] TextMesh clipCounter; [SerializeField] TextMesh totalCounter; [SerializeField] int totalAmmo; [SerializeField] int clipAmmo; [SerializeField] int clipAmmoMax; [SerializeField] string clipBarChar = "I"; [SerializeField] int clipBarCount = 30; [SerializeField] float clipBarWidth = 1f; void Start() { clipBars = transform.Find("ClipBars").GetComponent<TextMesh>(); clipCounter = transform.Find("ClipCounter").GetComponent<TextMesh>(); totalCounter = transform.Find("TotalCounter").GetComponent<TextMesh>(); // Set colors clipBars.renderer.sharedMaterial.SetColor("_Color", FpsHud.Instance.IconColor); clipCounter.renderer.sharedMaterial.SetColor("_Color", FpsHud.Instance.TextColor); totalCounter.renderer.sharedMaterial.SetColor("_Color", FpsHud.Instance.TextColor); // Set values over themselves for init ClipAmmo = clipAmmo; ClipAmmoMax = clipAmmoMax; TotalAmmo = totalAmmo; // Run update to set initial values UpdateClip(); UpdateTotal(); } void UpdateTotal() { totalCounter.text = totalAmmo.ToString(); } void UpdateClip() { int bars = clipAmmo; if (clipAmmoMax > clipBarCount) { bars = Mathf.RoundToInt(clipBarCount * Mathf.Clamp01((float)clipAmmo / (float)clipAmmoMax)); } float offset = clipBars.transform.localPosition.x; float width = bars * clipBarWidth * clipBars.transform.localScale.x; clipCounter.text = clipAmmo.ToString(); clipCounter.transform.localPosition = new Vector3(-width + offset, clipCounter.transform.localPosition.y, 0); clipBars.text = new string(clipBarChar[0], bars); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Draeger.Dynamics365.Testautomation.Common.Locators { public static class CaseLocators { public static string CustomerRaisedComplaint = "dw_customerraisedcomplaint"; public static string PatientInvolvement = "dw_patientinvolvement"; public static string ProductMalfunction = "dw_productmalfunction"; public static string DeviceTested = "dw_devicetested"; public static string DescriptionOfEvent = "dw_descriptionofevent"; public static string DateTimeOfEvent = "dw_datetimeofevent"; public static string InitialReporterRelationship = "dw_initialreporterrelationship"; public static string InjuryReported = "dw_injuryreported"; public static string GeneratedAlarms = "dw_generatedalarms"; public static string MaterialAvailability = "dw_materialavailability"; public static string OccurenceOfEvent = "dw_occurenceofevent"; public static string PatientPersionInjured = "dw_patientpersoninjured"; public static string UserfacilityCareport = "dw_userfacilitycareport"; public static string ResultFix = "dw_resultfix"; } }
using System; using FlexSoft.Infrastructure.Entites; using FlexSoft.Infrastructure.Entites.IdentityModels; using Microsoft.AspNet.Identity.EntityFramework; namespace FlexSoft.Infrastructure { public class UserStore : UserStore<User, UserRole, Guid, UserLogin, UserRoleMembership, UserClaim> { public UserStore(FlexSoftDbContext dbContext) : base(dbContext) { } } }
namespace Arcus.EventGrid.IoTHub.Contracts.Events.v1.Data { public class TwinProperties { public PropertyConfiguration Desired { get; set; } public PropertyConfiguration Reported { get; set; } } }
//using ACTFoundation.Core.ViewModels.Shared; //using ACTFoundation.Models.Generated; //using System; //using System.Collections.Generic; //using System.Linq; //using System.Text; //using System.Threading.Tasks; //using System.Web; //using Umbraco.Core.Models.PublishedContent; //namespace ACTFoundation.Core.ViewModels.Blocks //{ // public class CampaignCardViewModel // { // private const int ShortTextLength = 208; // public CampaignCardViewModel(Campaign campaign) // { // } // public string PageTitle { get; set; } // public string NavigationTitle { get; set; } // public string Title { get; set; } // public string Author { get; set; } // public ImageViewModel MainImage { get; } // public IHtmlString Text { get; set; } // public string Url { get; set; } // } //}
using System; namespace CCD.Enum { [Flags] public enum DisplayConfigScanLineOrdering : uint { Unspecified = 0, Progressive = 1, Interlaced = 2, InterlacedUpperfieldfirst = Interlaced, InterlacedLowerfieldfirst = 3, } }
//-------------------------------------------------- // Motion Framework // Copyright©2019-2020 何冠峰 // Licensed under the MIT license //-------------------------------------------------- using System; using System.Collections; using System.Collections.Generic; using MotionFramework.Utility; using UnityEngine; namespace MotionFramework.Console { public static class ConsoleGUI { private static bool _initGlobalStyle = false; public static GUIStyle SliderStyle { private set; get; } public static GUIStyle SliderThumbStyle { private set; get; } public static GUIStyle ToolbarStyle { private set; get; } public static GUIStyle ButtonStyle { private set; get; } public static GUIStyle ToogleStyle1 { private set; get; } public static GUIStyle ToogleStyle2 { private set; get; } public static GUIStyle TextFieldStyle { private set; get; } public static GUIStyle LableStyle { private set; get; } public static GUIStyle RichLabelStyle { private set; get; } public static int RichLabelFontSize { private set; get; } /// <summary> /// 创建一些高度和字体大小固定的控件样式 /// 控制台的标准分辨率为 : 1920X1080 /// </summary> internal static void InitGlobalStyle() { if (_initGlobalStyle == false) { _initGlobalStyle = true; float scale; if (Screen.height > Screen.width) { // 竖屏Portrait scale = Screen.width / 1080f; } else { // 横屏Landscape scale = Screen.width / 1920f; } SliderStyle = new GUIStyle(GUI.skin.horizontalSlider); SliderStyle.fixedHeight = (int)(20 * scale); SliderThumbStyle = new GUIStyle(GUI.skin.horizontalSliderThumb); SliderThumbStyle.fixedHeight = (int)(25 * scale); SliderThumbStyle.fixedWidth = (int)(25 * scale); ToolbarStyle = new GUIStyle(GUI.skin.button); ToolbarStyle.fontSize = (int)(28 * scale); ToolbarStyle.fixedHeight = (int)(40 * scale); ButtonStyle = new GUIStyle(GUI.skin.button); ButtonStyle.fontSize = (int)(28 * scale); ButtonStyle.fixedHeight = (int)(40 * scale); ToogleStyle1 = new GUIStyle(GUI.skin.button); ToogleStyle1.fontSize = (int)(26 * scale); ToogleStyle1.fixedHeight = (int)(35 * scale); ToogleStyle2 = new GUIStyle(GUI.skin.box); ToogleStyle2.fontSize = (int)(26 * scale); ToogleStyle2.fixedHeight = (int)(35 * scale); TextFieldStyle = new GUIStyle(GUI.skin.textField); TextFieldStyle.fontSize = (int)(22 * scale); TextFieldStyle.fixedHeight = (int)(30 * scale); LableStyle = new GUIStyle(GUI.skin.label); LableStyle.fontSize = (int)(24 * scale); RichLabelStyle = GUIStyle.none; RichLabelStyle.richText = true; RichLabelFontSize = (int)(24 * scale); } } public static Vector2 BeginScrollView(Vector2 pos, int fixedViewHeight) { float scrollWidth = Screen.width; float scrollHeight = Screen.height - ButtonStyle.fixedHeight - fixedViewHeight - 10; return GUILayout.BeginScrollView(pos, GUILayout.Width(scrollWidth), GUILayout.Height(scrollHeight)); } public static void EndScrollView() { GUILayout.EndScrollView(); } public static bool Toggle(string name, bool checkFlag) { GUIStyle style = checkFlag ? ToogleStyle1 : ToogleStyle2; if (GUILayout.Button(name, style)) { checkFlag = !checkFlag; } return checkFlag; } public static void Lable(string text) { GUILayout.Label($"<size={RichLabelFontSize}><color=white>{text}</color></size>", RichLabelStyle); } public static void RedLable(string text) { GUILayout.Label($"<size={RichLabelFontSize}><color=red>{text}</color></size>", RichLabelStyle); } public static void YellowLable(string text) { GUILayout.Label($"<size={RichLabelFontSize}><color=yellow>{text}</color></size>", RichLabelStyle); } } }
using UnityEngine; using System.Collections; public class DoorControllerAdvanced : MonoBehaviour { [SerializeField] private float openAngle = 90.0f; private float doorClickOpenAngle = 2.0f; private float slightDoorOpenAngle = 10.0f; private float maxDistance = 2.0f; [SerializeField] private AudioClip openDoorClip; [SerializeField] private AudioClip closeDoorClip; [SerializeField] private AudioClip slamDoorClip; [SerializeField] private AudioClip doorSqueekClip; [SerializeField] private AudioClip doorClickOpenClip; [SerializeField] private AudioClip doorClickCloseClip; [SerializeField] private AudioClip doorLockClip; private bool open; private bool enter; private bool isMoving; private bool isSlightOpen; private bool slamDoor; private bool slightlyOpenDoor; [SerializeField] private bool lockDoor = false; private Vector3 closedRotation; private BoxCollider doorCollider; private Rigidbody doorRB; // private Vector3 doorSize; // private Bounds doorBounds; private GameObject hinge; private AudioSource hingeAudioSource; private GameObject doorLock; private AudioSource doorLockAudioSource; // Use this for initialization void Start() { closedRotation = transform.rotation.eulerAngles; open = false; enter = false; isMoving = false; isSlightOpen = false; slamDoor = false; slightlyOpenDoor = false; doorCollider = gameObject.GetComponent<BoxCollider>(); if (gameObject.GetComponent<Rigidbody>() != null) doorRB = gameObject.GetComponent<Rigidbody>(); // Add BoxCollider component as trigger CreateBoxColliderTrigger(gameObject); // Check y-scale to correct direction of door swing if (gameObject.transform.localScale.y < 0) { openAngle *= -1; doorClickOpenAngle *= -1; slightDoorOpenAngle *= -1; } } // Update is called once per frame void Update() { if (!enter || isMoving) return; if (Input.GetKeyDown(KeyCode.E)) { Ray ray = Camera.main.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0)); RaycastHit hit; if (doorCollider.Raycast(ray, out hit, maxDistance)) { isMoving = true; StartCoroutine("MoveDoor"); } } } void OnTriggerEnter(Collider other) { if (other.CompareTag("Player")) enter = true; } void OnTriggerExit(Collider other) { if (other.CompareTag("Player")) enter = false; } public void SetSlamDoor() { if (open) { slamDoor = true; isMoving = true; StartCoroutine("MoveDoor"); } } public void SetSlightOpenDoor() { if (!open) { slightlyOpenDoor = true; isMoving = true; StartCoroutine("MoveDoor"); } } public void SetLockDoor(bool choice) { lockDoor = choice; } private AudioSource CreateAudioSource(GameObject targetGameObject) { AudioSource audio = targetGameObject.AddComponent<AudioSource>(); audio.volume = 1.0f; audio.spatialBlend = 1.0f; audio.minDistance = 0.5f; // 1.0 audio.maxDistance = 30.0f; // 50 return audio; } private void CreateBoxColliderTrigger(GameObject targetGameObject) { BoxCollider collider = targetGameObject.AddComponent<BoxCollider>(); collider.center = gameObject.transform.InverseTransformPoint(doorCollider.bounds.center); collider.size = new Vector3(2.0f, 2.5f, 2.3f); collider.isTrigger = true; } IEnumerator MoveDoor() { // Door rotation parameters float from, to, startTime, duration; // Create hinge GameObject with AudioSource CreateHingeObject(); // if door is closed if (!open) { // if door is slightly open if (isSlightOpen) { hingeAudioSource.clip = openDoorClip; from = closedRotation.z - slightDoorOpenAngle; to = closedRotation.z - openAngle; // Reset bool values isSlightOpen = false; } // if door is not slightly open (completely closed) else { // Create doorLock GameObject with AudioSource CreateDoorLockObject(); // Play audio of door clicking open doorLockAudioSource.PlayOneShot(doorClickOpenClip); // Door animation in time with audioClip yield return new WaitForSeconds(0.3f); // Check if door is locked if (lockDoor) { isMoving = false; DestroyDoorObjects(); yield break; } // Set door rotation parameters for door moving slightly from clicking open from = closedRotation.z; to = closedRotation.z - doorClickOpenAngle; startTime = Time.time; duration = 0.4f; // Rotate door while audioClip is playing while (doorLockAudioSource.isPlaying) { RotateDoor(from, to, startTime, duration); /* float timeRatio = (Time.time - startTime) / duration; float rotation = Mathf.LerpAngle(from, to, timeRatio); if (doorRB != null) doorRB.rotation = Quaternion.Euler(new Vector3(closedRotation.x, closedRotation.y, rotation)); else transform.rotation = Quaternion.Euler(new Vector3(closedRotation.x, closedRotation.y, rotation)); */ yield return null; } // Destroy doorLock gameObject containing AudioSource component Destroy(doorLock); // Set door rotation parameters for door opening from = closedRotation.z - doorClickOpenAngle; // if door is to be opened slightly if (slightlyOpenDoor) { hingeAudioSource.clip = doorSqueekClip; to = closedRotation.z - slightDoorOpenAngle; // Reset bool values isSlightOpen = true; slightlyOpenDoor = false; } // else door is to be opened fully else { hingeAudioSource.clip = openDoorClip; to = closedRotation.z - openAngle; } } // Play audio of door opening hingeAudioSource.Play(); startTime = Time.time; duration = hingeAudioSource.clip.length; // Rotate door while audioClip is playing while (hingeAudioSource.isPlaying) { RotateDoor(from, to, startTime, duration); /* float timeRatio = (Time.time - startTime) / duration; float rotation = Mathf.SmoothStep(from, to, timeRatio); if (doorRB != null) doorRB.rotation = Quaternion.Euler(new Vector3(closedRotation.x, closedRotation.y, rotation)); else transform.rotation = Quaternion.Euler(new Vector3(closedRotation.x, closedRotation.y, rotation)); */ yield return null; } // Set bool values if (isSlightOpen) open = false; else open = true; } // if door is open else if (open) { // Set door rotation parameters for closing door from = closedRotation.z - openAngle; to = closedRotation.z; // if door is to be slammed if (slamDoor) { hingeAudioSource.PlayOneShot(slamDoorClip); duration = 0.6f; // Reset bool values slamDoor = false; } // else door is closed normally else { hingeAudioSource.PlayOneShot(closeDoorClip); duration = closeDoorClip.length - 0.2f; } startTime = Time.time; // Rotate door while audioClip is playing while (hingeAudioSource.isPlaying) { RotateDoor(from, to, startTime, duration); /* float timeRatio = (Time.time - startTime) / duration; float rotation = Mathf.SmoothStep(from, to, timeRatio); if (doorRB != null) doorRB.rotation = Quaternion.Euler(new Vector3(closedRotation.x, closedRotation.y, rotation)); else transform.rotation = Quaternion.Euler(new Vector3(closedRotation.x, closedRotation.y, rotation)); */ yield return null; } // Set bool values open = false; } // Destroy hinge GameObject containing audioSource component Destroy(hinge); DestroyDoorObjects(); // Set bool values isMoving = false; } private void RotateDoor(float from, float to, float startTime, float duration) { float timeRatio = (Time.time - startTime) / duration; float rotation = Mathf.SmoothStep(from, to, timeRatio); if (doorRB != null) doorRB.rotation = Quaternion.Euler(new Vector3(closedRotation.x, closedRotation.y, rotation)); else transform.rotation = Quaternion.Euler(new Vector3(closedRotation.x, closedRotation.y, rotation)); } void CreateHingeObject() { // Create gameObject with AudioSource at position of hinge hinge = new GameObject("Hinge"); hingeAudioSource = CreateAudioSource(hinge); // Parent hinge gameObject to door hinge.transform.parent = gameObject.transform; // Set local position of hinge hinge.transform.localPosition = new Vector3(0.0f, -0.5f * doorCollider.size.y, 0.5f * doorCollider.size.z); } void CreateDoorLockObject() { // Create gameObject with AudioSource at position of door lock doorLock = new GameObject("DoorLock"); doorLockAudioSource = CreateAudioSource(doorLock); // Parent doorLock gameObject to door doorLock.transform.parent = gameObject.transform; // Set local position of doorLock doorLock.transform.localPosition = new Vector3(-doorCollider.size.x, -0.5f * doorCollider.size.y, 0.5f * doorCollider.size.z); } void DestroyDoorObjects() { if (hinge != null) Destroy(hinge); if (doorLock != null) Destroy(doorLock); } private float pushPower = 2.0f; void OnControllerColliderHit(ControllerColliderHit hit) { Rigidbody body = hit.collider.attachedRigidbody; if (body == null || body.isKinematic) return; if (hit.moveDirection.y < -0.3f) return; Vector3 pushDir = new Vector3(hit.moveDirection.x, 0, hit.moveDirection.z); body.velocity = pushDir * pushPower; } /* void OnCollisionEnter(Collision collision) { if (collision.collider.CompareTag("Player")) { Debug.Log("Colliding"); } else Debug.Log("Not Colliding"); } */ }
using System; using Wizard.Cinema.Application.Services.Dto.EnumTypes; namespace Wizard.Cinema.Application.Services.Dto.Request { public class ChangeProfilepReqs { public long WizardId { get; set; } /// <summary> /// 姓名 /// </summary> public string NickName { get; set; } /// <summary> /// 头像Url /// </summary> public string PortraitUrl { get; set; } /// <summary> /// 电话号码 /// </summary> public string Mobile { get; set; } /// <summary> /// 性别 /// </summary> public Gender Gender { get; set; } /// <summary> /// 生日 /// </summary> public DateTime Birthday { get; set; } /// <summary> /// 个性签名 /// </summary> public string Slogan { get; set; } /// <summary> /// 学院 /// </summary> public Houses House { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Jump : MonoBehaviour { Character_Movement movement = null; [Range(1, 20)] public float jumpVelocity; public int jumpLimit = 2; int jumpValue = 0; private void Start() { jumpLimit = jumpValue; GetComponent<Rigidbody2D>(); movement = GetComponent<Character_Movement>(); } void Update() { if(movement != null && movement.coll.onGround == true) { jumpValue = jumpLimit; } if (Input.GetButtonDown("Jump")) { if (jumpValue <= jumpLimit) { GetComponent<Rigidbody2D>().velocity = Vector2.up * jumpVelocity; jumpValue++; } if (movement != null) { movement.WallJump(); jumpValue++; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using UnityEngine; namespace FlappyBird { public class BulletData : EntityData { /// <summary> /// 发射位置 /// </summary> public Vector2 ShootPostion { get; private set; } /// <summary> /// 飞行速度 /// </summary> public float FlySpeed { get; private set; } public BulletData(int entityId, int typeId, Vector2 shootPositoin, float flySpeed) : base(entityId, typeId) { ShootPostion = shootPositoin; FlySpeed = flySpeed; } } }
using Microsoft.Azure.ApplicationInsights.Query; using Microsoft.Azure.ApplicationInsights.Query.Models; using Microsoft.Extensions.Options; using Microsoft.Rest; using SSW.SophieBot.Components.Models; using System; using System.Threading.Tasks; namespace SSW.SophieBot.Components.Services { public class AppInsightsService : ITelemetryService { public const string QueryBaseUrl = "https://api.applicationinsights.io/v1"; private readonly AppInsightsSettings _settings; public AppInsightsService(IOptions<AppInsightsSettings> settings) { _settings = settings.Value; } public async Task<UsageByUserQueryResult> GetUsageByUserAsync( int? spanDays = null, int? maxItemCount = null, Func<string, string> userNameGroupKeyFunc = null) { var validPastDays = Math.Min(90, Math.Max(0, spanDays ?? 7)); var validMaxItemCount = Math.Min(50, Math.Max(0, maxItemCount ?? 10)); var userNameGroupKey = "user_AccountId"; if (userNameGroupKeyFunc != null) { userNameGroupKey = userNameGroupKeyFunc.Invoke(userNameGroupKey); } var query = $@"customEvents | where name == 'LuisResult' and isnotnull(customDimensions.intent) and isnotempty(user_AccountId) | summarize usageCount = dcount(tostring(customDimensions.activityId), 2) by user={userNameGroupKey} | order by usageCount desc | limit {validMaxItemCount}"; var credentials = new ApiKeyClientCredentials(_settings.ApiKey); using var client = new ApplicationInsightsDataClient(credentials) { BaseUri = new Uri(QueryBaseUrl) }; using HttpOperationResponse<QueryResults> response = await client.Query.ExecuteWithHttpMessagesAsync(_settings.AppID, query, $"P{validPastDays}D"); if (!response.Response.IsSuccessStatusCode) { return new UsageByUserQueryResult(); // TODO: improve failure handling } return new UsageByUserQueryResult(response.Body).OrderByUsageCountDesc(); } } }
using System; using System.Web.Mvc; namespace Ext.Direct.Mvc { public class DirectRouterController : Controller { private readonly DirectProvider _provider = DirectProvider.GetCurrent(); [AcceptVerbs("POST")] [ValidateInput(false)] public ActionResult Index() { // Process Ext.Direct requests _provider.Execute(ControllerContext.RequestContext); return new EmptyResult(); } } }
using System; namespace Kunukn.XmlVisual.Core { public static class Reset { public static void Run() { } } }
// Copyright (c) Hugues Valois. All rights reserved. // Licensed under the X11 license. See LICENSE in the project root for license information. namespace Woohoo.Agi.Interpreter { using System.Collections.Generic; /// <summary> /// Menu hierarchical structure. /// </summary> public class Menu { public const int LastMenuColumn = 39; /// <summary> /// Initializes a new instance of the <see cref="Menu"/> class. /// </summary> public Menu() { this.Items = new List<MenuParentItem>(); } /// <summary> /// Gets top-level menu items (parent items). /// </summary> public IList<MenuParentItem> Items { get; } /// <summary> /// Gets or sets a value indicating whether once a menu is submitted, no changes are made to its structure. /// </summary> public bool Submitted { get; set; } /// <summary> /// Enable all the menu items. /// </summary> public void EnableAllItems() { foreach (var parent in this.Items) { if (parent.Enabled) { foreach (var item in parent.Items) { item.Enabled = true; } } } } /// <summary> /// Enable or disable the item(s) that use the specified controller. /// </summary> /// <param name="controller">Controller to search for.</param> /// <param name="enable">Enable/disable menu item(s).</param> public void SetItemEnabled(byte controller, bool enable) { foreach (var parentItem in this.Items) { foreach (var item in parentItem.Items) { if (item.Controller == controller) { item.Enabled = enable; } } } } /// <summary> /// Append a parent menu item. /// </summary> /// <param name="text">Parent menu item text.</param> public void AppendParentItem(string text) { byte column = 1; foreach (var current in this.Items) { column += (byte)(current.Text.Length + 1); } var parentItem = new MenuParentItem(); parentItem.Column = column; parentItem.Row = 0; parentItem.Text = text; parentItem.Enabled = true; this.Items.Add(parentItem); } } }
using System; using System.Collections.Generic; namespace GraphAlgorithms.D3 { public struct D3Node { public readonly string id; public readonly int groupColor; public D3Node(string id, int groupColor = 1) { this.id = id; this.groupColor = groupColor; } } public struct D3Link { public readonly string source; public readonly string target; public readonly double value; public D3Link(string source, string target, double value) { this.source = source; this.target = target; this.value = value; } } public struct D3ForceDirectedGraph<CONTENT> where CONTENT : IEquatable<CONTENT> { public readonly D3Node[] nodes; public readonly D3Link[] links; /// <summary> /// Initializes a new instance of the <see cref="T:D3Manager.D3Graph`1"/> struct. /// </summary> /// <param name="graph">Graph.</param> /// <param name="converter">Transforms the information in the WeightedNode into </param> public D3ForceDirectedGraph(WeightedGraph<CONTENT> graph, Func<CONTENT, string> converter) { var nList = new List<D3Node>(); graph.BFS(node => nList.Add(new D3Node(id: converter(node.Content)))); var lList = new List<D3Link>(); var edges = graph.UndirectedEdges(); foreach (var edge in edges) { lList.Add(new D3Link(converter(edge.Item1.Content), converter(edge.Item2.Content), edge.Item3)); } nodes = nList.ToArray(); links = lList.ToArray(); } } }
using System.Collections.Generic; using System.Linq; namespace Blueprint.Http { public class PagedApiResource<T> : ApiResource, IPagedApiResource { public PagedApiResource(IEnumerable<T> values) { this.Object = $"list.{GetTypeName(typeof(T))}"; // NB: It's important to consume values which could be a LINQ query as otherwise modifications // in middleware could be lost if the values are enumerated multiple times this.Values = values.ToList(); this.Total = this.Values.Count(); this.CurrentPage = 1; this.PageSize = this.Total; } public PagedApiResource(IEnumerable<T> values, long total, int pageSize, int currentPage) { this.Object = $"list.{GetTypeName(typeof(T))}"; // NB: It's important to consume values which could be a LINQ query as otherwise modifications // in middleware could be lost if the values are enumerated multiple times this.Values = values.ToList(); this.Total = total; this.PageSize = pageSize; this.CurrentPage = currentPage; } public IEnumerable<T> Values { get; } public long Total { get; } public long PageSize { get; } public int CurrentPage { get; } public IEnumerable<object> GetEnumerable() { return this.Values as IEnumerable<object>; } } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class DeckTester : MonoBehaviour { [SerializeField] List<AbilityCardData> _abilityDeckConfig = new List<AbilityCardData>(); [SerializeField] AbilityCardView _abilityCardViewFirst = null; [SerializeField] AbilityCardView _abilityCardView = null; [SerializeField] AbilityCardView _abilityCardViewLast = null; Deck<AbilityCard> _abilityDeck = new Deck<AbilityCard>(); Deck<AbilityCard> _abilityDiscard = new Deck<AbilityCard>(); [SerializeField] AbilityCardView _discardView = null; [SerializeField] AbilityCardView _upcomingView = null; Deck<AbilityCard> _playerHand = new Deck<AbilityCard>(); private bool _hasDrawn = false; [SerializeField] Button _button1 = null; [SerializeField] Button _button2 = null; [SerializeField] Button _button3 = null; [SerializeField] Button _drawButton = null; [SerializeField] Button _shuffleButton = null; [SerializeField] GameObject _playerCardArea = null; [SerializeField] Material m_PlayerCard = null; [SerializeField] Material m_Card = null; private void Start() { SetupAbilityDeck(); HidePlayerHand(); _upcomingView.Display(_abilityDeck.TopItem); _button1.onClick.AddListener(TaskOnClick); _button2.onClick.AddListener(TaskOnClick); _button3.onClick.AddListener(TaskOnClick); _drawButton.onClick.AddListener(() => DrawCard()); _shuffleButton.onClick.AddListener(() => ShuffleDeck()); } private void HidePlayerHand() { _abilityCardViewFirst.gameObject.SetActive(false); _abilityCardView.gameObject.SetActive(false); _abilityCardViewLast.gameObject.SetActive(false); } private void ShowPlayerHand() { _abilityCardViewFirst.gameObject.SetActive(true); _abilityCardView.gameObject.SetActive(true); _abilityCardViewLast.gameObject.SetActive(true); } private void SetupAbilityDeck() { foreach(AbilityCardData abilityData in _abilityDeckConfig) { AbilityCard newAbilityCard = new AbilityCard(abilityData); _abilityDeck.Add(newAbilityCard); } _abilityDeck.Shuffle(); } private void Update() { if(_abilityDeck.Count > 0) { _upcomingView.gameObject.SetActive(true); _shuffleButton.gameObject.SetActive(false); } if(_abilityDeck.Count == 0) { _shuffleButton.gameObject.SetActive(true); } if (Input.GetKeyDown(KeyCode.W)) { PrintPlayerHand(); } } void TaskOnClick() { PlayTopCard(); Debug.Log("You have clicked the button"); } void DrawCard() { Draw(); } void ShuffleDeck() { if (_abilityDeck.IsEmpty) { for (int j = _abilityDiscard.Count -1; j > -1; --j) { AbilityCard cardToShuffle = _abilityDiscard.GetCard(j); _abilityDiscard.Remove(j); _abilityDeck.Add(cardToShuffle); } _abilityDeck.Shuffle(); Debug.Log("Deck Shuffled. Deck Count: " + _abilityDeck.Count); Debug.Log("Discard Count: " + _abilityDiscard.Count); } } private void Draw() { if (_abilityDeck.IsEmpty) { Debug.Log("Cannot draw! Deck is Empty!"); } if (!_abilityDeck.IsEmpty) { if (_hasDrawn == false) { Renderer CardPlayed = _playerCardArea.GetComponent<Renderer>(); CardPlayed.material = m_Card; AbilityCard newCard = _abilityDeck.Draw(DeckPosition.Top); Debug.Log("Drew card: " + newCard.Name); AbilityCard firstCard = _abilityDeck.Draw(DeckPosition.Top); Debug.Log("Drew card: " + firstCard.Name); AbilityCard lastCard = _abilityDeck.Draw(DeckPosition.Top); Debug.Log("Drew card: " + lastCard.Name); _playerHand.Add(newCard, DeckPosition.Top); _playerHand.Add(firstCard, DeckPosition.Top); _playerHand.Add(lastCard, DeckPosition.Top); ShowPlayerHand(); _abilityCardView.Display(newCard); _abilityCardViewFirst.Display(firstCard); _abilityCardViewLast.Display(lastCard); if(_abilityDeck.Count > 0) { AbilityCard upcomingCard = _abilityDeck.TopItem; _upcomingView.Display(upcomingCard); } if(_abilityDeck.Count == 0) { _upcomingView.gameObject.SetActive(false); } _hasDrawn = true; Debug.Log("Deck Count: " + _abilityDeck.Count); } if (_hasDrawn == true) { Debug.Log("Card already drawn for the turn."); } } } private void PrintPlayerHand() { for(int i = 0; i<_playerHand.Count; i++) { Debug.Log("Player Hand Card: " + _playerHand.GetCard(i).Name); } } void PlayTopCard() { AbilityCard targetCard = _playerHand.TopItem; AbilityCard secondCard = _playerHand.SecondItem; AbilityCard thirdCard = _playerHand.ThirdItem; targetCard.Play(); Renderer CardPlayed = _playerCardArea.GetComponent<Renderer>(); CardPlayed.material = m_PlayerCard; //consider expanding remove to accept a deck position _playerHand.Remove(_playerHand.LastIndex); _playerHand.Remove(_playerHand.LastIndex); _playerHand.Remove(_playerHand.LastIndex); HidePlayerHand(); _abilityDiscard.Add(targetCard); Debug.Log("Card added to discard: " + targetCard.Name); _discardView.Display(targetCard); _abilityDiscard.Add(secondCard); Debug.Log("Card added to discard: " + secondCard.Name); _abilityDiscard.Add(thirdCard); Debug.Log("Card added to discard: " + thirdCard.Name); Debug.Log("Discard Count: " + _abilityDiscard.Count); _hasDrawn = false; } }
using Bunit.Extensions; namespace Bunit; /// <summary> /// <see cref="ComponentParameter"/> factory methods. /// </summary> public static class ComponentParameterFactory { /// <summary> /// Creates a <see cref="ComponentParameter"/> with an <see cref="Microsoft.AspNetCore.Components.EventCallback"/> that will call the provided <paramref name="callback"/>. /// </summary> /// <param name="name">Parameter name.</param> /// <param name="callback">The event callback.</param> /// <returns>The <see cref="ComponentParameter"/>.</returns> public static ComponentParameter EventCallback(string name, Action callback) { return ComponentParameter.CreateParameter(name, new EventCallback(receiver: null, callback)); } /// <summary> /// Creates a <see cref="ComponentParameter"/> with an <see cref="Microsoft.AspNetCore.Components.EventCallback"/> that will call the provided <paramref name="callback"/>. /// </summary> /// <param name="name">Parameter name.</param> /// <param name="callback">The event callback.</param> /// <returns>The <see cref="ComponentParameter"/>.</returns> public static ComponentParameter EventCallback(string name, Action<object> callback) { return ComponentParameter.CreateParameter(name, new EventCallback(receiver: null, callback)); } /// <summary> /// Creates a <see cref="ComponentParameter"/> with an <see cref="Microsoft.AspNetCore.Components.EventCallback"/> that will call the provided <paramref name="callback"/>. /// </summary> /// <param name="name">Parameter name.</param> /// <param name="callback">The event callback.</param> /// <returns>The <see cref="ComponentParameter"/>.</returns> public static ComponentParameter EventCallback(string name, Func<Task> callback) { return ComponentParameter.CreateParameter(name, new EventCallback(receiver: null, callback)); } /// <summary> /// Creates a <see cref="ComponentParameter"/> with an <see cref="Microsoft.AspNetCore.Components.EventCallback"/> that will call the provided <paramref name="callback"/>. /// </summary> /// <param name="name">Parameter name.</param> /// <param name="callback">The event callback.</param> /// <returns>The <see cref="ComponentParameter"/>.</returns> public static ComponentParameter EventCallback(string name, Func<object, Task> callback) { return ComponentParameter.CreateParameter(name, new EventCallback(receiver: null, callback)); } /// <summary> /// Creates a <see cref="ComponentParameter"/> with an <see cref="Microsoft.AspNetCore.Components.EventCallback"/> that will call the provided <paramref name="callback"/>. /// </summary> /// <param name="name">Parameter name.</param> /// <param name="callback">The event callback.</param> /// <typeparam name="TValue">The value returned in the <see cref="Microsoft.AspNetCore.Components.EventCallback{TValue}"/>.</typeparam> /// <returns>The <see cref="ComponentParameter"/>.</returns> public static ComponentParameter EventCallback<TValue>(string name, Action callback) { return ComponentParameter.CreateParameter(name, new EventCallback<TValue>(receiver: null, callback)); } /// <summary> /// Creates a <see cref="ComponentParameter"/> with an <see cref="Microsoft.AspNetCore.Components.EventCallback"/> that will call the provided <paramref name="callback"/>. /// </summary> /// <param name="name">Parameter name.</param> /// <param name="callback">The event callback.</param> /// <typeparam name="TValue">The value returned in the <see cref="Microsoft.AspNetCore.Components.EventCallback{TValue}"/>.</typeparam> /// <returns>The <see cref="ComponentParameter"/>.</returns> public static ComponentParameter EventCallback<TValue>(string name, Action<TValue> callback) { return ComponentParameter.CreateParameter(name, new EventCallback<TValue>(receiver: null, callback)); } /// <summary> /// Creates a <see cref="ComponentParameter"/> with an <see cref="Microsoft.AspNetCore.Components.EventCallback"/> that will call the provided <paramref name="callback"/>. /// </summary> /// <param name="name">Parameter name.</param> /// <param name="callback">The event callback.</param> /// <typeparam name="TValue">The value returned in the <see cref="Microsoft.AspNetCore.Components.EventCallback{TValue}"/>.</typeparam> /// <returns>The <see cref="ComponentParameter"/>.</returns> public static ComponentParameter EventCallback<TValue>(string name, Func<Task> callback) { return ComponentParameter.CreateParameter(name, new EventCallback<TValue>(receiver: null, callback)); } /// <summary> /// Creates a <see cref="ComponentParameter"/> with an <see cref="Microsoft.AspNetCore.Components.EventCallback"/> that will call the provided <paramref name="callback"/>. /// </summary> /// <param name="name">Parameter name.</param> /// <param name="callback">The event callback.</param> /// <typeparam name="TValue">The value returned in the <see cref="Microsoft.AspNetCore.Components.EventCallback{TValue}"/>.</typeparam> /// <returns>The <see cref="ComponentParameter"/>.</returns> public static ComponentParameter EventCallback<TValue>(string name, Func<TValue, Task> callback) { return ComponentParameter.CreateParameter(name, new EventCallback<TValue>(receiver: null, callback)); } /// <summary> /// Creates a component parameter which can be passed to a test contexts render methods. /// </summary> /// <param name="name">Parameter name.</param> /// <param name="value">Value or null of the parameter.</param> /// <returns>The <see cref="ComponentParameter"/>.</returns> public static ComponentParameter Parameter(string name, object? value) { return ComponentParameter.CreateParameter(name, value); } /// <summary> /// Creates a cascading value which can be passed to a test contexts render methods. /// </summary> /// <param name="name">Parameter name.</param> /// <param name="value">Value of the parameter.</param> /// <returns>The <see cref="ComponentParameter"/>.</returns> public static ComponentParameter CascadingValue(string name, object value) { return ComponentParameter.CreateCascadingValue(name, value); } /// <summary> /// Creates a cascading value which can be passed to a test contexts render methods. /// </summary> /// <param name="value">Value of the parameter.</param> /// <returns>The <see cref="ComponentParameter"/>.</returns> public static ComponentParameter CascadingValue(object value) { return ComponentParameter.CreateCascadingValue(name: null, value); } /// <summary> /// Creates a ChildContent <see cref="Microsoft.AspNetCore.Components.RenderFragment"/> with the provided /// <paramref name="markup"/> as rendered output. /// </summary> /// <param name="markup">Markup to pass to the child content parameter.</param> /// <returns>The <see cref="ComponentParameter"/>.</returns> public static ComponentParameter ChildContent(string markup) { return RenderFragment(nameof(ChildContent), markup); } /// <summary> /// Creates a ChildContent <see cref="Microsoft.AspNetCore.Components.RenderFragment"/> which will render a <typeparamref name="TComponent"/> component /// with the provided <paramref name="parameters"/> as input. /// </summary> /// <typeparam name="TComponent">The type of the component to render with the <see cref="Microsoft.AspNetCore.Components.RenderFragment"/>.</typeparam> /// <param name="parameters">Parameters to pass to the <typeparamref name="TComponent"/>.</param> /// <returns>The <see cref="ComponentParameter"/>.</returns> public static ComponentParameter ChildContent<TComponent>(params ComponentParameter[] parameters) where TComponent : class, IComponent { return RenderFragment<TComponent>(nameof(ChildContent), parameters); } /// <summary> /// Creates a ChildContent parameter that will pass the provided <paramref name="renderFragment"/> /// to the parameter in the component. /// </summary> /// <param name="renderFragment">The <see cref="Microsoft.AspNetCore.Components.RenderFragment"/> to pass to the ChildContent parameter.</param> /// <returns>The <see cref="ComponentParameter"/>.</returns> public static ComponentParameter ChildContent(RenderFragment renderFragment) { return Parameter(nameof(ChildContent), renderFragment); } /// <summary> /// Creates a <see cref="Microsoft.AspNetCore.Components.RenderFragment"/> with the provided /// <paramref name="markup"/> as rendered output and passes it to the parameter specified in <paramref name="name"/>. /// </summary> /// <param name="name">Parameter name.</param> /// <param name="markup">Markup to pass to the render fragment parameter.</param> /// <returns>The <see cref="ComponentParameter"/>.</returns> public static ComponentParameter RenderFragment(string name, string markup) { return ComponentParameter.CreateParameter(name, markup.ToMarkupRenderFragment()); } /// <summary> /// Creates a <see cref="Microsoft.AspNetCore.Components.RenderFragment"/> which will render a <typeparamref name="TComponent"/> component /// with the provided <paramref name="parameters"/> as input, and passes it to the parameter specified in <paramref name="name"/>. /// </summary> /// <typeparam name="TComponent">The type of the component to render with the <see cref="Microsoft.AspNetCore.Components.RenderFragment"/>.</typeparam> /// <param name="name">Parameter name.</param> /// <param name="parameters">Parameters to pass to the <typeparamref name="TComponent"/>.</param> /// <returns>The <see cref="ComponentParameter"/>.</returns> public static ComponentParameter RenderFragment<TComponent>(string name, params ComponentParameter[] parameters) where TComponent : class, IComponent { var cpc = new ComponentParameterCollection() { parameters }; return ComponentParameter.CreateParameter(name, cpc.ToRenderFragment<TComponent>()); } /// <summary> /// Creates a template component parameter which will pass the <paramref name="template"/> <see cref="Microsoft.AspNetCore.Components.RenderFragment{TValue}" /> /// to the parameter with the name <paramref name="name"/>. /// </summary> /// <typeparam name="TValue">The value used to build the content.</typeparam> /// <param name="name">Parameter name.</param> /// <param name="template"><see cref="Microsoft.AspNetCore.Components.RenderFragment{TValue}" /> to pass to the parameter.</param> /// <returns>The <see cref="ComponentParameter"/>.</returns> public static ComponentParameter Template<TValue>(string name, RenderFragment<TValue> template) { return ComponentParameter.CreateParameter(name, template); } /// <summary> /// Creates a template component parameter which will pass the a <see cref="Microsoft.AspNetCore.Components.RenderFragment{TValue}" /> /// to the parameter with the name <paramref name="name"/>. /// The <paramref name="markupFactory"/> will be used to generate the markup inside the template. /// </summary> /// <typeparam name="TValue">The value used to build the content.</typeparam> /// <param name="name">Parameter name.</param> /// <param name="markupFactory">A markup factory that takes a <typeparamref name="TValue"/> as input and returns markup/HTML.</param> /// <returns>The <see cref="ComponentParameter"/>.</returns> public static ComponentParameter Template<TValue>(string name, Func<TValue, string> markupFactory) { return Template<TValue>(name, value => (RenderTreeBuilder builder) => builder.AddMarkupContent(0, markupFactory(value))); } /// <summary> /// Creates a template component parameter which will pass the a <see cref="Microsoft.AspNetCore.Components.RenderFragment{TValue}" /> /// to the <paramref name="parameterCollectionBuilder"/> at runtime. The parameters returned from it /// will be passed to the <typeparamref name="TComponent"/> and it will be rendered as the template. /// </summary> /// <typeparam name="TComponent">The type of component to render in template.</typeparam> /// <typeparam name="TValue">The value used to build the content.</typeparam> /// <param name="name">Parameter name.</param> /// <param name="parameterCollectionBuilder">The parameter collection builder function that will be passed the template <typeparamref name="TValue"/>.</param> /// <returns>The <see cref="ComponentParameter"/>.</returns> public static ComponentParameter Template<TComponent, TValue>(string name, Func<TValue, ComponentParameter[]> parameterCollectionBuilder) where TComponent : IComponent { return Template<TValue>(name, value => { var cpc = new ComponentParameterCollection() { parameterCollectionBuilder(value) }; return cpc.ToRenderFragment<TComponent>(); }); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data.Entity; namespace NetBots.WebServer.Data.MsSql { using Model; public class NetBotsDbContext : DbContext { public DbSet<PlayerBot> PlayerBots { get; set; } public DbSet<BotRecord> BotRecords { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Factory { public interface IAnimalFactory { IAnimal FactoryMethod();// A method in which to build the product } }
using System; using System.Threading.Tasks; namespace Dalion.HttpMessageSigning.Utils { internal class BackgroundTaskStarter : IBackgroundTaskStarter { private readonly IDelayer _delayer; public BackgroundTaskStarter(IDelayer delayer) { _delayer = delayer ?? throw new ArgumentNullException(nameof(delayer)); } public void Start(Func<Task> task) { if (task == null) throw new ArgumentNullException(nameof(task)); Start(task, TimeSpan.Zero); } public void Start(Func<Task> task, TimeSpan delay) { if (task == null) throw new ArgumentNullException(nameof(task)); #pragma warning disable 4014 // Fire-and-forget Task.Factory.StartNew(async () => { await _delayer.Delay(delay).ConfigureAwait(continueOnCapturedContext: false); await task().ConfigureAwait(continueOnCapturedContext: false); }); #pragma warning restore 4014 } } }
using System.Compiler; using System.Diagnostics.Contracts; namespace Microsoft.Contracts.Foxtrot.Utils { internal static class TypeNodeExtensions { // TODO: retire this method after moving to C# 6.0 public static int TemplateArgumentsCount(this TypeNode typeNode) { Contract.Requires(typeNode != null); return typeNode.TemplateArguments == null ? 0 : typeNode.TemplateArguments.Count; } // TODO: retire this method after moving to C# 6.0 public static int TemplateArgumentsCount(this Method method) { Contract.Requires(method != null); return method.TemplateArguments == null ? 0 : method.TemplateArguments.Count; } // TODO: retire this method ater moving to C# 6.0 public static int CountOrDefault(this TypeNodeList list) { return list == null ? 0 : list.Count; } public static bool IsNullOrEmpty(this TypeNodeList list) { return list == null || list.Count == 0; } } }
using Newtonsoft.Json; using System; namespace Smart.Web.Mvc.UI.FullCalendar { public class EventObject { /// <summary> /// 可选,事件唯一标识,重复的事件具有相同的id /// </summary> [JsonProperty("id")] public string Id { get; set; } /// <summary> /// 必须,事件在日历上显示的title /// </summary> [JsonProperty("title")] public string Title { get; set; } /// <summary> /// 可选,true or false,是否是全天事件。 /// </summary> [JsonProperty("allDay")] public bool AllDay { get; set; } /// <summary> /// 必须,事件的开始时间。 /// </summary> [JsonProperty("start")] public DateTime Start { get; set; } /// <summary> /// 可选,结束时间。 /// </summary> [JsonProperty("end")] public DateTime End { get; set; } /// <summary> /// 可选,当指定后,事件被点击将打开对应url。 /// </summary> [JsonProperty("url")] public string Url { get; set; } /// <summary> /// 指定事件的样式。 /// </summary> [JsonProperty("className")] public string ClassName { get; set; } /// <summary> /// 事件是否可编辑,可编辑是指可以移动, 改变大小等。 /// </summary> [JsonProperty("editable")] public bool Editable { get; set; } ///// <summary> ///// 指向次event的eventsource对象。 ///// </summary> //public string source { get; set; } /// <summary> /// 背景和边框颜色。 /// </summary> [JsonProperty("color")] public string Color { get; set; } ///// <summary> ///// 背景颜色。 ///// </summary> //[JsonProperty("backgroundColor")] //public string BackgroundColor { get; set; } ///// <summary> ///// 边框颜色。 ///// </summary> //[JsonProperty("borderColor")] //public string BorderColor { get; set; } ///// <summary> ///// 文本颜色。 ///// </summary> //[JsonProperty("textColor")] //public string TextColor { get; set; } } public class EventObjectColor { public string Red = "#f56954"; public string Yellow = "#f39c12"; public string Blue = "#0073b7"; public string Aqua = "#00c0ef"; public string Green = "#00a65a"; public string Light_Blue = "#3c8dbc"; } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Movie_Application.Client.Helper { public interface IHttpService { Task<HttpResponseWrapper<T>> Get<T>(string url); Task<HttpResponseWrapper<object>> Post<T>(string url, T data); Task<HttpResponseWrapper<TResponse>> Post<T, TResponse>(string url, T data); } }