content
stringlengths
23
1.05M
// ----------------------------------------------------------------------- // <copyright file="RasterImage.cs" company=""> // Christian Woltering, Triangle.NET, http://triangle.codeplex.com/ // </copyright> // ----------------------------------------------------------------------- namespace MeshExplorer.IO { using System.IO; using System.IO.Compression; using TriangleNet; using TriangleNet.Rendering.GDI; using TriangleNet.Rendering.Text; /// <summary> /// Writes an image of the mesh to disk. /// </summary> public class ImageWriter { /// <summary> /// Export the mesh to PNG format. /// </summary> /// <param name="mesh">The current mesh.</param> /// <param name="filename">The PNG filename.</param> /// <param name="type">Image type (0 = png, 1 = eps, 2 = svg).</param> /// <param name="width">The desired width of the image.</param> /// <param name="compress">Use GZip compression (only eps or svg).</param> public void Export(Mesh mesh, string filename, int type, int width, bool compress) { if (type == 1) { ExportEps(mesh, filename, width, compress); } else if (type == 2) { ExportSvg(mesh, filename, width, compress); } else { ImageRenderer.Save(mesh, filename, width); } } private void ExportEps(Mesh mesh, string filename, int width, bool compress) { var eps = new EpsImage(); eps.Export(mesh, filename, width); if (compress) { CompressFile(filename, true); } } private void ExportSvg(Mesh mesh, string filename, int width, bool compress) { var svg = new SvgImage(); svg.Export(mesh, filename, width); if (compress) { CompressFile(filename, true); } } private void CompressFile(string filename, bool cleanup) { if (!File.Exists(filename)) { return; } using (var input = File.OpenRead(filename)) using (var output = File.Create(filename + ".gz")) using (var gzip = new GZipStream(output, CompressionMode.Compress)) { input.CopyTo(gzip); } if (cleanup) { File.Delete(filename); } } } }
namespace RecipeApp.UI.WPF.ViewModels.Recipe { public interface IRecipeViewModel { } }
using System; using System.Globalization; using Microsoft.CodeAnalysis.Text; using Xunit; namespace NationalInstruments.Analyzers.Utilities.UnitTests { /// <summary> /// Tests for <see cref="SourceTextExtensions"/>. /// </summary> public sealed class SourceTextExtensionTests { [Fact] public void NullSourceText_Parse_Throws() { SourceText sourceText = null; Assert.Throws<ArgumentNullException>("text", () => sourceText.Parse(stream => stream.ReadToEnd())); } [Fact] public void SourceText_ParseWithNullFunction_Throws() { var sourceText = SourceText.From(string.Empty); Assert.Throws<ArgumentNullException>("parser", () => sourceText.Parse<int>(null)); } [Fact] public void SourceText_Parse_ReturnsParserFunctionOutput() { var sourceText = SourceText.From("text"); var contents = sourceText.Parse(stream => stream.ReadToEnd().ToUpper(CultureInfo.InvariantCulture)); Assert.Equal("TEXT", contents); } } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public sealed class PlatformFactory { public ObjectPool pool; public static PlatformFactory instance; private InGamePlatform _inGamePlatform; public static PlatformFactory GetInstance() { if (instance == null) { instance = new PlatformFactory(); } return instance; } public IPlatform GetPlatform(PlatformConfig config) { if (pool.objectGroupNames.Contains(config.name)) { if (_inGamePlatform == null) { _inGamePlatform = new InGamePlatform(); } _inGamePlatform.pool = pool; return _inGamePlatform; } else { throw new Exception("There is no InGameObject with name: " + config.name); } } public Vector3 getEndingPosition(GameObject last) { return last.GetComponent<InGameObject>().boundaries.endPosition + last.transform.position; } public void DeactivateObject(GameObject levelObject) { if (levelObject.GetComponent<InGameObject>() != null) { pool.DeactivateObject(levelObject.GetComponent<InGameObject>()); } } }
using Xunit; using CSharpDS; namespace CSharpDSTests { public class MostCommonWordProblemTests { private MostCommonWordProblem tSub; public MostCommonWordProblemTests() { tSub = new MostCommonWordProblem(); } [Fact] public void UniqueSubstringTest1() { //Given var paragraph = "Bob hit a ball, the hit BALL flew far after it was hit."; var banned = new string[] { "hit" }; //When var expected = "ball"; var actual = tSub.MostCommonWord(paragraph, banned); //Then Assert.Equal(expected, actual); } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; namespace MscLib { /// <summary> /// This can spawn a variety of items, primarily those sold by Teimo with few others /// </summary> public class Spawner : MonoBehaviour { private static Spawner _instance; private GameObject spawnerObject; /// <summary> /// All spawnable item types /// </summary> public enum ItemType { BEER, SAUSAGE, MACARONBOX, PIZZA, CHIPS, JUICE, YEAST, SUGAR, MILK, MOSQUITOSPRAY, COOLANT, BRAKEFLUID, MOTOROIL, TWOSTROKE_FUEL, FIRE_EXTINGUISHER, NITROUS_BOTTLE, BATTERY, CIGARETTES, OILFILTER, SPARKPLUG_BOX, COFFEE, CHARCOAL, ALTERNATOR_BELT, SPARKPLUG }; //This is just a convenience to help convert the ItemType enum names into strings //for cases where we can't just titlecase it easily private static Dictionary<ItemType, string> itemMapping = new Dictionary<ItemType, string> { { ItemType.SAUSAGE, "Sausages" }, { ItemType.MACARONBOX, "MacaronBox" }, { ItemType.MOSQUITOSPRAY, "MosquitoSpray" }, { ItemType.BRAKEFLUID, "BrakeFluid" }, { ItemType.MOTOROIL, "MotorOil" }, { ItemType.TWOSTROKE_FUEL, "TwoStroke" }, { ItemType.FIRE_EXTINGUISHER, "FireExtinguisher" }, { ItemType.NITROUS_BOTTLE, "N2OBottle" }, { ItemType.SPARKPLUG_BOX, "SparkplugBox" }, { ItemType.ALTERNATOR_BELT, "Alternatorbelt" }, }; private Spawner() { spawnerObject = GameObject.Find("Spawner/CreateItems"); } /// <summary> /// Spawn an item /// </summary> /// <param name="t">Item type</param> /// <returns>New item's GameObject</returns> public static GameObject SpawnItem(ItemType t) { string fsmName; if (itemMapping.ContainsKey(t)) { fsmName = itemMapping[t]; } else { var itemString = t.ToString(); fsmName = char.ToUpper(itemString[0]) + itemString.Substring(1).ToLower(); } var fsm = PlayMakerFSM.FindFsmOnGameObject(Instance.spawnerObject, fsmName); //this triggers the item to spawn fsm.SendEvent("SPAWNITEM"); //the spawner fsm stores a reference to the newly created object in this variable return fsm.FsmVariables.FindFsmGameObject("New").Value; } private static Spawner Instance { get { if (_instance == null) { var go = new GameObject("MscLib_Spawner"); _instance = go.AddComponent<Spawner>(); } return _instance; } } void OnDestroy() { _instance = null; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using GameEngine.Common; using TestHarness.TestHarnesses.SocketHarness; namespace SocketHost { public class ClientRegistrationService : IDisposable { public const int Port = 19010; private readonly Socket _socket; private readonly List<Player> _players = new List<Player>(); public ClientRegistrationService() { var ipHost = Dns.GetHostEntry(""); _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); foreach (var ipAddress in ipHost.AddressList.Where(x => x.AddressFamily == AddressFamily.InterNetwork)) { var ipEndPoint = new IPEndPoint(ipAddress, Port); _socket.Bind(ipEndPoint); } Console.WriteLine("Waiting for client registrations on port " + Port); _socket.Listen(12); _socket.BeginAccept(ConnectCallBack, _socket); } public List<Player> Players { get { return _players; } } private void ConnectCallBack(IAsyncResult ar) { try { var listener = (Socket) ar.AsyncState; var clientSocket = listener.EndAccept(ar); var state = new SocketState() { Socket = clientSocket, ByteBuffer = new byte[10240] }; clientSocket.BeginReceive(state.ByteBuffer, 0, state.ByteBuffer.Length, SocketFlags.None, ReceiveCallBack, state); _socket.BeginAccept(ConnectCallBack, _socket); } catch (ObjectDisposedException) { //This is supposed to happen once the game is started and no clients can be registered anymore } } private void ReceiveCallBack(IAsyncResult ar) { var socketState = (SocketState)ar.AsyncState; var socket = socketState.Socket; var result = SocketHarnessMessage.ProcessMessage(ar); socket.EndReceive(ar); switch (result.MessageType) { case SocketHarnessMessage.MessageType.RegisterPlayer: HandleRegistration(socket, result.Message); break; default: throw new ArgumentException("Only registration messages allowed " + result.MessageType); } } private void HandleRegistration(Socket socket, String name) { var port = 20000 + _players.Count; var player = new SocketServer(name, port); _players.Add(player); SocketHarnessMessage.SendMessage(socket, SocketHarnessMessage.MessageType.RegistrationPort, port.ToString(), Callback); } private void Callback(IAsyncResult ar) { var socketState = (SocketState)ar.AsyncState; var socket = socketState.Socket; if (socket.Connected) { socket.Disconnect(false); socket.Close(); } socket.Close(); } public void Dispose() { _socket.Close(); _socket.Close(); } } }
using System; using amulware.Graphics; using OpenTK.Input; namespace Squarrel { public abstract class WorldObject<Env> where Env : GameEnvironment<Env> { protected Env environment { get; private set; } protected KeyboardDevice keyboard { get { return this.environment.Keyboard; } } protected MouseDevice mouse { get { return this.environment.Mouse; } } public WorldObject(Env environment) { this.environment = environment; } abstract public void Update(UpdateEventArgs e); } }
using System; using MonoTouch.CoreFoundation; using MonoTouch.Foundation; namespace Toggl.Ross { public static class DispatchQueueExtensions { public static void DispatchAfter (this DispatchQueue self, TimeSpan delay, NSAction action) { var time = new DispatchTime (DispatchTime.Now, delay.Ticks * 100); self.DispatchAfter (time, action); } } }
using System.Diagnostics; using FreeSql; using FreeSql.Internal; using LinCms.Core.Entities; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; namespace LinCms.IdentityServer4 { public static class DependencyInjectionExtensions { #region FreeSql /// <summary> /// FreeSql /// </summary> /// <param name="services"></param> public static void AddContext(this IServiceCollection services) { var configuration = services.BuildServiceProvider().GetRequiredService<IConfiguration>(); IConfigurationSection configurationSection = configuration.GetSection("ConnectionStrings:MySql"); IFreeSql fsql = new FreeSqlBuilder() .UseConnectionString(DataType.MySql, configurationSection.Value) .UseNameConvert(NameConvertType.PascalCaseToUnderscoreWithLower) .UseAutoSyncStructure(true) .UseMonitorCommand(cmd => { Trace.WriteLine(cmd.CommandText); } ) .Build(); fsql.CodeFirst.IsSyncStructureToLower = true; services.AddSingleton(fsql); services.AddScoped<UnitOfWorkManager>(); services.AddFreeRepository(filter => { filter.Apply<IDeleteAduitEntity>("IsDeleted", a => a.IsDeleted == false); }); } #endregion } }
namespace P01.CommandPattern { using P01.CommandPattern.Core; using P01.CommandPattern.Core.Interfaces; public class StartUp { internal static void Main() { ICommandInterpreter command = new CommandInterpreter(); IEngine engine = new Engine(command); engine.Run(); } } }
// ReSharper disable InconsistentNaming namespace BuildMaster.Net.Native.Models { public class EventOccurrenceDetails { public int EventOccurence_Id { get; set; } public string Event_Code { get; set; } public string Detail_Name { get; set; } public object Detail_Value { get; set; } } }
/* * Copyright (c) 2016 Samsung Electronics Co., Ltd * * 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://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using Tizen.NUI; using Tizen.NUI.BaseComponents; namespace NUI_CustomView { public class ContactView : CustomView { private string name; private string resourceDirectory; //Indexes for registering Visuals in the CustomView private const int BaseIndex = 10000; private const int BackgroundVisualIndex = BaseIndex + 1; private const int LabelVisualIndex = BaseIndex + 2; private const int ContactBgIconIndex = BaseIndex + 3; private const int ContactIconIndex = BaseIndex + 4; private const int ContactEditIndex = BaseIndex + 5; private const int ContactFavoriteIndex = BaseIndex + 6; private const int ContactDeleteIndex = BaseIndex + 7; static ContactView() { //Each custom view must have its static constructor to register its type. CustomViewRegistry.Instance.Register(CreateInstance, typeof(ContactView)); } static CustomView CreateInstance() { //Create and return valid custom view object. In this case ContactView is created. return new ContactView(null, null); } /// <summary> /// Creates and register background color visual. /// </summary> /// <param name="color">RGBA color vector</param> private void CreateBackground(Vector4 color) { PropertyMap map = new PropertyMap(); map.Add(Visual.Property.Type, new PropertyValue((int)Visual.Type.Color)) .Add(ColorVisualProperty.MixColor, new PropertyValue(color)); VisualBase background = VisualFactory.Instance.CreateVisual(map); RegisterVisual(BackgroundVisualIndex, background); background.DepthIndex = BackgroundVisualIndex; } /// <summary> /// Creates and register label visual. /// </summary> /// <param name="text">String viewed by created label</param> private void CreateLabel(string text) { PropertyMap textVisual = new PropertyMap(); textVisual.Add(Visual.Property.Type, new PropertyValue((int)Visual.Type.Text)) .Add(TextVisualProperty.Text, new PropertyValue(text)) .Add(TextVisualProperty.TextColor, new PropertyValue(Color.Black)) .Add(TextVisualProperty.PointSize, new PropertyValue(12)) .Add(TextVisualProperty.HorizontalAlignment, new PropertyValue("CENTER")) .Add(TextVisualProperty.VerticalAlignment, new PropertyValue("CENTER")); VisualBase label = VisualFactory.Instance.CreateVisual(textVisual); RegisterVisual(LabelVisualIndex, label); label.DepthIndex = LabelVisualIndex; PropertyMap imageVisualTransform = new PropertyMap(); imageVisualTransform.Add((int)VisualTransformPropertyType.Offset, new PropertyValue(new Vector2(30, 5))) .Add((int)VisualTransformPropertyType.OffsetPolicy, new PropertyValue(new Vector2((int)VisualTransformPolicyType.Absolute, (int)VisualTransformPolicyType.Absolute))) .Add((int)VisualTransformPropertyType.SizePolicy, new PropertyValue(new Vector2((int)VisualTransformPolicyType.Absolute, (int)VisualTransformPolicyType.Absolute))) .Add((int)VisualTransformPropertyType.Size, new PropertyValue(new Vector2(350, 100))); label.SetTransformAndSize(imageVisualTransform, new Vector2(this.SizeWidth, this.SizeHeight)); } /// <summary> /// Creates and register icon image. /// </summary> /// <param name="url">Icon absolute path</param> /// <param name="x">x icon position</param> /// <param name="y">y icon position</param> /// <param name="w">icon width</param> /// <param name="h">icon height</param> /// <param name="index">visuals registration index</param> private void CreateIcon(string url, float x, float y, float w, float h, int index) { PropertyMap map = new PropertyMap(); PropertyMap transformMap = new PropertyMap(); map.Add(Visual.Property.Type, new PropertyValue((int)Visual.Type.Image)) .Add(ImageVisualProperty.URL, new PropertyValue(url)); VisualBase icon = VisualFactory.Instance.CreateVisual(map); PropertyMap imageVisualTransform = new PropertyMap(); imageVisualTransform.Add((int)VisualTransformPropertyType.Offset, new PropertyValue(new Vector2(x, y))) .Add((int)VisualTransformPropertyType.OffsetPolicy, new PropertyValue(new Vector2((int)VisualTransformPolicyType.Absolute, (int)VisualTransformPolicyType.Absolute))) .Add((int)VisualTransformPropertyType.SizePolicy, new PropertyValue(new Vector2((int)VisualTransformPolicyType.Absolute, (int)VisualTransformPolicyType.Absolute))) .Add((int)VisualTransformPropertyType.Size, new PropertyValue(new Vector2(w, h))) .Add((int)VisualTransformPropertyType.Origin, new PropertyValue((int)Visual.AlignType.CenterBegin)) .Add((int)VisualTransformPropertyType.AnchorPoint, new PropertyValue((int)Visual.AlignType.CenterBegin)); icon.SetTransformAndSize(imageVisualTransform, new Vector2(this.SizeWidth, this.SizeHeight)); RegisterVisual(index, icon); icon.DepthIndex = index; } /// <summary> /// Contact View constructor /// </summary> /// <param name="name">name viewed by CustomView object</param> /// <param name="resourceDirectory">resource directory path used to create absolute paths to icons</param> /// <returns></returns> public ContactView(string name, string resourceDirectory) : base(typeof(ContactView).Name, CustomViewBehaviour.ViewBehaviourDefault) { this.name = name; this.resourceDirectory = resourceDirectory; //Add background to contact view CreateBackground(new Vector4(1.0f, 1.0f, 1.0f, 1.0f)); //Append icons using absolute path and icons positions parameters. CreateIcon(resourceDirectory + "/images/cbg.png", 10.0f, 5.0f, 100.0f, 100.0f, ContactBgIconIndex); CreateIcon(resourceDirectory + "/images/contact.png", 10.0f, 5.0f, 100.0f, 100.0f, ContactIconIndex); CreateIcon(resourceDirectory + "/images/edit.png", 130.0f, 40.0f, 50.0f, 50.0f, ContactEditIndex); CreateIcon(resourceDirectory + "/images/favorite.png", 180.0f, 40.0f, 50.0f, 50.0f, ContactFavoriteIndex); CreateIcon(resourceDirectory + "/images/delete.png", 640.0f, 40.0f, 50.0f, 50.0f, ContactDeleteIndex); //Append title CreateLabel(name); } } }
// ---------------------------------------------------------- // <project>QCV</project> // <author>Christoph Heindl</author> // <copyright>Copyright (c) Christoph Heindl 2010</copyright> // <license>New BSD</license> // ---------------------------------------------------------- using System; using System.Collections.Generic; namespace QCV.Base { /// <summary> /// A filter that takes an action to be executed. /// </summary> public class AnonymousFilter : IFilter { /// <summary> /// The action to carry out. /// </summary> private Action<Dictionary<string, object>> _action; /// <summary> /// Initializes a new instance of the AnonymousFilter class. /// </summary> /// <param name="action">Action to be carried out.</param> public AnonymousFilter(Action<Dictionary<string, object>> action) { _action = action; } /// <summary> /// Execute the filter. /// </summary> /// <param name="b">Bundle containing filter parameters.</param> public void Execute(Dictionary<string, object> b) { _action(b); } } }
using Laser.Orchard.MultiStepAuthentication.Controllers; using Laser.Orchard.MultiStepAuthentication.Permissions; using Orchard.Environment.Extensions; using Orchard.Localization; using Orchard.UI.Navigation; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Laser.Orchard.MultiStepAuthentication.Navigation { [OrchardFeature("Laser.Orchard.MultiStepAuthentication")] public class MultiStepAuthenticationNavigation : INavigationProvider { private readonly IEnumerable<IMultiStepAdminController> _settingsControllers; public MultiStepAuthenticationNavigation( IEnumerable<IMultiStepAdminController> settingsControllers) { _settingsControllers = settingsControllers; T = NullLocalizer.Instance; } public Localizer T { get; set; } public string MenuName { get { return "admin"; } } public void GetNavigation(NavigationBuilder builder) { if (_settingsControllers.Any()) { builder.Add(T("Settings"), menu => menu .Add(T("MultiStep Authentication"), "10.0", submenu => { submenu .Action(_settingsControllers.First().ActionName, _settingsControllers.First().ControllerName, new { area = _settingsControllers.First().AreaName }) .Permission(MultiStepAuthenticationPermissions.ConfigureAuthentication); foreach (var controller in _settingsControllers) { submenu.Add(controller.Caption, "10", item => item .Action(controller.ActionName, controller.ControllerName, new { area = controller.AreaName }) .Permission(MultiStepAuthenticationPermissions.ConfigureAuthentication) .LocalNav()); } })); } } } }
using DevOps.Util; using DevOps.Util.DotNet; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace DevOps.Util.DotNet { public readonly struct NGenAssemblyData { public string AssemblyName { get; } public string TargetFramework { get; } public int MethodCount { get; } public NGenAssemblyData( string assemblyName, string targetFramework, int methodCount) { AssemblyName = assemblyName; TargetFramework = targetFramework; MethodCount = methodCount; } public override string ToString() => $"{AssemblyName} - {TargetFramework}"; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; /// <summary> /// 该接口用于进行玩家施法状态同步。该接口的实例作为Unit的成员变量存储于Unit中。 /// </summary> public interface ISyncPlayerCastingState { /// <summary> /// 同步技能开始施法。 /// </summary> /// <param name="instant">开始施法的时刻</param> /// <param name="skillIndex">技能序号,指玩家的技能槽位的序号,取值1,2,3,4</param> void SyncStart(long instant, int skillIndex); /// <summary> /// 同步技能停止施法。 /// </summary> /// <param name="instant">停止施法的时刻</param> /// <param name="skillIndex">技能序号,指玩家的技能槽位的序号,取值1,2,3,4</param> void SyncStop(long instant, int skillIndex); /// <summary> /// 同步瞄准目标。 /// </summary> /// <param name="target">目标</param> void SyncTarget(long instant, Unit target); /// <summary> /// 初始化同步类。 /// </summary> /// <param name="unit">接受同步的单位</param> void Init(Unit unit); }
using System.Data.Entity.ModelConfiguration; namespace AIM.Service.Entities.Models.Mapping { public class UserMap : EntityTypeConfiguration<User> { public UserMap() { // Primary Key this.HasKey(t => t.UserId); // Properties this.Property(t => t.FirstName) .HasMaxLength(25); this.Property(t => t.MiddleName) .HasMaxLength(25); this.Property(t => t.LastName) .HasMaxLength(40); this.Property(t => t.Email) .HasMaxLength(100); this.Property(t => t.SocialSecurityNumber) .HasMaxLength(11); this.Property(t => t.UserName) .HasMaxLength(256); this.Property(t => t.Password) .HasMaxLength(50); this.Property(t => t.AspNetUsersId) .HasMaxLength(128); // Table & Column Mappings this.ToTable("Users"); this.Property(t => t.UserId).HasColumnName("UserId"); this.Property(t => t.FirstName).HasColumnName("FirstName"); this.Property(t => t.MiddleName).HasColumnName("MiddleName"); this.Property(t => t.LastName).HasColumnName("LastName"); this.Property(t => t.Email).HasColumnName("Email"); this.Property(t => t.SocialSecurityNumber).HasColumnName("SocialSecurityNumber"); this.Property(t => t.PersonalInfoId).HasColumnName("PersonalInfoId"); this.Property(t => t.ApplicantId).HasColumnName("ApplicantId"); this.Property(t => t.ApplicationId).HasColumnName("ApplicationId"); this.Property(t => t.EmployeeId).HasColumnName("EmployeeId"); this.Property(t => t.UserName).HasColumnName("UserName"); this.Property(t => t.Password).HasColumnName("Password"); this.Property(t => t.AspNetUsersId).HasColumnName("AspNetUsersId"); // Tracking Properties this.Ignore(t => t.TrackingState); this.Ignore(t => t.ModifiedProperties); // Relationships this.HasOptional(t => t.Applicant) .WithMany(t => t.Users) .HasForeignKey(d => d.ApplicantId); this.HasOptional(t => t.AspNetUser) .WithMany(t => t.Users) .HasForeignKey(d => d.AspNetUsersId); this.HasOptional(t => t.Employee) .WithMany(t => t.Users) .HasForeignKey(d => d.EmployeeId); this.HasOptional(t => t.PersonalInfo) .WithMany(t => t.Users) .HasForeignKey(d => d.PersonalInfoId); } } }
using Xunit; namespace FacioRatio.CSharpRailway.Tests { public class ResultEmptyTExtensionsTests { [Fact] public void Empty_Fails() { var sut = Result.Fail<int>("fail"); var result = sut.Empty(); Assert.True(result.IsFailure); Assert.IsAssignableFrom<Empty>(result.ValueOrFallback(new Empty())); Assert.Equal("fail", result.Error.Message); } [Fact] public void Empty_Succeeds() { var sut = Result.Ok<int>(1); var result = sut.Empty(); Assert.True(result.IsSuccess); Assert.Null(result.ValueOrFallback()); } } }
using Catalog.Api.Datas.Interfaces; using Catalog.Api.Entities; using Catalog.Api.Utilities.Constants; using Microsoft.Extensions.Configuration; using MongoDB.Driver; namespace Catalog.Api.Datas { public class CatalogContext : ICatalogContext { public CatalogContext(IConfiguration config) { Setup(config); CatalogContextSeed.SeedData(this); } public IMongoCollection<Product> Products { get; set; } private void Setup(IConfiguration config) { var db = GetDatabase(config); Products = GetCollection<Product>(db, Constants.COLLECTION_PRODUCT); } private IMongoDatabase GetDatabase(IConfiguration config) { var client = new MongoClient(config.GetValue<string>(Constants.CATALOG_DB_CONN_STRING)); var db = client.GetDatabase(Constants.CATALOG_DB); return db; } private IMongoCollection<T> GetCollection<T>(IMongoDatabase db, string name) { return db.GetCollection<T>(name); } } }
using Jarvis.Framework.Shared.ReadModel; using NUnit.Framework; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Jarvis.Framework.Tests.SharedTests.ReadModel { [TestFixture] public class AbstractChildReadModelTests { [Test] public void Verify_replace_helper_dischard_duplicates() { var rm1 = new ReadModelTest("test1", 42); var rm2 = new ReadModelTest("test1", 42); List<ReadModelTest> sut = new List<ReadModelTest>(); sut.AddOrReplace(rm1); sut.AddOrReplace(rm2); Assert.That(sut.Count, Is.EqualTo(1)); } [Test] public void Verify_replace_helper_works_with_unique_ids() { var rm1 = new ReadModelTest("test1", 42); var rm2 = new ReadModelTest("test2", 42); List<ReadModelTest> sut = new List<ReadModelTest>(); sut.AddOrReplace(rm1); sut.AddOrReplace(rm2); Assert.That(sut.Count, Is.EqualTo(2)); } public class ReadModelTest : AbstractChildReadModel<String> { public ReadModelTest(string id, int value) { Id = id; Value = value; } public Int32 Value { get; set; } } } }
using System; using System.ComponentModel.DataAnnotations; using System.Runtime.CompilerServices; namespace MvcHelpers.Validation { public sealed class PropertyRequiredAttribute : RequiredAttribute { public string PropertyName { get; private set; } public PropertyRequiredAttribute([CallerMemberName] string propertyName = null) { PropertyName = propertyName; AllowEmptyStrings = false; ErrorMessage = String.Format("{0} required", PropertyName); } } }
using System; using System.Diagnostics; using System.IO; using System.Text; using UnityEditor; using UnityEngine; using Debug = UnityEngine.Debug; public class BuildPostprocessor { private const string ExtractorPath = "Tools/AssetBundleExtractor/AssetBundleExtractor.exe"; private readonly string _bundlePath; #if UNITY_EDITOR public BuildPostprocessor(string bundlePath) { _bundlePath = bundlePath; } public void Run() { byte[] bytes = File.ReadAllBytes(_bundlePath); PatchPlatform(bytes); PatchAbDependencies(bytes); PatchDependencyPointers(bytes); File.WriteAllBytes(_bundlePath, bytes); } private void PatchPlatform(byte[] bytes) { Debug.Log("Patching platform..."); // The platform is located after the second version string string str = Encoding.ASCII.GetString(bytes); string unityVersion = Application.unityVersion; int index = str.LastIndexOf(unityVersion, StringComparison.InvariantCulture); if (index < 0) { Debug.LogError("Could not patch platform"); } index += unityVersion.Length + 1; // 00 terminated string using (var s = new BinaryWriter(new MemoryStream(bytes))) { s.Seek(index, SeekOrigin.Begin); s.Write((uint) BuildTarget.Switch); // Change it to a Switch bundle } } private void PatchAbDependencies(byte[] bytes) { Debug.Log("Patching shader pack archive dependency..."); string ourShaderPack = "archive:/cab-411f45211d405148b72c6a1e052b5a20/cab-411f45211d405148b72c6a1e052b5a20"; string originalPath = "archive:/cab-caafd6a11c9514e386d3454c9c3a0782/cab-caafd6a11c9514e386d3454c9c3a0782"; string str = Encoding.ASCII.GetString(bytes); // Loop through all instances of our path. int count = 0; int i = 0; while ((i = str.IndexOf(ourShaderPack, i, StringComparison.Ordinal)) != -1) { var originalPathBytes = Encoding.ASCII.GetBytes(originalPath); Array.Copy(originalPathBytes, 0, bytes, i, originalPathBytes.Length); i += ourShaderPack.Length; count++; } Debug.Log($"Replaced {count} times."); } private void PatchDependencyPointers(byte[] bytes) { Debug.Log("Patching dependency pointers..."); var dependencyMap = DependencyPathIdMap.Load().OptimizedMap; int count = 0; var memStream = new MemoryStream(bytes); using (var s = new BinaryReader(memStream)) { while (s.BaseStream.Position < s.BaseStream.Length - 8) { long ourPathId = s.ReadInt64(); s.BaseStream.Position -= 7; if (dependencyMap.ContainsKey(ourPathId)) { long origPathId = dependencyMap[ourPathId]; var wr = new BinaryWriter(memStream); wr.Seek((int) wr.BaseStream.Position - 1, SeekOrigin.Begin); wr.Write(origPathId); wr.Flush(); count++; } } } Debug.Log($"Replaced {count} dependency path IDs."); } #endif }
using System; using System.Linq; namespace NGitLab.Mock { public sealed class BadgeCollection : Collection<Badge> { public BadgeCollection(GitLabObject parent) : base(parent) { } public Badge GetById(int id) { return this.FirstOrDefault(badge => badge.Id == id); } public override void Add(Badge item) { if (item == null) throw new ArgumentNullException(nameof(item)); if (item.Id == default) { item.Id = Server.GetNewBadgeId(); } else if (GetById(item.Id) != null) { throw new GitLabException("Badge already exists."); } base.Add(item); } public Badge Add(string linkUrl, string imageUrl) { var badge = new Badge { LinkUrl = linkUrl, ImageUrl = imageUrl, }; Add(badge); return badge; } } }
using System; using System.Collections.Generic; namespace SharpShell.ServerRegistration { /// <summary> /// Represents registration info for a server. /// </summary> public class ShellExtensionRegistrationInfo { internal ShellExtensionRegistrationInfo() { } /// <summary> /// Initializes a new instance of the <see cref="ShellExtensionRegistrationInfo"/> class. /// </summary> /// <param name="serverRegistationType">Type of the server registation.</param> /// <param name="serverCLSID">The server CLSID.</param> public ShellExtensionRegistrationInfo(ServerRegistationType serverRegistationType, Guid serverCLSID) { ServerRegistationType = serverRegistationType; ServerCLSID = serverCLSID; } /// <summary> /// The class registrations. /// </summary> internal readonly List<ClassRegistration> classRegistrations = new List<ClassRegistration>(); /// <summary> /// Gets the server CLSID. /// </summary> public Guid ServerCLSID { get; internal set; } /// <summary> /// Gets the type of the shell extension. /// </summary> /// <value> /// The type of the shell extension. /// </value> public ShellExtensionType ShellExtensionType { get; internal set; } /// <summary> /// Gets the display name. /// </summary> /// <value> /// The display name. /// </value> public string DisplayName { get; internal set; } /// <summary> /// Gets the server path. /// </summary> public string ServerPath { get; internal set; } /// <summary> /// Gets the threading model. /// </summary> public string ThreadingModel { get; internal set; } /// <summary> /// Gets the assembly version. /// </summary> public string AssemblyVersion { get; internal set; } /// <summary> /// Gets the assembly. /// </summary> public string Assembly { get; internal set; } /// <summary> /// Gets the class. /// </summary> public string Class { get; internal set; } /// <summary> /// Gets the runtime version. /// </summary> public string RuntimeVersion { get; internal set; } /// <summary> /// Gets the codebase path. /// </summary> public string CodeBase { get; internal set; } /// <summary> /// Gets a value indicating whether this extension is on the approved list. /// </summary> /// <value> /// <c>true</c> if this instance is approved; otherwise, <c>false</c>. /// </value> public bool IsApproved { get; internal set; } /// <summary> /// Gets the type of the server registation. /// </summary> /// <value> /// The type of the server registation. /// </value> public ServerRegistationType ServerRegistationType { get; internal set; } /// <summary> /// Gets the class registrations. /// </summary> /// <value> /// The class registrations. /// </value> public IEnumerable<ClassRegistration> ClassRegistrations { get { return classRegistrations; } } } }
using System.Collections.Generic; namespace Jirapi.Resources { public class EggGroup { public int Id { get; set; } public string Name { get; set; } public List<Name> Names { get; set; } /// <summary> /// A list of all Pokémon species that are members of this egg group. /// </summary> /// <value>The pokemon species.</value> /// [Newtonsoft.Json.JsonProperty("pokemon_species")] public List<NamedApiResource<PokemonSpecies>> PokemonSpecies { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; namespace FirePlace.Util { public class SceneCheckPoint : MonoBehaviour { public enum Action { Load, Unload }; //public enum Tipo { Clique, Colisao }; //public Tipo tipo = Tipo.Clique; public Action action = Action.Load; public bool addictive = true; public string sceneName = ""; private bool after = false; void Start () { after = false; } void OnTriggerEnter(Collider other) { if (other.gameObject.tag == "Player") { if (action == Action.Load) // If the scene has already been loaded unloads the scene. { if(after) SceneManager.UnloadSceneAsync(sceneName); else { if (!addictive) SceneManager.LoadSceneAsync(sceneName, LoadSceneMode.Single); else SceneManager.LoadSceneAsync(sceneName, LoadSceneMode.Additive); } after = !after; } else if(action == Action.Unload) { if(after) // If the scene has already been unloaded loads back the scene. { if(!addictive) SceneManager.LoadSceneAsync(sceneName, LoadSceneMode.Single); else SceneManager.LoadSceneAsync(sceneName, LoadSceneMode.Additive); } else SceneManager.UnloadSceneAsync(sceneName); after = !after; } } } } }
using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Navigation; using SoundByte.Core.Items.Podcast; using SoundByte.UWP.ViewModels; namespace SoundByte.UWP.Views { public sealed partial class PodcastShowView { public PodcastShowViewModel ViewModel { get; } = new PodcastShowViewModel(); public PodcastShowView() { InitializeComponent(); Unloaded += (s, e) => { ViewModel.Dispose(); }; } protected override void OnNavigatedTo(NavigationEventArgs e) { ViewModel.Init(e.Parameter as BasePodcast); } } }
using System; class A { ~A() { Console.WriteLine("Destruct instance of A"); } } class B { object Ref; public B(object o) { Ref = o; } ~B() { Console.WriteLine("Destruct instance of B"); } } class Test { static void Main() { B b = new B(new A()); b = null; GC.Collect(); GC.WaitForPendingFinalizers(); } }
using Cofoundry.Core.Configuration; using System.ComponentModel.DataAnnotations; namespace Bogevang.Website.Configuration { public class ThemeSettings : IConfigurationSettings { [Required] public string SiteTitle { get; set; } [Required] public string SiteSubTitle { get; set; } } }
using Metrics.SignalFx.Helpers; namespace Metrics.NET.SignalFx.UnitTest.Fakes { public class GenericFakeRequestorFactory<TRequestor> : IWebRequestorFactory where TRequestor : IWebRequestor, new() { public IWebRequestor GetRequestor() { return new TRequestor(); } } }
using System; using System.Collections.Generic; using System.Linq; using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.Dialog; using GCDiscreetNotification; namespace GCDiscreetNotificationDemo { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to // application events from iOS. [Register ("AppDelegate")] public partial class AppDelegate : UIApplicationDelegate { // class-level declarations UIWindow window; UINavigationController navController; DialogViewController dvc; EntryElement text2Show; BooleanElement topBottom; BooleanElement showActivity; GCDiscreetNotificationView notificationView; public override bool FinishedLaunching (UIApplication app, NSDictionary options) { window = new UIWindow (UIScreen.MainScreen.Bounds); var root = new RootElement ("Discreet Sample") { new Section ("Settings") { (text2Show = new EntryElement ("Text2Show:", "Some text here", "I'm so Discreet")), new StringElement ("Show", Show) { Alignment = UITextAlignment.Center }, new StringElement ("Hide", Hide) { Alignment = UITextAlignment.Center }, new StringElement ("Hide after 1 second", HideAfter1sec) { Alignment = UITextAlignment.Center }, (topBottom = new BooleanElement ("Top / Bottom", true)), (showActivity = new BooleanElement ("Show Activity?", true)) } }; dvc = new DialogViewController (root); navController = new UINavigationController (dvc); window.RootViewController = navController; window.MakeKeyAndVisible (); notificationView = new GCDiscreetNotificationView (text:text2Show.Value, activity: showActivity.Value, presentationMode: topBottom.Value ? GCDNPresentationMode.Top : GCDNPresentationMode.Bottom, view: dvc.View); showActivity.ValueChanged += ChangeActivity; topBottom.ValueChanged += ChangeTopBottom; text2Show.Changed += HandleChanged; return true; } void Show () { notificationView.Show (animated: true); } void Hide () { notificationView.Hide (animated: true); } void HideAfter1sec () { notificationView.hideAnimated (timeInterval: 1); } void ChangeActivity (object sender, EventArgs e) { notificationView.SetShowActivity (activity: showActivity.Value, animated: true); } void ChangeTopBottom (object sender, EventArgs e) { notificationView.PresentationMode = topBottom.Value ? GCDNPresentationMode.Top : GCDNPresentationMode.Bottom; } void HandleChanged (object sender, EventArgs e) { notificationView.SetTextLabel (text: text2Show.Value, animated: true); } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using Microsoft.Dnx.Testing.Framework; using Xunit; namespace Bootstrapper.FunctionalTests { [Collection(nameof(BootstrapperTestCollection))] public class BootstrapperTests : DnxSdkFunctionalTestBase { [Theory, TraceTest] [MemberData(nameof(DnxSdks))] public void UnknownCommandDoesNotThrow(DnxSdk sdk) { const string solutionName = "BootstrapperSolution"; const string projectName = "TesterProgram"; const string unknownCommand = "unknownCommand"; const string testerCommand = "TesterProgram"; var solution = TestUtils.GetSolution<BootstrapperTests>(sdk, solutionName); var project = solution.GetProject(projectName); var result = sdk.Dnx.Execute($"--project {project.ProjectDirectory} {unknownCommand}"); Assert.Equal(1, result.ExitCode); Assert.Equal($"Error: Unable to load application or execute command '{unknownCommand}'. Available commands: {testerCommand}.{Environment.NewLine}", result.StandardError); TestUtils.CleanUpTestDir<BootstrapperTests>(sdk); } [Theory, TraceTest] [MemberData(nameof(DnxSdks))] public void OverrideRidWithEnvironmentVariable(DnxSdk sdk) { var result = sdk.Dnx.Execute("--version", envSetup: env => env["DNX_RUNTIME_ID"] = "woozlewuzzle"); Assert.Contains("Runtime Id: woozlewuzzle", result.StandardOutput); } [Theory, TraceTest] [MemberData(nameof(DnxSdks))] public void UnresolvedProjectDoesNotThrow(DnxSdk sdk) { const string solutionName = "BootstrapperSolution"; var solution = TestUtils.GetSolution<BootstrapperTests>(sdk, solutionName); var result = sdk.Dnx.Execute($"--project {solution.RootPath} run"); Assert.Equal(1, result.ExitCode); Assert.Equal($"Error: Unable to resolve project from {solution.RootPath}{Environment.NewLine}", result.StandardError); TestUtils.CleanUpTestDir<BootstrapperTests>(sdk); } [Theory, TraceTest] [MemberData(nameof(DnxSdks))] public void UserExceptionsThrows(DnxSdk sdk) { const string solutionName = "BootstrapperSolution"; const string projectName = "TesterProgram"; var solution = TestUtils.GetSolution<BootstrapperTests>(sdk, solutionName); var project = solution.GetProject(projectName); sdk.Dnu.Restore(project).EnsureSuccess(); var result = sdk.Dnx.Execute($"--project {project.ProjectDirectory} run"); Assert.Equal(1, result.ExitCode); Assert.Contains("System.Exception: foo", result.StandardError); TestUtils.CleanUpTestDir<BootstrapperTests>(sdk); } } }
using OnlineChessCore.Game.Board; using OnlineChessCore.Game.Pieces; namespace OnlineChessCore.Game.Events.Args { public class PawnUpgradedArgs { public Piece NewPiece { get; set; } public Coords Coords { get; set; } } }
using Eternity.FlatBuffer; public interface IReformer : IShipItemBase { /// <summary> /// 基础数据 /// </summary> /// <returns></returns> Item GetBaseConfig(); /// <summary> /// 转化炉数据 /// </summary> /// <returns></returns> Weapon GetConfig(); /// <summary> /// lv /// </summary> /// <returns></returns> int GetLv(); }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Codeable.Foundation.Common.Daemons { [Serializable] public class DaemonConfig { public string InstanceName { get; set; } public bool ContinueOnError { get; set; } public int StartDelayMilliSeconds { get; set; } /// <summary> /// Below 1 for on demand /// </summary> public int IntervalMilliSeconds { get; set; } public string TaskConfiguration { get; set; } } }
using Hl7.Fhir.ElementModel; using Hl7.Fhir.Model; using Hl7.Fhir.Serialization; using Hl7.Fhir.Specification; using Hl7.Fhir.Utility; using Microsoft.Health.Fhir.Anonymizer.Core.Models; using System.Collections.Generic; using System.Linq; namespace Microsoft.Health.Fhir.Anonymizer.Core.Models { /// <summary> /// Empty element format example: /// { /// "resourceType": "Patient", /// "meta": { /// "security": [ /// { /// "system": "http://terminology.hl7.org/CodeSystem/v3-ObservationValue", /// "code": "REDACTED", /// "display": "redacted" /// } /// ] ///} /// </summary> public class EmptyElement: ITypedElement { public EmptyElement(string instanceType) { InstanceType = instanceType; } private static Meta _meta = new Meta() { Security = new List<Coding>() { SecurityLabels.REDACT } }; private static IStructureDefinitionSummaryProvider _provider = new PocoStructureDefinitionSummaryProvider(); private static FhirJsonParser _parser = new FhirJsonParser(); protected List<ITypedElement> ChildList = new List<ITypedElement>() { _meta.ToTypedElement("meta") }; public string Name => "empty"; public string InstanceType { get; set; } public object Value => null; public string Location => Name; public IElementDefinitionSummary Definition => ElementDefinitionSummary.ForRoot(_provider.Provide(InstanceType)); public IEnumerable<ITypedElement> Children(string name = null) => name == null ? ChildList : ChildList.Where(c => c.Name.MatchesPrefix(name)); public static bool IsEmptyElement(ITypedElement element) { if(element is EmptyElement) { return true; } return element.Children().Count() == 1 && element.Children("meta").Count() == 1; } public static bool IsEmptyElement(string elementJson) { try { var element = _parser.Parse(elementJson).ToTypedElement(); return IsEmptyElement(element); } catch { return false; } } public static bool IsEmptyElement(object element) { if (element is string) { return IsEmptyElement(element as string); } else if (element is ITypedElement) { return IsEmptyElement(element as ITypedElement); } return false; } } }
using Darecali.Strategy; using NUnit.Framework; using Shouldly; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Darecali.Tests.Strategy { [Category("Strategy")] public class EveryNthYearOnSpecifiedDayAndMonthStrategyFixture { #region Out of range parameter tests [Test] public void ShouldThrowWhenMonthLessThan1Test() { Shouldly.ShouldThrowExtensions.ShouldThrow<ArgumentOutOfRangeException>(() => { var sut = new EveryNthYearOnSpecifiedDayAndMonthStrategy(0); }); } [Test] public void ShouldThrowWhenMonthGreaterThan12Test() { Shouldly.ShouldThrowExtensions.ShouldThrow<ArgumentOutOfRangeException>(() => { var sut = new EveryNthYearOnSpecifiedDayAndMonthStrategy(13); }); } [Test] public void ShouldThrowWhenDayLessThan1Test() { Shouldly.ShouldThrowExtensions.ShouldThrow<ArgumentOutOfRangeException>(() => { var sut = new EveryNthYearOnSpecifiedDayAndMonthStrategy(day: 0); }); } [Test] public void ShouldThrowWhenDayGreaterThan31Test() { Shouldly.ShouldThrowExtensions.ShouldThrow<ArgumentOutOfRangeException>(() => { var sut = new EveryNthYearOnSpecifiedDayAndMonthStrategy(day: 32); }); } [Test] public void ShouldThrowWhenNLessThan1Test() { Shouldly.ShouldThrowExtensions.ShouldThrow<ArgumentOutOfRangeException>(() => { var sut = new EveryNthYearOnSpecifiedDayAndMonthStrategy(n: 0); }); } [TestCase(2, 30)] [TestCase(2, 31)] public void ShouldThrowWhenInvalidDateInFebruaryTest(int month, int day) { Shouldly.ShouldThrowExtensions.ShouldThrow<ArgumentOutOfRangeException>(() => { var sut = new EveryNthYearOnSpecifiedDayAndMonthStrategy(month, day); }); } public void ShouldNotThrowWhenFebruary29Test() { Shouldly.ShouldThrowExtensions.ShouldNotThrow(() => { var sut = new EveryNthYearOnSpecifiedDayAndMonthStrategy(2, 29); }); } [TestCase(9)] [TestCase(4)] [TestCase(6)] [TestCase(11)] public void ShouldThrowWhenInvalidDateInMonthsWithOnly30DaysTest(int month) { Shouldly.ShouldThrowExtensions.ShouldThrow<ArgumentOutOfRangeException>(() => { var sut = new EveryNthYearOnSpecifiedDayAndMonthStrategy(month, 31); }); } #endregion #region First date tests [Test] public void StartsSameDayTest() { var startDate = new DateTime(2016, 03, 03); Factory.CreateController(startDate, "Y3,3") .First() .ShouldBe(startDate, "should be March 3, 2016"); } [Test] public void StartsEarlierInYearTest() { var startDate = new DateTime(2016, 03, 03); Factory.CreateController(startDate, "Y11,11") .First() .ShouldBe(new DateTime(2016, 11, 11), "should be November 11, 2016"); } [Test] public void StartsLaterInYearTest() { var startDate = new DateTime(2016, 03, 03); Factory.CreateController(startDate, "Y1,1") .First() .ShouldBe(new DateTime(2017, 01, 01), "should be January 1, 2017"); } #endregion #region Nth year tests [Test] public void October6EveryYearTest() { var startDate = new DateTime(2016, 03, 03); var sut = Factory.CreateController(startDate, "Y10,6") .Take(3).ToList(); sut[0].ShouldBe(new DateTime(2016, 10, 06), "should be October 6, 2016"); sut[1].ShouldBe(new DateTime(2017, 10, 06), "should be October 6, 2017"); sut[2].ShouldBe(new DateTime(2018, 10, 06), "should be October 6, 2018"); } [Test] public void October6EveryTwoYearsTest() { var startDate = new DateTime(2016, 03, 03); var sut = Factory.CreateController(startDate, "Y10,6,2") .Take(3).ToList(); sut[0].ShouldBe(new DateTime(2016, 10, 06), "should be October 6, 2016"); sut[1].ShouldBe(new DateTime(2018, 10, 06), "should be October 6, 2018"); sut[2].ShouldBe(new DateTime(2020, 10, 06), "should be October 6, 2020"); } [Test] public void October6EveryThreeYearsTest() { var startDate = new DateTime(2016, 03, 03); var sut = Factory.CreateController(startDate, "Y10,6,3") .Take(3).ToList(); sut[0].ShouldBe(new DateTime(2016, 10, 06), "should be October 6, 2016"); sut[1].ShouldBe(new DateTime(2019, 10, 06), "should be October 6, 2019"); sut[2].ShouldBe(new DateTime(2022, 10, 06), "should be October 6, 2022"); } #endregion #region Date not available every year tests (Feb 29 tests) [Test] public void EveryFebruary29EveryYearTest() { var startDate = new DateTime(2016, 03, 03); var sut = Factory.CreateController(startDate, "Y2,29,1") .Take(3).ToList(); sut[0].ShouldBe(new DateTime(2020, 02, 29), "should be February 29, 2020"); sut[1].ShouldBe(new DateTime(2024, 02, 29), "should be February 29, 2024"); sut[2].ShouldBe(new DateTime(2028, 02, 29), "should be February 29, 2028"); } [Test] public void EveryFebruary29EverySecondYearTest() { var startDate = new DateTime(2016, 03, 03); var sut = Factory.CreateController(startDate, "Y2,29,2") .Take(3).ToList(); sut[0].ShouldBe(new DateTime(2020, 02, 29), "should be February 29, 2020"); sut[1].ShouldBe(new DateTime(2024, 02, 29), "should be February 29, 2024"); sut[2].ShouldBe(new DateTime(2028, 02, 29), "should be February 29, 2028"); } [Test] public void EveryFebruary29EveryThirdYearTest() { var startDate = new DateTime(2016, 03, 03); var sut = Factory.CreateController(startDate, "Y2,29,3") .Take(3).ToList(); sut[0].ShouldBe(new DateTime(2020, 02, 29), "should be February 29, 2020"); sut[1].ShouldBe(new DateTime(2032, 02, 29), "should be February 29, 2032"); sut[2].ShouldBe(new DateTime(2044, 02, 29), "should be February 29, 2044"); } [Test] public void Skips100YearsNot1000YearsFebruary29Test() { var startDate = new DateTime(2196, 01, 01); var sut = Factory.CreateController(startDate, "Y2,29") .Take(2).ToList(); sut[0].ShouldBe(new DateTime(2196, 02, 29), "should be February 29, 2196"); sut[1].ShouldBe(new DateTime(2204, 02, 29), "should be February 29, 2204"); } #endregion } }
using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using System.IO; using OpenFTTH.DesktopBridge.GeographicalAreaUpdated; namespace OpenFTTH.DesktopBridge.Bridge; public class DesktopBridgeHost : IHostedService { private readonly ILogger<DesktopBridgeHost> _logger; private readonly IHostApplicationLifetime _applicationLifetime; private readonly IBridgeServer _bridgeServer; private readonly IGeographicalAreaUpdatedConsumer _geographicalAreaUpdatedConsumer; public DesktopBridgeHost( ILogger<DesktopBridgeHost> logger, IHostApplicationLifetime applicationLifetime, IBridgeServer bridgeServer, IGeographicalAreaUpdatedConsumer geographicalAreaUpdatedConsumer) { _logger = logger; _applicationLifetime = applicationLifetime; _bridgeServer = bridgeServer; _geographicalAreaUpdatedConsumer = geographicalAreaUpdatedConsumer; } public Task StartAsync(CancellationToken cancellationToken) { _logger.LogInformation($"Starting {nameof(DesktopBridgeHost)}"); _applicationLifetime.ApplicationStarted.Register(OnStarted); _applicationLifetime.ApplicationStopping.Register(OnStopped); MarkAsReady(); return Task.CompletedTask; } public Task StopAsync(CancellationToken cancellationToken) { _logger.LogInformation($"Stopping {nameof(BridgeServer)}..."); _bridgeServer.Stop(); return Task.CompletedTask; } private void MarkAsReady() { File.Create("/tmp/healthy"); } private void OnStarted() { _logger.LogInformation($"Starting {nameof(BridgeServer)}"); _bridgeServer.Start(); _geographicalAreaUpdatedConsumer.Consume(); } private void OnStopped() { _geographicalAreaUpdatedConsumer.Dispose(); _bridgeServer.Dispose(); _logger.LogInformation("Stopped"); } }
using GestaoContratos.Teste.Util; using GestaoContratos.Util; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; namespace GestaoContratos.Teste { [TestClass] public class Inicializacao { [AssemblyInitialize] public static void IniciarAplicacao(TestContext context) { if (Configuracao.TipoTesteIntegracao == "banco") { UtilBancoDados.CriarBanco(); InjetorDependencias.InjetorDependencias.Iniciar(); } else if (Configuracao.TipoTesteIntegracao == "mock") { InjetorDependencias.InjetorDependencias.IniciarMock(); } else { throw new Exception("tipoTesteIntegracao invalido"); } } } }
 namespace XML_Processing_in.NET { using System; using System.Xml; public class DOMParser { static void Main() { var doc = new XmlDocument(); doc.Load("../../catalog.xml"); var root = doc.DocumentElement; Console.WriteLine(root); } } }
/** Game.Audio */ namespace Game.Audio { /** Se */ public sealed class Se : System.IDisposable { /** audio_se_gameobject */ private UnityEngine.GameObject se_gameobject; /** audiosource_list */ private UnityEngine.AudioSource[] audiosource_list; /** volume */ public float volume; public int volume_index; public float[] volume_list; /** execute */ public Execute.AudioExecute execute; /** constructor */ public Se(UnityEngine.AudioClip[] a_audioclip_list,float a_volume,Execute.AudioExecute a_execute) { //execute this.execute = a_execute; this.se_gameobject = new UnityEngine.GameObject("se"); UnityEngine.GameObject.DontDestroyOnLoad(this.se_gameobject); this.audiosource_list = new UnityEngine.AudioSource[a_audioclip_list.Length]; for(int ii=0;ii<this.audiosource_list.Length;ii++){ this.audiosource_list[ii] = this.se_gameobject.AddComponent<UnityEngine.AudioSource>(); this.audiosource_list[ii].clip = a_audioclip_list[ii]; } //volume this.volume = a_volume; //volume_index this.volume_index = 0; //volume_list this.volume_list = new float[]{ 0.0f, 0.1f, 0.2f, 0.5f, 1.0f, }; } /** SetVolumeIndex */ public void SetVolumeIndex(int a_volume_index) { this.volume_index = UnityEngine.Mathf.Clamp(a_volume_index,0,this.volume_list.Length - 1); this.volume = this.volume_list[this.volume_index]; } /** [IDisposable.Dispose] */ public void Dispose() { for(int ii=0;ii<this.audiosource_list.Length;ii++){ if(this.audiosource_list[ii] != null){ this.audiosource_list[ii].Stop(); this.audiosource_list[ii] = null; } } this.audiosource_list = null; if(this.se_gameobject != null){ UnityEngine.GameObject.Destroy(this.se_gameobject); this.se_gameobject = null; } } /** PlayOnce */ public void PlayOnce(int a_index,float a_volume) { this.audiosource_list[a_index].PlayOneShot(this.audiosource_list[a_index].clip,this.volume * a_volume); } } }
namespace Ofl.Slack.WebApi { public class Response { public bool Ok { get; set; } public string? Error { get; set; } public string? Warning { get; set; } } }
namespace DateTimeExtensions.Tests { using System; using System.Linq; using DateTimeExtensions.WorkingDays; using NUnit.Framework; [TestFixture] public class NLHolidaysTests { private readonly WorkingDayCultureInfo dateTimeCulture = new WorkingDayCultureInfo("nl-NL"); [Test] public void The_Netherlands_has_11_main_holidays() { var holidays = dateTimeCulture.Holidays; Assert.AreEqual(11, holidays.Count()); } [Test] public void Kingsday_is_a_national_holiday_since_1885() { Assert.That(Kingsday(1885).IsHoliday(dateTimeCulture)); } [Test] public void Kingsday_is_a_national_holiday_in_1949() { Assert.That(Kingsday(1949).IsHoliday(dateTimeCulture)); } [Test] public void Kingsday_is_a_national_holiday_in_2014() { Assert.That(Kingsday(2014).IsHoliday(dateTimeCulture)); } [Test] public void Liberation_Day_is_a_national_holiday_in_2005() { // Liberation_Day_is_a_national_holiday_once_every_5_years Assert.That(LiberationDay(2005).IsHoliday(dateTimeCulture)); } [Test] public void Liberation_Day_is_a_regular_day_in_2006() { // Liberation_Day_is_a_national_holiday_once_every_5_years Assert.That(LiberationDay(2006).IsWorkingDay(dateTimeCulture)); } private static DateTime Kingsday(int year) { if (year >= 2014) { return new DateTime(year, 4, 27); } if (year >= 1949) { return new DateTime(year, 4, 30); } if (year >= 1885) { return new DateTime(year, 8, 31); } throw new ArgumentException("No kingsday before 1885."); } private static DateTime LiberationDay(int year) { var liberationDay = new DateTime(year, 5, 5); return liberationDay; } } }
using Fortnox.SDK.Serialization; using Newtonsoft.Json; using System; using System.Collections.Generic; namespace Fortnox.SDK.Entities { [Entity(SingularName = "Offer", PluralName = "Offers")] public class Offer { ///<summary> Direct url to the record and URL to Taxreduction for the offer (URL to Taxreduction shows even if – Taxreduction is connected to offer) </summary> [ReadOnly] [JsonProperty("@url")] public Uri Url { get; private set; } ///<summary> Administration fee </summary> [JsonProperty] public decimal? AdministrationFee { get; set; } ///<summary> VAT of the administration fee </summary> [ReadOnly] [JsonProperty] public decimal? AdministrationFeeVAT { get; private set; } ///<summary> Address 1 </summary> [JsonProperty] public string Address1 { get; set; } ///<summary> Address 2 </summary> [JsonProperty] public string Address2 { get; set; } ///<summary> The amount that Taxreduction is based on </summary> [ReadOnly] [JsonProperty] public decimal? BasisTaxReduction { get; private set; } ///<summary> If the offer is cancelled </summary> [ReadOnly] [JsonProperty] public bool? Cancelled { get; private set; } ///<summary> City </summary> [JsonProperty] public string City { get; set; } ///<summary> Comments </summary> [JsonProperty] public string Comments { get; set; } ///<summary> Contribution in Percent </summary> [ReadOnly] [JsonProperty] public decimal? ContributionPercent { get; private set; } ///<summary> Contribution in amount </summary> [ReadOnly] [JsonProperty] public decimal? ContributionValue { get; private set; } ///<summary> Remarks will be copied from offer to order </summary> [JsonProperty] public bool? CopyRemarks { get; set; } ///<summary> Country </summary> [JsonProperty] public string Country { get; set; } ///<summary> Cost center </summary> [JsonProperty] public string CostCenter { get; set; } ///<summary> Currency </summary> [JsonProperty] public string Currency { get; set; } ///<summary> Currency rate </summary> [JsonProperty] public decimal? CurrencyRate { get; set; } ///<summary> Currency unit </summary> [JsonProperty] public decimal? CurrencyUnit { get; set; } ///<summary> Customer name </summary> [JsonProperty] public string CustomerName { get; set; } ///<summary> Customer number </summary> [JsonProperty] public string CustomerNumber { get; set; } ///<summary> Delivery address 1 </summary> [JsonProperty] public string DeliveryAddress1 { get; set; } ///<summary> Delivery address 2 </summary> [JsonProperty] public string DeliveryAddress2 { get; set; } ///<summary> Delivery City </summary> [JsonProperty] public string DeliveryCity { get; set; } ///<summary> Delivery Country </summary> [JsonProperty] public string DeliveryCountry { get; set; } ///<summary> Delivery date </summary> [JsonProperty] public DateTime? DeliveryDate { get; set; } ///<summary> Delivery name </summary> [JsonProperty] public string DeliveryName { get; set; } ///<summary> Delivery zipcode </summary> [JsonProperty] public string DeliveryZipCode { get; set; } ///<summary> Document Number </summary> [JsonProperty] public long? DocumentNumber { get; set; } ///<summary> – </summary> [JsonProperty] public EmailInformation EmailInformation { get; set; } ///<summary> Expire date </summary> [JsonProperty] public DateTime? ExpireDate { get; set; } ///<summary> Freight </summary> [JsonProperty] public decimal? Freight { get; set; } ///<summary> VAT of the freight </summary> [ReadOnly] [JsonProperty] public decimal? FreightVAT { get; private set; } ///<summary> Gross value of the offer </summary> [ReadOnly] [JsonProperty] public decimal? Gross { get; private set; } ///<summary> If offer is marked with housework </summary> [ReadOnly] [JsonProperty] public bool? HouseWork { get; private set; } ///<summary> Net amount </summary> [ReadOnly] [JsonProperty] public decimal? Net { get; private set; } ///<summary> If the offer is marked Completed (this mark stops the offer from being cancelled or that a user can create an order from the offer ) </summary> [JsonProperty] public bool? Completed { get; set; } ///<summary> Date of order </summary> [JsonProperty] public DateTime? OfferDate { get; set; } ///<summary> Reference to order </summary> [ReadOnly] [JsonProperty] public long? OrderReference { get; private set; } ///<summary> Organisation number </summary> [JsonProperty] public string OrganisationNumber { get; set; } ///<summary> Our reference </summary> [JsonProperty] public string OurReference { get; set; } ///<summary> Phone 1 </summary> [JsonProperty] public string Phone1 { get; set; } ///<summary> Phone 2 </summary> [JsonProperty] public string Phone2 { get; set; } ///<summary> Pricelist code </summary> [JsonProperty] public string PriceList { get; set; } ///<summary> Print document template </summary> [JsonProperty] public string PrintTemplate { get; set; } ///<summary> Project code </summary> [JsonProperty] public string Project { get; set; } ///<summary> Remarks on offer </summary> [JsonProperty] public string Remarks { get; set; } ///<summary> Round off amount </summary> [ReadOnly] [JsonProperty] public decimal? RoundOff { get; private set; } ///<summary> – </summary> [JsonProperty] public IList<OfferRow> OfferRows { get; set; } ///<summary> If document is printed or e-mailed to customer </summary> [ReadOnly] [JsonProperty] public bool? Sent { get; private set; } ///<summary> Amount of Taxreduction </summary> [ReadOnly] [JsonProperty] public decimal? TaxReduction { get; private set; } /// <summary> Tax Reduction Type </summary> [JsonProperty] public TaxReductionType? TaxReductionType { get; set; } ///<summary> Terms of delivery code </summary> [JsonProperty] public string TermsOfDelivery { get; set; } ///<summary> Terms of payment code </summary> [JsonProperty] public string TermsOfPayment { get; set; } ///<summary> Total amount </summary> [ReadOnly] [JsonProperty] public decimal? Total { get; private set; } ///<summary> Total vat amount </summary> [ReadOnly] [JsonProperty] public decimal? TotalVAT { get; private set; } ///<summary> If offer row price exclude or include vat </summary> [JsonProperty] public bool? VATIncluded { get; set; } ///<summary> Code of delivery </summary> [JsonProperty] public string WayOfDelivery { get; set; } ///<summary> Customer reference </summary> [JsonProperty] public string YourReference { get; set; } ///<summary> ReferenceNumber </summary> [JsonProperty] public string YourReferenceNumber { get; set; } ///<summary> Zip code </summary> [JsonProperty] public string ZipCode { get; set; } } }
using System; namespace CienciaArgentina.Microservices.Storage.Azure.QueueStorage.Messages { [Serializable()] public class AppException { public DateTime? Date { get; set; } public string IdFront { get; set; } public string Message { get; set; } public string Detail { get; set; } public string CustomMessage { get; set; } public string Url { get; set; } public string UrlReferrer { get; set; } public string Source { get; set; } } }
using System; using System.Threading.Tasks; namespace Spawn.Demo.Store { public abstract class StoreRetrier { private readonly int connection_retries = 10; private readonly int wait_between_connections = 2000; protected async Task<T> RunWithRetryAsync<T>(Func<T> func) { for (var i = 0; i < connection_retries; i++) { if (CanConnect()) { return func(); } Console.WriteLine( $"Unable to connect to database, waiting {wait_between_connections}ms before retrying..."); await Task.Delay(wait_between_connections); } throw new TimeoutException($"Unable to connect to database after {connection_retries} attempts"); } protected async Task RunWithRetryAsync(Action action) { Func<int> func = () => { action(); return 0; }; await RunWithRetryAsync(() => func()); } protected abstract bool CanConnect(); } }
using ControleContas.Application.Interfaces; using ControleContas.Application.ViewModels; using Microsoft.AspNetCore.Mvc; using System; using System.Threading.Tasks; namespace MVCWebApp.Controllers { public class ContasTiposController : Controller { private readonly IContasTiposService _contastiposService; public ContasTiposController(IContasTiposService contastiposService) { _contastiposService = contastiposService; } [HttpGet] public async Task<IActionResult> Index() { var result = await _contastiposService.GetAll(); return View(result); } [HttpGet] public IActionResult Cadastrar() { return View(); } [HttpPost] [ValidateAntiForgeryToken] public IActionResult Cadastrar([Bind("Id,Nome")] ContasTiposViewModel contastipos) { if (ModelState.IsValid) { try { _contastiposService.Add(contastipos); } catch (Exception) { throw; } return RedirectToAction(nameof(Index)); } return View(contastipos); } [HttpGet] public async Task<IActionResult> Detalhes(int? id) { if (id == null) return NotFound(); var contastipos = await _contastiposService.GetById(id); if (contastipos == null) return NotFound(); return View(contastipos); } [HttpGet] public async Task<IActionResult> Editar(int? id) { if (id == null) return NotFound(); var contastipos = await _contastiposService.GetById(id); if (contastipos == null) return NotFound(); return View(contastipos); } [HttpPost] [ValidateAntiForgeryToken] public IActionResult Editar([Bind("Id,Nome")] ContasTiposViewModel contatipos) { if (ModelState.IsValid) { try { _contastiposService.Update(contatipos); } catch (Exception) { throw; } return RedirectToAction(nameof(Index)); } return View(contatipos); } [HttpGet] public async Task<IActionResult> Excluir(int? id) { if (id == null) return NotFound(); var contastipos = await _contastiposService.GetById(id); if (contastipos == null) return NotFound(); return View(contastipos); } [HttpPost] [ValidateAntiForgeryToken] public IActionResult Excluir([Bind("Id,Nome")] ContasTiposViewModel contatipos) { _contastiposService.Remove(contatipos.Id); return RedirectToAction(nameof(Index)); } } }
namespace ConsoleWebServer.Framework.Handlers { using System; using System.IO; using System.Net; public class StaticFileHandler { public bool CanHandle(IHttpRequest request) { return request.Uri.LastIndexOf(".", StringComparison.Ordinal) > request.Uri.LastIndexOf("/", StringComparison.Ordinal); } public HttpResponse Handle(IHttpRequest request) { var filePath = Environment.CurrentDirectory + "/" + request.Uri; if (!File.Exists(filePath)) { return new HttpResponse(request.ProtocolVersion, HttpStatusCode.NotFound, "File not found!"); } var fileContents = File.ReadAllText(filePath); var response = new HttpResponse(request.ProtocolVersion, HttpStatusCode.OK, fileContents); return response; } } }
namespace TicTacToe.Web.DataModels { using System; using AutoMapper; using Mapping; using TicTacToe.Models; public class UserDataModel : IMappableFrom<User>, IHaveCustomMappings { public string Username { get; set; } public DateTime DateRegistration { get; set; } public void CreateMappings(IConfiguration configuration) { configuration.CreateMap<User, UserDataModel>() .ForMember(m => m.Username, opt => opt.MapFrom(user => user.UserName)) .ForMember(m => m.DateRegistration, opt => opt.MapFrom(user => user.DateRegistration)); } } }
using System; using System.Collections.Generic; using System.Text; namespace FileTransfer.Model { public enum SocketMessageType { Heart = 1, Request = 2, BigData = 3, Allow = 5, Refuse = 6, } }
namespace GrocerySupplyManagementApp.Entities { public class POSDetail { public long Id { get; set; } public string EndOfDay { get; set; } public long UserTransactionId { get; set; } public string InvoiceNo { get; set; } public decimal SubTotal { get; set; } public decimal DiscountPercent { get; set; } public decimal Discount { get; set; } public decimal VatPercent { get; set; } public decimal Vat { get; set; } public decimal DeliveryChargePercent { get; set; } public decimal DeliveryCharge { get; set; } public string DeliveryPersonId { get; set; } } }
using UnityEngine; public interface Interface1 { string name { get; set; } } public interface Interface2 { int select { get; set; } } public class SomeClass { public static void Foo(Interface1 data) { Debug.Log(string.Format("SomeClass.Foo, got name: {0}", data.name)); data.name = "Foo"; } }
using HelpMyStreet.Utils.Models; using HelpMyStreetFE.Models.RequestHelp.Enum; using Microsoft.AspNetCore.Mvc; using System; namespace HelpMyStreetFE.Models.Registration { public class StepTwoFormModel { [BindProperty(Name = "first_name")] public string FirstName { get; set; } [BindProperty(Name = "last_name")] public string LastName { get; set; } [BindProperty(Name = "address_line_1")] public string AddressLine1 { get; set; } [BindProperty(Name = "address_line_2")] public string AddressLine2 { get; set; } [BindProperty(Name = "city")] public string City { get; set; } [BindProperty(Name = "county")] public string County { get; set; } [BindProperty(Name = "postcode")] public string Postcode { get; set; } [BindProperty(Name = "mobile_number")] public string MobilePhone { get; set; } [BindProperty(Name = "alt_number")] public string OtherPhone { get; set; } [BindProperty(Name = "dob")] public DateTime DateOfBirth { get; set; } } }
using Sockets.Core.Conversion; using System; using System.IO; using System.Text; namespace Sockets.Core.IO { /// <summary> /// Equivalent of System.IO.BinaryWriter, but with either endianness, depending on /// the EndianBitConverter it is constructed with. /// </summary> public class EndianBinaryWriter : IDisposable { #region Fields not directly related to properties /// <summary> /// Whether or not this writer has been disposed yet. /// </summary> bool disposed = false; /// <summary> /// Buffer used for temporary storage during conversion from primitives /// </summary> byte[] buffer = new byte[16]; /// <summary> /// Buffer used for Write(char) /// </summary> char[] charBuffer = new char[1]; #endregion #region Constructors /// <summary> /// Constructs a new binary writer with the given bit converter, writing /// to the given stream, using UTF-8 encoding. /// </summary> /// <param name="bitConverter">Converter to use when writing data</param> /// <param name="stream">Stream to write data to</param> public EndianBinaryWriter(EndianBitConverter bitConverter, Stream stream) : this(bitConverter, stream, Encoding.UTF8) { } /// <summary> /// Constructs a new binary writer with the given bit converter, writing /// to the given stream, using the given encoding. /// </summary> /// <param name="bitConverter">Converter to use when writing data</param> /// <param name="stream">Stream to write data to</param> /// <param name="encoding">Encoding to use when writing character data</param> public EndianBinaryWriter(EndianBitConverter bitConverter, Stream stream, Encoding encoding) { if (bitConverter == null) { throw new ArgumentNullException("bitConverter"); } if (stream == null) { throw new ArgumentNullException("stream"); } if (encoding == null) { throw new ArgumentNullException("encoding"); } if (!stream.CanWrite) { throw new ArgumentException("Stream isn't writable", "stream"); } this.stream = stream; this.bitConverter = bitConverter; this.encoding = encoding; } #endregion #region Properties EndianBitConverter bitConverter; /// <summary> /// The bit converter used to write values to the stream /// </summary> public EndianBitConverter BitConverter { get { return bitConverter; } } Encoding encoding; /// <summary> /// The encoding used to write strings /// </summary> public Encoding Encoding { get { return encoding; } } Stream stream; /// <summary> /// Gets the underlying stream of the EndianBinaryWriter. /// </summary> public Stream BaseStream { get { return stream; } } #endregion #region Public methods /// <summary> /// Closes the writer, including the underlying stream. /// </summary> public void Close() { Dispose(); } /// <summary> /// Flushes the underlying stream. /// </summary> public void Flush() { CheckDisposed(); stream.Flush(); } /// <summary> /// Seeks within the stream. /// </summary> /// <param name="offset">Offset to seek to.</param> /// <param name="origin">Origin of seek operation.</param> public void Seek(int offset, SeekOrigin origin) { CheckDisposed(); stream.Seek(offset, origin); } /// <summary> /// Writes a boolean value to the stream. 1 byte is written. /// </summary> /// <param name="value">The value to write</param> public void Write(bool value) { bitConverter.CopyBytes(value, buffer, 0); WriteInternal(buffer, 1); } /// <summary> /// Writes a 16-bit signed integer to the stream, using the bit converter /// for this writer. 2 bytes are written. /// </summary> /// <param name="value">The value to write</param> public void Write(short value) { bitConverter.CopyBytes(value, buffer, 0); WriteInternal(buffer, 2); } /// <summary> /// Writes a 32-bit signed integer to the stream, using the bit converter /// for this writer. 4 bytes are written. /// </summary> /// <param name="value">The value to write</param> public void Write(int value) { bitConverter.CopyBytes(value, buffer, 0); WriteInternal(buffer, 4); } /// <summary> /// Writes a 64-bit signed integer to the stream, using the bit converter /// for this writer. 8 bytes are written. /// </summary> /// <param name="value">The value to write</param> public void Write(long value) { bitConverter.CopyBytes(value, buffer, 0); WriteInternal(buffer, 8); } /// <summary> /// Writes a 16-bit unsigned integer to the stream, using the bit converter /// for this writer. 2 bytes are written. /// </summary> /// <param name="value">The value to write</param> public void Write(ushort value) { bitConverter.CopyBytes(value, buffer, 0); WriteInternal(buffer, 2); } /// <summary> /// Writes a 32-bit unsigned integer to the stream, using the bit converter /// for this writer. 4 bytes are written. /// </summary> /// <param name="value">The value to write</param> public void Write(uint value) { bitConverter.CopyBytes(value, buffer, 0); WriteInternal(buffer, 4); } /// <summary> /// Writes a 64-bit unsigned integer to the stream, using the bit converter /// for this writer. 8 bytes are written. /// </summary> /// <param name="value">The value to write</param> public void Write(ulong value) { bitConverter.CopyBytes(value, buffer, 0); WriteInternal(buffer, 8); } /// <summary> /// Writes a single-precision floating-point value to the stream, using the bit converter /// for this writer. 4 bytes are written. /// </summary> /// <param name="value">The value to write</param> public void Write(float value) { bitConverter.CopyBytes(value, buffer, 0); WriteInternal(buffer, 4); } /// <summary> /// Writes a double-precision floating-point value to the stream, using the bit converter /// for this writer. 8 bytes are written. /// </summary> /// <param name="value">The value to write</param> public void Write(double value) { bitConverter.CopyBytes(value, buffer, 0); WriteInternal(buffer, 8); } /// <summary> /// Writes a decimal value to the stream, using the bit converter for this writer. /// 16 bytes are written. /// </summary> /// <param name="value">The value to write</param> public void Write(decimal value) { bitConverter.CopyBytes(value, buffer, 0); WriteInternal(buffer, 16); } /// <summary> /// Writes a signed byte to the stream. /// </summary> /// <param name="value">The value to write</param> public void Write(byte value) { buffer[0] = value; WriteInternal(buffer, 1); } /// <summary> /// Writes an unsigned byte to the stream. /// </summary> /// <param name="value">The value to write</param> public void Write(sbyte value) { buffer[0] = unchecked((byte)value); WriteInternal(buffer, 1); } /// <summary> /// Writes an array of bytes to the stream. /// </summary> /// <param name="value">The values to write</param> public void Write(byte[] value) { if (value == null) { throw (new System.ArgumentNullException("value")); } WriteInternal(value, value.Length); } /// <summary> /// Writes a portion of an array of bytes to the stream. /// </summary> /// <param name="value">An array containing the bytes to write</param> /// <param name="offset">The index of the first byte to write within the array</param> /// <param name="count">The number of bytes to write</param> public void Write(byte[] value, int offset, int count) { CheckDisposed(); stream.Write(value, offset, count); } /// <summary> /// Writes a single character to the stream, using the encoding for this writer. /// </summary> /// <param name="value">The value to write</param> public void Write(char value) { charBuffer[0] = value; Write(charBuffer); } /// <summary> /// Writes an array of characters to the stream, using the encoding for this writer. /// </summary> /// <param name="value">An array containing the characters to write</param> public void Write(char[] value) { if (value == null) { throw new ArgumentNullException("value"); } CheckDisposed(); byte[] data = Encoding.GetBytes(value, 0, value.Length); WriteInternal(data, data.Length); } /// <summary> /// Writes a string to the stream, using the encoding for this writer. /// </summary> /// <param name="value">The value to write. Must not be null.</param> /// <exception cref="ArgumentNullException">value is null</exception> public void Write(string value) { if (value == null) { throw new ArgumentNullException("value"); } CheckDisposed(); byte[] data = Encoding.GetBytes(value); Write7BitEncodedInt(data.Length); WriteInternal(data, data.Length); } /// <summary> /// Writes a 7-bit encoded integer from the stream. This is stored with the least significant /// information first, with 7 bits of information per byte of value, and the top /// bit as a continuation flag. /// </summary> /// <param name="value">The 7-bit encoded integer to write to the stream</param> public void Write7BitEncodedInt(int value) { CheckDisposed(); if (value < 0) { throw new ArgumentOutOfRangeException("value", "Value must be greater than or equal to 0."); } int index = 0; while (value >= 128) { buffer[index++] = (byte)((value & 0x7f) | 0x80); value = value >> 7; index++; } buffer[index++] = (byte)value; stream.Write(buffer, 0, index); } #endregion #region Private methods /// <summary> /// Checks whether or not the writer has been disposed, throwing an exception if so. /// </summary> void CheckDisposed() { if (disposed) { throw new ObjectDisposedException("EndianBinaryWriter"); } } /// <summary> /// Writes the specified number of bytes from the start of the given byte array, /// after checking whether or not the writer has been disposed. /// </summary> /// <param name="bytes">The array of bytes to write from</param> /// <param name="length">The number of bytes to write</param> void WriteInternal(byte[] bytes, int length) { CheckDisposed(); stream.Write(bytes, 0, length); } #endregion #region IDisposable Members /// <summary> /// Disposes of the underlying stream. /// </summary> public void Dispose() { if (!disposed) { Flush(); disposed = true; ((IDisposable)stream).Dispose(); } } #endregion } }
using System; using System.Collections.Generic; using Newtonsoft.Json; using UnityEngine.Scripting; namespace Siccity.GLTFUtility { // https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#scene [Preserve] public class GLTFScene { /// <summary> Indices of nodes </summary> public List<int> nodes; public string name; } }
using System; using System.Configuration; namespace SimpleLogs.Simple { public class LogLevelHelper { public static Lazy<LogLevel> LogLevelLazy = new Lazy<LogLevel>(TryReadFromConfig); public static bool IsLevelEnabled(LogLevel current) { return current >= LogLevelLazy.Value; } public static string Common_Logs_SimpleLogLevel = "Common.Logs.SimpleLogLevel"; private static LogLevel TryReadFromConfig() { var appSetting = ConfigurationManager.AppSettings[Common_Logs_SimpleLogLevel]; if (!string.IsNullOrWhiteSpace(appSetting)) { LogLevel result; var tryParse = LogLevel.TryParse(appSetting, true, out result); if (tryParse) { return result; } } return LogLevel.All; } } public enum LogLevel { All = 0, Debug = 1, Info = 2, Warn = 3, Error = 4, Fatal = 5 } }
using System; using System.Drawing; using System.Runtime.InteropServices; namespace Calibration.Controllers { public class ClickControll { [DllImport("user32.dll", EntryPoint = "SetCursorPos")] private static extern bool SetCursorPos(int X, int Y); [DllImport("user32.dll")] public static extern void mouse_event(int dwFlags, int dx, int dy, int cButtons, int dwExtraInfo); private const int MOUSEEVENTF_LEFTDOWN = 0x02; private const int MOUSEEVENTF_LEFTUP = 0x04; private const int MOUSEEVENTF_RIGHTDOWN = 0x08; private const int MOUSEEVENTF_RIGHTUP = 0x10; public static void LeftClick(int x, int y) { mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, x, y,0, 0); } public static void RightClick(int x, int y) { mouse_event(MOUSEEVENTF_RIGHTDOWN| MOUSEEVENTF_RIGHTUP, x, y, 0, 0); } } }
namespace destiny_chat_client.Repositories.Interfaces { /// <summary> /// An interface to accessing and playing sounds. /// </summary> public interface ISoundRepository { /// <summary> /// Play the sound that would signify a notification. /// </summary> void PlayNotificationSound(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Consultas_medicas.Models { //Essa classe deve conter os mesmos atributos da tabela do banco de dados , junto com get e set public class Funcionarios { public int codFuncionario { get; set; } public string nomeFuncionario { get; set; } public string emailFuncionario { get; set; } public Int64 telefoneFixoFunc { get; set; } public Int64 telefoneCelularFunc { get; set; } public string cidadeFuncionario { get; set; } public string estadoFuncionario { get; set; } public string enderecoFuncionario { get; set; } public string bairroFuncionario { get; set; } public string cepFuncionario { get; set; } public int numeroResidenciaFuncionario { get; set; } public string complementoFuncionario { get; set; } } }
namespace FootballAnalyzes.Services { using System.Collections.Generic; using FootballAnalyzes.Services.Models.Prediction; public interface IPredictionService { IEnumerable<AllListingSM> All(); PredictGamesSM PredictGames(string name); } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; namespace DigitalMenu.Models { public class Category { public Category() { this.Items = new HashSet<Item>(); } public int Id { get; set; } [Required] [StringLength(70)] [Display(Name = "Category Name")] public string CategoryName { get; set; } [Required] [StringLength(100)] [Display(Name = "Category Description")] public string CategoryDescription { get; set; } public short Rank { get; set; } [Display(Name = "Special Text")] public string SpecialText { get; set; } public virtual ICollection<Item> Items { get; set; } public string MemberId { get; set; } //[Display(Name = "Is Active")] //public bool IsActive { get; set; } } }
namespace Telnyx { /// <summary> /// Interface that identifies entities returned by Telnyx that have an `id` attribute. /// </summary> public interface IHasId { /// <summary> /// Gets or sets unique identifier for the object. /// </summary> string Id { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Click_Change_Position_SC : MonoBehaviour { public GameObject target; public Vector2 position0; //按下去的位置 public Vector2 position1; //拖到新的位置 public float horizon_dist; //兩點之間的水平距離 public float vertical_dist; //兩點之間的垂直距離 public bool isDragging; public bool first_position_Get; //是否已經決定抓到按下去的那點 // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { MousePosition(position0.x, position0.y); } public void MousePosition(float _mouseX, float _mouseY) { if (Input.GetMouseButtonDown(0)) { Vector3 v3; v3 = Camera.main.ScreenToViewportPoint(Input.mousePosition); target.transform.position = Input.mousePosition; Debug.Log(Input.mousePosition); Debug.Log(v3); // target.transform.position = new Vector3(v3.x,v3.y,0); // target.transform.position = v3; isDragging = true; } if (Input.GetMouseButtonUp(0)) { if (isDragging == true) { target.transform.position = new Vector3(0,0,0); } } } // private float _maxy; // public float max_y // { // get { return this.transform.position.y; } // set { // if (this.transform.position.y>=7) // { // _maxy = Mathf.Min(7, this.transform.position.y); // } // } // } }
namespace Elements.Services.Admin.Interfaces { using Elements.Models; using Elements.Services.Models.Areas.Admin.ViewModels; using System.Collections.Generic; public interface IManageUsersService { IEnumerable<AdministrateUserViewModel> GetAllUsersWithTopics(); IEnumerable<AdministrateUserViewModel> GetUsers(); AdministrateUserViewModel GetUserWithTopics(string userId); UserDetailsViewModel GetUserWithTopicsAndReplies(string userId); User RestrictUser(string id); User RestoreUser(string id); } }
using MediatR; namespace Taobao.Area.Api.Domain.Events { public class AnalysisJsCompletedEvent : INotification { } }
using System; using System.Collections.Generic; namespace IServiceCollectionExtension.LazyLoadService.Test.TestClasses { internal class StepChecker { private readonly List<string> _stepsPassed = new List<string>(); public void AddStep(string step) { _stepsPassed.Add(step); } public string[] PassedSteps => _stepsPassed.ToArray(); public void PrintPassedSteps() { foreach (var step in _stepsPassed) { Console.WriteLine(step); } } } }
using Microsoft.VisualStudio.TestTools.UnitTesting; using RepoDb.Resolvers; using RepoDb.Types; using System; namespace RepoDb.SqlServer.UnitTests.Resolvers { [TestClass] public class SqlServerTypeNameToClientTypeResolverTest { /* * Taken: * https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/sql-server-data-type-mappings */ private readonly SqlServerDbTypeNameToClientTypeResolver m_resolver = new(); [TestMethod] public void TestSqlServerTypeNameToClientTypeResolverForBigInt() { // Setup var dbTypeName = "bigint"; // Act var clientType = m_resolver.Resolve(dbTypeName); // Assert Assert.AreEqual(typeof(long), clientType); } [TestMethod] public void TestSqlServerTypeNameToClientTypeResolverForBinary() { // Setup var dbTypeName = "binary"; // Act var clientType = m_resolver.Resolve(dbTypeName); // Assert Assert.AreEqual(typeof(byte[]), clientType); } [TestMethod] public void TestSqlServerTypeNameToClientTypeResolverForBit() { // Setup var dbTypeName = "bit"; // Act var clientType = m_resolver.Resolve(dbTypeName); // Assert Assert.AreEqual(typeof(bool), clientType); } [TestMethod] public void TestSqlServerTypeNameToClientTypeResolverForChar() { // Setup var dbTypeName = "char"; // Act var clientType = m_resolver.Resolve(dbTypeName); // Assert Assert.AreEqual(typeof(string), clientType); } [TestMethod] public void TestSqlServerTypeNameToClientTypeResolverForDate() { // Setup var dbTypeName = "date"; // Act var clientType = m_resolver.Resolve(dbTypeName); // Assert Assert.AreEqual(typeof(DateTime), clientType); } [TestMethod] public void TestSqlServerTypeNameToClientTypeResolverForDateTime() { // Setup var dbTypeName = "datetime"; // Act var clientType = m_resolver.Resolve(dbTypeName); // Assert Assert.AreEqual(typeof(DateTime), clientType); } [TestMethod] public void TestSqlServerTypeNameToClientTypeResolverForDateTime2() { // Setup var dbTypeName = "datetime2"; // Act var clientType = m_resolver.Resolve(dbTypeName); // Assert Assert.AreEqual(typeof(DateTime), clientType); } [TestMethod] public void TestSqlServerTypeNameToClientTypeResolverForDateTimeOffset() { // Setup var dbTypeName = "datetimeoffset"; // Act var clientType = m_resolver.Resolve(dbTypeName); // Assert Assert.AreEqual(typeof(DateTimeOffset), clientType); } [TestMethod] public void TestSqlServerTypeNameToClientTypeResolverForDecimal() { // Setup var dbTypeName = "decimal"; // Act var clientType = m_resolver.Resolve(dbTypeName); // Assert Assert.AreEqual(typeof(Decimal), clientType); } [TestMethod] public void TestSqlServerTypeNameToClientTypeResolverForFileStream() { // Setup var dbTypeName = "filestream"; // Act var clientType = m_resolver.Resolve(dbTypeName); // Assert Assert.AreEqual(typeof(byte[]), clientType); } [TestMethod] public void TestSqlServerTypeNameToClientTypeResolverForAttribute() { // Setup var dbTypeName = "attribute"; // Act var clientType = m_resolver.Resolve(dbTypeName); // Assert Assert.AreEqual(typeof(byte[]), clientType); } [TestMethod] public void TestSqlServerTypeNameToClientTypeResolverForVarBinaryMax() { // Setup var dbTypeName = "varbinary(max)"; // Act var clientType = m_resolver.Resolve(dbTypeName); // Assert Assert.AreEqual(typeof(byte[]), clientType); } [TestMethod] public void TestSqlServerTypeNameToClientTypeResolverForFloat() { // Setup var dbTypeName = "float"; // Act var clientType = m_resolver.Resolve(dbTypeName); // Assert Assert.AreEqual(typeof(Double), clientType); } [TestMethod] public void TestSqlServerTypeNameToClientTypeResolverForImage() { // Setup var dbTypeName = "image"; // Act var clientType = m_resolver.Resolve(dbTypeName); // Assert Assert.AreEqual(typeof(byte[]), clientType); } [TestMethod] public void TestSqlServerTypeNameToClientTypeResolverForInt() { // Setup var dbTypeName = "int"; // Act var clientType = m_resolver.Resolve(dbTypeName); // Assert Assert.AreEqual(typeof(int), clientType); } [TestMethod] public void TestSqlServerTypeNameToClientTypeResolverForMoney() { // Setup var dbTypeName = "money"; // Act var clientType = m_resolver.Resolve(dbTypeName); // Assert Assert.AreEqual(typeof(decimal), clientType); } [TestMethod] public void TestSqlServerTypeNameToClientTypeResolverForNChar() { // Setup var dbTypeName = "nchar"; // Act var clientType = m_resolver.Resolve(dbTypeName); // Assert Assert.AreEqual(typeof(string), clientType); } [TestMethod] public void TestSqlServerTypeNameToClientTypeResolverForNText() { // Setup var dbTypeName = "ntext"; // Act var clientType = m_resolver.Resolve(dbTypeName); // Assert Assert.AreEqual(typeof(string), clientType); } [TestMethod] public void TestSqlServerTypeNameToClientTypeResolverForNumeric() { // Setup var dbTypeName = "numeric"; // Act var clientType = m_resolver.Resolve(dbTypeName); // Assert Assert.AreEqual(typeof(decimal), clientType); } [TestMethod] public void TestSqlServerTypeNameToClientTypeResolverForNVarChar() { // Setup var dbTypeName = "nvarchar"; // Act var clientType = m_resolver.Resolve(dbTypeName); // Assert Assert.AreEqual(typeof(string), clientType); } [TestMethod] public void TestSqlServerTypeNameToClientTypeResolverForReal() { // Setup var dbTypeName = "real"; // Act var clientType = m_resolver.Resolve(dbTypeName); // Assert Assert.AreEqual(typeof(float), clientType); } [TestMethod] public void TestSqlServerTypeNameToClientTypeResolverForRowVersion() { // Setup var dbTypeName = "rowversion"; // Act var clientType = m_resolver.Resolve(dbTypeName); // Assert Assert.AreEqual(typeof(byte[]), clientType); } [TestMethod] public void TestSqlServerTypeNameToClientTypeResolverForSmallDateTime() { // Setup var dbTypeName = "smalldatetime"; // Act var clientType = m_resolver.Resolve(dbTypeName); // Assert Assert.AreEqual(typeof(DateTime), clientType); } [TestMethod] public void TestSqlServerTypeNameToClientTypeResolverForSmallInt() { // Setup var dbTypeName = "smallint"; // Act var clientType = m_resolver.Resolve(dbTypeName); // Assert Assert.AreEqual(typeof(short), clientType); } [TestMethod] public void TestSqlServerTypeNameToClientTypeResolverForSmallMoney() { // Setup var dbTypeName = "smallmoney"; // Act var clientType = m_resolver.Resolve(dbTypeName); // Assert Assert.AreEqual(typeof(decimal), clientType); } [TestMethod] public void TestSqlServerTypeNameToClientTypeResolverForSqlVariant() { // Setup var dbTypeName = "sql_variant"; // Act var clientType = m_resolver.Resolve(dbTypeName); // Assert Assert.AreEqual(typeof(SqlVariant), clientType); } [TestMethod] public void TestSqlServerTypeNameToClientTypeResolverForText() { // Setup var dbTypeName = "text"; // Act var clientType = m_resolver.Resolve(dbTypeName); // Assert Assert.AreEqual(typeof(string), clientType); } [TestMethod] public void TestSqlServerTypeNameToClientTypeResolverForTime() { // Setup var dbTypeName = "time"; // Act var clientType = m_resolver.Resolve(dbTypeName); // Assert Assert.AreEqual(typeof(TimeSpan), clientType); } [TestMethod] public void TestSqlServerTypeNameToClientTypeResolverForTimestamp() { // Setup var dbTypeName = "timestamp"; // Act var clientType = m_resolver.Resolve(dbTypeName); // Assert Assert.AreEqual(typeof(byte[]), clientType); } [TestMethod] public void TestSqlServerTypeNameToClientTypeResolverForTinyInt() { // Setup var dbTypeName = "tinyint"; // Act var clientType = m_resolver.Resolve(dbTypeName); // Assert Assert.AreEqual(typeof(byte), clientType); } [TestMethod] public void TestSqlServerTypeNameToClientTypeResolverForUniqueIdentifier() { // Setup var dbTypeName = "uniqueidentifier"; // Act var clientType = m_resolver.Resolve(dbTypeName); // Assert Assert.AreEqual(typeof(Guid), clientType); } [TestMethod] public void TestSqlServerTypeNameToClientTypeResolverForVarBinary() { // Setup var dbTypeName = "varbinary"; // Act var clientType = m_resolver.Resolve(dbTypeName); // Assert Assert.AreEqual(typeof(byte[]), clientType); } [TestMethod] public void TestSqlServerTypeNameToClientTypeResolverForVarChar() { // Setup var dbTypeName = "varchar"; // Act var clientType = m_resolver.Resolve(dbTypeName); // Assert Assert.AreEqual(typeof(string), clientType); } [TestMethod] public void TestSqlServerTypeNameToClientTypeResolverForXml() { // Setup var dbTypeName = "xml"; // Act var clientType = m_resolver.Resolve(dbTypeName); // Assert Assert.AreEqual(typeof(string), clientType); } [TestMethod, ExpectedException(typeof(NullReferenceException))] public void ThrowOnExceptionTestSqlServerTypeNameToClientTypeResolverIfDbTypeNameIsNull() { // Act m_resolver.Resolve(null); } } }
using System; namespace custom_attributes { class Program { static void Main(string[] args) { Console.WriteLine("Invoking custom instrumentation"); Transaction(); } [NewRelic.Api.Agent.Transaction] static void Transaction() { Thing(); } [NewRelic.Api.Agent.Trace] static void Thing() { } } }
using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; namespace Acquaintance.ScatterGather { /// <summary> /// A pending scatter/gather operation. Allows the monitoring and control of /// asynchronous responses /// </summary> /// <typeparam name="TResponse"></typeparam> public interface IScatter<TResponse> : IDisposable { /// <summary> /// Get the next response, waiting up to a certain timeout /// </summary> /// <param name="timeout"></param> /// <returns></returns> ScatterResponse<TResponse> GetNextResponse(TimeSpan timeout); /// <summary> /// Get the next response, waiting up to a certain timeout /// </summary> /// <param name="timeoutMs"></param> /// <returns></returns> ScatterResponse<TResponse> GetNextResponse(int timeoutMs); /// <summary> /// Get the next response, waiting up to a default timeout /// </summary> /// <returns></returns> ScatterResponse<TResponse> GetNextResponse(); /// <summary> /// Gather a number of responses, waiting up to a certain timeout /// </summary> /// <param name="max"></param> /// <param name="timeout"></param> /// <returns></returns> IReadOnlyList<ScatterResponse<TResponse>> GatherResponses(int max, TimeSpan timeout); /// <summary> /// Gather a number of responses, waiting up to a default timeout /// </summary> /// <param name="max"></param> /// <returns></returns> IReadOnlyList<ScatterResponse<TResponse>> GatherResponses(int max); /// <summary> /// Attempt to gather all responses, waiting up to a certain timeout /// </summary> /// <param name="timeout"></param> /// <returns></returns> IReadOnlyList<ScatterResponse<TResponse>> GatherResponses(TimeSpan timeout); /// <summary> /// Attempt to gather all responses, waiting up to a default timeout /// </summary> /// <returns></returns> IReadOnlyList<ScatterResponse<TResponse>> GatherResponses(); /// <summary> /// The total number of participants in this scatter /// </summary> int TotalParticipants { get; } /// <summary> /// The number of participants which have provided a result. /// Note that because of the asynchronous nature of this operation, this count /// might be incremented before the response is available to be read. /// </summary> int CompletedParticipants { get; } /// <summary> /// Start a task to get the next response asynchronously /// </summary> /// <param name="timeoutMs"></param> /// <param name="token"></param> /// <returns></returns> Task<TResponse> GetNextResponseAsync(int timeoutMs, CancellationToken token); } }
using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Collections; using System.Linq; using System.IO; using SongFeedReaders; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using SongFeedReaders.Readers.BeatSaver; namespace SongFeedReadersTests.BeatSaverReaderTests { [TestClass] public class ParseSongsFromPage_Tests { static ParseSongsFromPage_Tests() { TestSetup.Initialize(); } [TestMethod] public void Success() { string pageText = File.ReadAllText(@"Data\BeatSaverListPage.json"); Uri uri = null; var songs = BeatSaverReader.ParseSongsFromPage(pageText, uri); Assert.IsTrue(songs.Count == 10); foreach (var song in songs) { Assert.IsFalse(song.DownloadUri == null); Assert.IsFalse(string.IsNullOrEmpty(song.Hash)); Assert.IsFalse(string.IsNullOrEmpty(song.MapperName)); Assert.IsFalse(string.IsNullOrEmpty(song.RawData)); Assert.IsFalse(string.IsNullOrEmpty(song.SongName)); } var firstSong = JObject.Parse(songs.First().RawData); string firstHash = firstSong["hash"]?.Value<string>(); Assert.IsTrue(firstHash == "27639680f92a9588b7cce843fc7aaa0f5dc720f8"); string firstUploader = firstSong["uploader"]?["username"]?.Value<string>(); Assert.IsTrue(firstUploader == "latte"); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; using Windows.UI.Core; using System.Collections.ObjectModel; using Windows.UI.Popups; using Windows.UI.ViewManagement; using Windows.UI.Xaml.Media.Animation; using Windows.Storage; //“空白页”项模板在 http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409 上有介绍 namespace RandomMaster { /// <summary> /// 可用于自身或导航至 Frame 内部的空白页。 /// </summary> public sealed partial class MainPage : Page { private bool isWideMode = false; public NotificationPoint redpoint = Config.redpoint; //private void CurrentWindow_SizeChanged(object sender,Windows.UI.Core.WindowSizeChangedEventArgs e) //{ // if (e.Size.Width >= 720) // VisualStateManager.GoToState(this, "WideState", false); // else // VisualStateManager.GoToState(this, "DefaultState", false); //} protected async override void OnNavigatedTo(NavigationEventArgs e) { //if((string)e.Parameter!="") //{ // QuesManager.isCortanaQuest = true; // MyFrame.Navigate(typeof(ListPage), e.Parameter); //} //else // MyFrame.Navigate(typeof(ListPage)); // ObservableCollection<Ques> Queses = new ObservableCollection<Ques>(); var StringLoader = new Windows.ApplicationModel.Resources.ResourceLoader(); MessageDialog error = new MessageDialog(StringLoader.GetString("App_NoSuchQuestion")); Ques thisQues = null; if ((string)e.Parameter != null && (string)e.Parameter != "") { foreach (Ques s in App.qm.queses) { // Remark: Using NLP to match (but this part has been removed) if (s.question == (string)e.Parameter) { thisQues = s; break; } } if (thisQues != null) MyFrame.Navigate(typeof(Option), thisQues); else { await error.ShowAsync(); var newquestbox = new AddQuesDialogue((string)e.Parameter); await newquestbox.ShowAsync(); } } } public MainPage() { this.InitializeComponent(); this.IconListBox.SelectedIndex = 0; //订阅返回键的响应事件 SystemNavigationManager.GetForCurrentView().BackRequested += App_BackRequested; //订阅窗口的导航事件 MyFrame.Navigated += RootFrame_Navigated; MyFrame.Navigate(typeof(ListPage)); myFrame2.Navigate(typeof(waitPage)); //敞口尺寸变化事件句柄 this.SizeChanged += CurrentWindow_SizeChanged; if (Windows.System.Profile.AnalyticsInfo.VersionInfo.DeviceFamily == "Windows.Mobile") { this.mySplitView.OpenPaneLength = 180; } // Achievement #0 welcome AccomplishmentsManager.ReportAccomplishment(0); } //超变态的窗口尺寸响应函数 private void CurrentWindow_SizeChanged(object sender, SizeChangedEventArgs e) { //宽屏尺寸 if (e.NewSize.Width >= 720 && e.NewSize.Width < 1280) { if (Windows.System.Profile.AnalyticsInfo.VersionInfo.DeviceFamily == "Windows.Mobile") this.mySplitView.OpenPaneLength = 180; VisualStateManager.GoToState(this, "WideState", true); isWideMode = true; Config.isSuperWideMode = false; sideFrameGrid.MaxWidth = 0; //从超宽屏切回时如果frame2有option列表,则切换回来时显示option列表 if (myFrame2.CurrentSourcePageType == typeof(Option)) { DependencyObject nowQues = VisualTreeHelper.GetChild(VisualTreeHelper.GetChild(myFrame2, 0), 0); MyFrame.Navigate(typeof(Option), ((Option)nowQues).thisQues); } myFrame2.Navigate(typeof(waitPage)); } //小屏尺寸 if (e.NewSize.Width < 720) { this.mySplitView.OpenPaneLength = 280; VisualStateManager.GoToState(this, "DefaultState", true); isWideMode = false; Config.isSuperWideMode = false; sideFrameGrid.MaxWidth = 0; //从超宽屏切回时如果frame2有option列表,则切换回来时显示option列表 if (myFrame2.CurrentSourcePageType == typeof(Option)) { DependencyObject nowQues = VisualTreeHelper.GetChild(VisualTreeHelper.GetChild(myFrame2, 0), 0); MyFrame.Navigate(typeof(Option), ((Option)nowQues).thisQues); } myFrame2.Navigate(typeof(waitPage)); } //超大屏尺寸! if (e.NewSize.Width >= 1280) { isWideMode = true; Config.isSuperWideMode = true; if (Windows.System.Profile.AnalyticsInfo.VersionInfo.DeviceFamily == "Windows.Mobile") this.mySplitView.OpenPaneLength = 180; if (MyFrame.CurrentSourcePageType == typeof(ListPage) || MyFrame.CurrentSourcePageType == typeof(Option)) sideFrameGrid.MaxWidth = int.MaxValue; //切换到超宽屏前,若显示的是某问题的选项页面,切换后将此页面显示到旁边,中间显示问题列表 if (MyFrame.CurrentSourcePageType == typeof(Option)) { DependencyObject nowQues = VisualTreeHelper.GetChild(VisualTreeHelper.GetChild(MyFrame, 0), 0); myFrame2.Navigate(typeof(Option), ((Option)nowQues).thisQues); MyFrame.Navigate(typeof(ListPage)); } VisualStateManager.GoToState(this, "WideState", true); } // I suppose no need to collapse (since too much bug on diverse devices) //if (e.NewSize.Height >= 720) // this.menuBackgroungLOGO.Visibility = Visibility.Visible; //else // this.menuBackgroungLOGO.Visibility = Visibility.Collapsed; //menuBackgroungLOGO.Margin = new Thickness(50, Window.Current.CoreWindow.Bounds.Height - 110, -256.934, 0); if (mySplitView.IsPaneOpen) { ((Storyboard)this.Resources["HamburgerMenuImageControl"]).Begin(); } else { ((Storyboard)this.Resources["HamburgerMenuImageControl2"]).Begin(); } } //返回键的响应事件定义 private void App_BackRequested(object sender, BackRequestedEventArgs e) { // 这里面可以任意选择控制哪个Frame // 如果MainPage.xaml中使用了另外的Frame标签进行导航 可在此处获取需要GoBack的Frame var rootFrame = MyFrame; //var currentPage = rootFrame.CurrentSourcePageType; //// ReSharper disable once PossibleNullReferenceException //if (currentPage == typeof(ListPage)) //{ // App.Current.Exit(); //} if (rootFrame.CanGoBack && e.Handled == false) { e.Handled = true; rootFrame.GoBack(); while (rootFrame.CurrentSourcePageType == typeof(Option) && rootFrame.CanGoBack) { e.Handled = true; rootFrame.GoBack(); } } } //导航事件响应的定义 private void RootFrame_Navigated(object sender, NavigationEventArgs e) { // 每次完成导航 确定下是否显示系统后退按钮 // ReSharper disable once PossibleNullReferenceException SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility = MyFrame.BackStack.Any() ? AppViewBackButtonVisibility.Visible : AppViewBackButtonVisibility.Collapsed; //汉堡菜单根据当前FRAME的页面进行指示 if (MyFrame.CurrentSourcePageType == typeof(ListPage)) { this.IconListBox.SelectedIndex = 0; this.configListBox.SelectedItem = null; } else if (MyFrame.CurrentSourcePageType == typeof(Manual)) { this.IconListBox.SelectedIndex = 1; this.configListBox.SelectedItem = null; } else if (MyFrame.CurrentSourcePageType == typeof(Feedback)) { this.IconListBox.SelectedIndex = 3; this.configListBox.SelectedItem = null; } else if (MyFrame.CurrentSourcePageType == typeof(AboutPage)) { this.configListBox.SelectedIndex = 0; this.IconListBox.SelectedItem = null; } else if (MyFrame.CurrentSourcePageType == typeof(EastEggPage)) { this.IconListBox.SelectedIndex = 2; this.configListBox.SelectedItem = null; } } private void HamburgerButton_Click(object sender, RoutedEventArgs e) { if (!mySplitView.IsPaneOpen) ((Storyboard)this.Resources["HamburgerMenuImageControl"]).Begin(); else ((Storyboard)this.Resources["HamburgerMenuImageControl2"]).Begin(); // if (!isWideMode) this.mySplitView.IsPaneOpen = !this.mySplitView.IsPaneOpen; } private void IconListBox_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (HomeListBoxItem.IsSelected) { if (this.mySplitView.IsPaneOpen && (!isWideMode)) { this.mySplitView.IsPaneOpen = !this.mySplitView.IsPaneOpen; } if (Config.isSuperWideMode) { this.sideFrameGrid.MaxWidth = int.MaxValue; myFrame2.Navigate(typeof(waitPage)); } configListBox.SelectedItem = null; MyFrame.Navigate(typeof(ListPage)); } if (ManualListBoxItem.IsSelected) { if (this.mySplitView.IsPaneOpen && (!isWideMode)) { this.mySplitView.IsPaneOpen = !this.mySplitView.IsPaneOpen; } this.sideFrameGrid.MaxWidth = 0; configListBox.SelectedItem = null; MyFrame.Navigate(typeof(Manual)); } if (FeedbackListBoxItem.IsSelected) { if (this.mySplitView.IsPaneOpen && (!isWideMode)) { this.mySplitView.IsPaneOpen = !this.mySplitView.IsPaneOpen; } this.sideFrameGrid.MaxWidth = 0; configListBox.SelectedItem = null; MyFrame.Navigate(typeof(Feedback)); } if (FeatureTestBoxItem.IsSelected) { if (this.mySplitView.IsPaneOpen && (!isWideMode)) { this.mySplitView.IsPaneOpen = !this.mySplitView.IsPaneOpen; } this.sideFrameGrid.MaxWidth = 0; configListBox.SelectedItem = null; MyFrame.Navigate(typeof(EastEggPage)); } } private void configListBox_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (configListBoxItem.IsSelected) { if (this.mySplitView.IsPaneOpen && (!isWideMode)) { this.mySplitView.IsPaneOpen = !this.mySplitView.IsPaneOpen; } this.sideFrameGrid.MaxWidth = 0; IconListBox.SelectedItem = null; MyFrame.Navigate(typeof(AboutPage)); } } private void mySplitView_PaneClosing(SplitView sender, SplitViewPaneClosingEventArgs args) { ((Storyboard)this.Resources["HamburgerMenuImageControl2"]).Begin(); } } }
using System; using NUnit.Framework; using SciChart.UI.Reactive.Observability; namespace SciChart.UI.Reactive.Tests.Observability { [TestFixture] public class ObservablePropertyTests { public class SomeClass { public SomeClass() { SomeProp = new ObservableProperty<string>(); } public ObservableProperty<string> SomeProp { get; } } [Test] public void ShouldGetSetProperty() { var test = new SomeClass(); test.SomeProp.SetValue("Hello"); string receivedValue = null; var token = test.SomeProp.Subscribe(t => receivedValue = t); Assert.That(receivedValue, Is.EqualTo("Hello")); test.SomeProp.SetValue("World"); Assert.That(receivedValue, Is.EqualTo("World")); token.Dispose(); test.SomeProp.SetValue("..."); Assert.That(receivedValue, Is.EqualTo("World")); } } }
//---------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. //---------------------------------------------------------------- namespace System.Activities.Statements { using System.Activities; using System.Activities.Expressions; using System.Activities.Persistence; using System.Activities.Tracking; using System.Activities.Validation; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; using System.Threading; using System.Transactions; using System.Xml.Linq; using System.Workflow.Runtime; using System.Workflow.ComponentModel.Compiler; using ValidationError = System.Activities.Validation.ValidationError; using System.Workflow.Runtime.Hosting; using System.Workflow.Activities; using System.Runtime.Serialization; [SuppressMessage("Microsoft.Naming", "CA1724:TypeNamesShouldNotMatchNamespaces", Justification = "The type name 'Interop' conflicts in whole or in part with the namespace name 'System.Web.Services.Interop' - not common usage")] [Obsolete("The WF3 Types are deprecated. Instead, please use the new WF4 Types from System.Activities.*")] public sealed class Interop : NativeActivity, ICustomTypeDescriptor { static Func<TimerExtension> getDefaultTimerExtension = new Func<TimerExtension>(GetDefaultTimerExtension); static Func<InteropPersistenceParticipant> getInteropPersistenceParticipant = new Func<InteropPersistenceParticipant>(GetInteropPersistenceParticipant); Dictionary<string, Argument> properties; Dictionary<string, object> metaProperties; System.Workflow.ComponentModel.Activity v1Activity; IList<PropertyInfo> outputPropertyDefinitions; HashSet<string> extraDynamicArguments; bool exposedBodyPropertiesCacheIsValid; IList<InteropProperty> exposedBodyProperties; Variable<InteropExecutor> interopActivityExecutor; Variable<RuntimeTransactionHandle> runtimeTransactionHandle; BookmarkCallback onResumeBookmark; CompletionCallback onPersistComplete; BookmarkCallback onTransactionComplete; Type activityType; Persist persistActivity; internal const string InArgumentSuffix = "In"; internal const string OutArgumentSuffix = "Out"; Variable<bool> persistOnClose; Variable<InteropEnlistment> interopEnlistment; Variable<Exception> outstandingException; object thisLock; // true if the body type is a valid activity. used so we can have delayed validation support in the designer bool hasValidBody; // true if the V3 activity property names will conflict with our generated argument names bool hasNameCollision; public Interop() : base() { this.interopActivityExecutor = new Variable<InteropExecutor>(); this.runtimeTransactionHandle = new Variable<RuntimeTransactionHandle>(); this.persistOnClose = new Variable<bool>(); this.interopEnlistment = new Variable<InteropEnlistment>(); this.outstandingException = new Variable<Exception>(); this.onResumeBookmark = new BookmarkCallback(this.OnResumeBookmark); this.persistActivity = new Persist(); this.thisLock = new object(); base.Constraints.Add(ProcessAdvancedConstraints()); } [DefaultValue(null)] public Type ActivityType { get { return this.activityType; } set { if (value != this.activityType) { this.hasValidBody = false; if (value != null) { if (typeof(System.Workflow.ComponentModel.Activity).IsAssignableFrom(value) && value.GetConstructor(Type.EmptyTypes) != null) { this.hasValidBody = true; } } this.activityType = value; if (this.metaProperties != null) { this.metaProperties.Clear(); } if (this.outputPropertyDefinitions != null) { this.outputPropertyDefinitions.Clear(); } if (this.properties != null) { this.properties.Clear(); } if (this.exposedBodyProperties != null) { for (int i = 0; i < this.exposedBodyProperties.Count; i++) { this.exposedBodyProperties[i].Invalidate(); } this.exposedBodyProperties.Clear(); } this.exposedBodyPropertiesCacheIsValid = false; this.v1Activity = null; } } } [Browsable(false)] public IDictionary<string, Argument> ActivityProperties { get { if (this.properties == null) { this.properties = new Dictionary<string, Argument>(); } return this.properties; } } [Browsable(false)] public IDictionary<string, object> ActivityMetaProperties { get { if (this.metaProperties == null) { this.metaProperties = new Dictionary<string, object>(); } return this.metaProperties; } } protected override bool CanInduceIdle { get { return true; } } internal System.Workflow.ComponentModel.Activity ComponentModelActivity { get { if (this.v1Activity == null && this.ActivityType != null) { Debug.Assert(this.hasValidBody, "should only be called when we have a valid body"); this.v1Activity = CreateActivity(); } return this.v1Activity; } } internal IList<PropertyInfo> OutputPropertyDefinitions { get { return this.outputPropertyDefinitions; } } internal bool HasNameCollision { get { return this.hasNameCollision; } } protected override void CacheMetadata(NativeActivityMetadata metadata) { if (this.extraDynamicArguments != null) { this.extraDynamicArguments.Clear(); } this.v1Activity = null; if (this.hasValidBody) { //Cache the output properties prop info for look up. this.outputPropertyDefinitions = new List<PropertyInfo>(); //Cache the extra property definitions for look up in OnOpen if (this.properties != null) { if (this.extraDynamicArguments == null) { this.extraDynamicArguments = new HashSet<string>(); } foreach (string name in properties.Keys) { this.extraDynamicArguments.Add(name); } } //Create matched pair of RuntimeArguments for every property: Property (InArgument) & PropertyOut (Argument) PropertyInfo[] bodyProperties = this.ActivityType.GetProperties(); // recheck for name collisions this.hasNameCollision = InteropEnvironment.ParameterHelper.HasPropertyNameCollision(bodyProperties); foreach (PropertyInfo propertyInfo in bodyProperties) { if (InteropEnvironment.ParameterHelper.IsBindable(propertyInfo)) { string propertyInName; //If there are any Property/PropertyOut name pairs already extant, we fall back to renaming the InArgument half of the pair as well if (this.hasNameCollision) { propertyInName = propertyInfo.Name + Interop.InArgumentSuffix; } else { propertyInName = propertyInfo.Name; } //We always rename the OutArgument half of the pair string propertyOutName = propertyInfo.Name + Interop.OutArgumentSuffix; RuntimeArgument inArgument = new RuntimeArgument(propertyInName, propertyInfo.PropertyType, ArgumentDirection.In); RuntimeArgument outArgument = new RuntimeArgument(propertyOutName, propertyInfo.PropertyType, ArgumentDirection.Out); if (this.properties != null) { Argument inBinding = null; if (this.properties.TryGetValue(propertyInName, out inBinding)) { if (inBinding.Direction != ArgumentDirection.In) { throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, ExecutionStringManager.InteropArgumentDirectionMismatch, propertyInName, propertyOutName)); } this.extraDynamicArguments.Remove(propertyInName); metadata.Bind(inBinding, inArgument); } Argument outBinding = null; if (this.properties.TryGetValue(propertyOutName, out outBinding)) { this.extraDynamicArguments.Remove(propertyOutName); metadata.Bind(outBinding, outArgument); } } metadata.AddArgument(inArgument); metadata.AddArgument(outArgument); this.outputPropertyDefinitions.Add(propertyInfo); } } } metadata.SetImplementationVariablesCollection( new Collection<Variable> { this.interopActivityExecutor, this.runtimeTransactionHandle, this.persistOnClose, this.interopEnlistment, this.outstandingException }); metadata.AddImplementationChild(this.persistActivity); if (!this.hasValidBody) { if (this.ActivityType == null) { metadata.AddValidationError(string.Format(CultureInfo.CurrentCulture, ExecutionStringManager.InteropBodyNotSet, this.DisplayName)); } else { // Body needs to be a WF 3.0 activity if (!typeof(System.Workflow.ComponentModel.Activity).IsAssignableFrom(this.ActivityType)) { metadata.AddValidationError(string.Format(CultureInfo.CurrentCulture, ExecutionStringManager.InteropWrongBody, this.DisplayName)); } // and have a default ctor if (this.ActivityType.GetConstructor(Type.EmptyTypes) == null) { metadata.AddValidationError(string.Format(CultureInfo.CurrentCulture, ExecutionStringManager.InteropBodyMustHavePublicDefaultConstructor, this.DisplayName)); } } } else { if (this.extraDynamicArguments != null && this.extraDynamicArguments.Count > 0) { metadata.AddValidationError(string.Format(CultureInfo.CurrentCulture, ExecutionStringManager.AttemptToBindUnknownProperties, this.DisplayName, this.extraDynamicArguments.First())); } else { try { InitializeMetaProperties(this.ComponentModelActivity); // We call InitializeDefinitionForRuntime in the first call to execute to // make sure it only happens once. } catch (InvalidOperationException e) { metadata.AddValidationError(e.Message); } } } metadata.AddDefaultExtensionProvider(getDefaultTimerExtension); metadata.AddDefaultExtensionProvider(getInteropPersistenceParticipant); } static TimerExtension GetDefaultTimerExtension() { return new DurableTimerExtension(); } static InteropPersistenceParticipant GetInteropPersistenceParticipant() { return new InteropPersistenceParticipant(); } protected override void Execute(NativeActivityContext context) { // WorkflowRuntimeService workflowRuntimeService = context.GetExtension<WorkflowRuntimeService>(); if (workflowRuntimeService != null && !(workflowRuntimeService is ExternalDataExchangeService)) { throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, ExecutionStringManager.InteropWorkflowRuntimeServiceNotSupported)); } lock (this.thisLock) { ((System.Workflow.ComponentModel.IDependencyObjectAccessor)this.ComponentModelActivity).InitializeDefinitionForRuntime(null); } if (!this.ComponentModelActivity.Enabled) { return; } System.Workflow.ComponentModel.Activity activityInstance = CreateActivity(); InitializeMetaProperties(activityInstance); activityInstance.SetValue(WorkflowExecutor.WorkflowInstanceIdProperty, context.WorkflowInstanceId); InteropExecutor interopExecutor = new InteropExecutor(context.WorkflowInstanceId, activityInstance, this.OutputPropertyDefinitions, this.ComponentModelActivity); if (!interopExecutor.HasCheckedForTrackingParticipant) { interopExecutor.TrackingEnabled = (context.GetExtension<TrackingParticipant>() != null); interopExecutor.HasCheckedForTrackingParticipant = true; } this.interopActivityExecutor.Set(context, interopExecutor); //Register the Handle as an execution property so that we can call GetCurrentTransaction or //RequestTransactionContext on it later RuntimeTransactionHandle runtimeTransactionHandle = this.runtimeTransactionHandle.Get(context); context.Properties.Add(runtimeTransactionHandle.ExecutionPropertyName, runtimeTransactionHandle); try { using (new ServiceEnvironment(activityInstance)) { using (InteropEnvironment interopEnvironment = new InteropEnvironment( interopExecutor, context, this.onResumeBookmark, this, runtimeTransactionHandle.GetCurrentTransaction(context))) { interopEnvironment.Execute(this.ComponentModelActivity, context); } } } catch (Exception exception) { if (WorkflowExecutor.IsIrrecoverableException(exception) || !this.persistOnClose.Get(context)) { throw; } // We are not ----ing the exception. The exception is saved in this.outstandingException. // We will throw the exception from OnPersistComplete. } } protected override void Cancel(NativeActivityContext context) { InteropExecutor interopExecutor = this.interopActivityExecutor.Get(context); if (!interopExecutor.HasCheckedForTrackingParticipant) { interopExecutor.TrackingEnabled = (context.GetExtension<TrackingParticipant>() != null); interopExecutor.HasCheckedForTrackingParticipant = true; } interopExecutor.EnsureReload(this); try { using (InteropEnvironment interopEnvironment = new InteropEnvironment( interopExecutor, context, this.onResumeBookmark, this, this.runtimeTransactionHandle.Get(context).GetCurrentTransaction(context))) { interopEnvironment.Cancel(); } } catch (Exception exception) { if (WorkflowExecutor.IsIrrecoverableException(exception) || !this.persistOnClose.Get(context)) { throw; } // We are not ----ing the exception. The exception is saved in this.outstandingException. // We will throw the exception from OnPersistComplete. } } internal void SetOutputArgumentValues(IDictionary<string, object> outputs, NativeActivityContext context) { if ((this.properties != null) && (outputs != null)) { foreach (KeyValuePair<string, object> output in outputs) { Argument argument; if (this.properties.TryGetValue(output.Key, out argument) && argument != null) { if (argument.Direction == ArgumentDirection.Out) { argument.Set(context, output.Value); } } } } } internal IDictionary<string, object> GetInputArgumentValues(NativeActivityContext context) { Dictionary<string, object> arguments = null; if (this.properties != null) { foreach (KeyValuePair<string, Argument> parameter in this.properties) { Argument argument = parameter.Value; if (argument.Direction == ArgumentDirection.In) { if (arguments == null) { arguments = new Dictionary<string, object>(); } arguments.Add(parameter.Key, argument.Get<object>(context)); } } } return arguments; } System.Workflow.ComponentModel.Activity CreateActivity() { Debug.Assert(this.ActivityType != null, "ActivityType must be set by the time we get here"); System.Workflow.ComponentModel.Activity activity = Activator.CreateInstance(this.ActivityType) as System.Workflow.ComponentModel.Activity; Debug.Assert(activity != null, "We should have validated that the type has a default ctor() and derives from System.Workflow.ComponentModel.Activity."); return activity; } void InitializeMetaProperties(System.Workflow.ComponentModel.Activity activity) { Debug.Assert((activity.GetType() == this.ActivityType), "activity must be the same type as this.ActivityType"); if (this.metaProperties != null && this.metaProperties.Count > 0) { foreach (string name in this.metaProperties.Keys) { PropertyInfo property = this.ActivityType.GetProperty(name); if (property == null) { throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, ExecutionStringManager.MetaPropertyDoesNotExist, name, this.ActivityType.FullName)); } property.SetValue(activity, this.metaProperties[name], null); } } } void OnResumeBookmark(NativeActivityContext context, Bookmark bookmark, object state) { InteropExecutor interopExecutor = this.interopActivityExecutor.Get(context); if (!interopExecutor.HasCheckedForTrackingParticipant) { interopExecutor.TrackingEnabled = (context.GetExtension<TrackingParticipant>() != null); interopExecutor.HasCheckedForTrackingParticipant = true; } interopExecutor.EnsureReload(this); try { using (InteropEnvironment interopEnvironment = new InteropEnvironment( interopExecutor, context, this.onResumeBookmark, this, this.runtimeTransactionHandle.Get(context).GetCurrentTransaction(context))) { IComparable queueName = interopExecutor.BookmarkQueueMap[bookmark]; interopEnvironment.EnqueueEvent(queueName, state); } } catch (Exception exception) { if (WorkflowExecutor.IsIrrecoverableException(exception) || !this.persistOnClose.Get(context)) { throw; } // We are not ----ing the exception. The exception is saved in this.outstandingException. // We will throw the exception from OnPersistComplete. } } AttributeCollection ICustomTypeDescriptor.GetAttributes() { return TypeDescriptor.GetAttributes(this, true); } string ICustomTypeDescriptor.GetClassName() { return TypeDescriptor.GetClassName(this, true); } string ICustomTypeDescriptor.GetComponentName() { return TypeDescriptor.GetComponentName(this, true); } TypeConverter ICustomTypeDescriptor.GetConverter() { return TypeDescriptor.GetConverter(this, true); } EventDescriptor ICustomTypeDescriptor.GetDefaultEvent() { return TypeDescriptor.GetDefaultEvent(this, true); } PropertyDescriptor ICustomTypeDescriptor.GetDefaultProperty() { return TypeDescriptor.GetDefaultProperty(this, true); } object ICustomTypeDescriptor.GetEditor(Type editorBaseType) { return TypeDescriptor.GetEditor(this, editorBaseType, true); } EventDescriptorCollection ICustomTypeDescriptor.GetEvents(Attribute[] attributes) { return TypeDescriptor.GetEvents(this, attributes, true); } EventDescriptorCollection ICustomTypeDescriptor.GetEvents() { return TypeDescriptor.GetEvents(this, true); } PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties(Attribute[] attributes) { List<PropertyDescriptor> properties = new List<PropertyDescriptor>(); PropertyDescriptorCollection interopProperties; if (attributes != null) { interopProperties = TypeDescriptor.GetProperties(this, attributes, true); } else { interopProperties = TypeDescriptor.GetProperties(this, true); } for (int i = 0; i < interopProperties.Count; i++) { properties.Add(interopProperties[i]); } if (this.hasValidBody) { // First, cache the full set of body properties if (!this.exposedBodyPropertiesCacheIsValid) { //Create matched pair of RuntimeArguments for every property: Property (InArgument) & PropertyOut (Argument) PropertyInfo[] bodyProperties = this.ActivityType.GetProperties(); // recheck for name collisions this.hasNameCollision = InteropEnvironment.ParameterHelper.HasPropertyNameCollision(bodyProperties); for (int i = 0; i < bodyProperties.Length; i++) { PropertyInfo property = bodyProperties[i]; bool isMetaProperty; if (InteropEnvironment.ParameterHelper.IsBindableOrMetaProperty(property, out isMetaProperty)) { // Propagate the attributes to the PropertyDescriptor, appending a DesignerSerializationVisibility attribute Attribute[] customAttributes = Attribute.GetCustomAttributes(property, true); Attribute[] newAttributes = new Attribute[customAttributes.Length + 1]; customAttributes.CopyTo(newAttributes, 0); newAttributes[customAttributes.Length] = new DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Hidden); if (this.exposedBodyProperties == null) { this.exposedBodyProperties = new List<InteropProperty>(bodyProperties.Length); } if (isMetaProperty) { InteropProperty descriptor = new LiteralProperty(this, property.Name, property.PropertyType, newAttributes); this.exposedBodyProperties.Add(descriptor); } else { InteropProperty inDescriptor; //If there are any Property/PropertyOut name pairs already extant, we fall back to renaming the InArgument half of the pair as well if (this.hasNameCollision) { inDescriptor = new ArgumentProperty(this, property.Name + InArgumentSuffix, Argument.Create(property.PropertyType, ArgumentDirection.In), newAttributes); } else { inDescriptor = new ArgumentProperty(this, property.Name, Argument.Create(property.PropertyType, ArgumentDirection.In), newAttributes); } this.exposedBodyProperties.Add(inDescriptor); //We always rename the OutArgument half of the pair InteropProperty outDescriptor = new ArgumentProperty(this, property.Name + OutArgumentSuffix, Argument.Create(property.PropertyType, ArgumentDirection.Out), newAttributes); this.exposedBodyProperties.Add(outDescriptor); } } } this.exposedBodyPropertiesCacheIsValid = true; } // Now adds body properties, complying with the filter: if (this.exposedBodyProperties != null) { for (int i = 0; i < this.exposedBodyProperties.Count; i++) { PropertyDescriptor descriptor = this.exposedBodyProperties[i]; if (attributes == null || !ShouldFilterProperty(descriptor, attributes)) { properties.Add(descriptor); } } } } return new PropertyDescriptorCollection(properties.ToArray()); } static bool ShouldFilterProperty(PropertyDescriptor property, Attribute[] attributes) { if (attributes == null || attributes.Length == 0) { return false; } for (int i = 0; i < attributes.Length; i++) { Attribute filterAttribute = attributes[i]; Attribute propertyAttribute = property.Attributes[filterAttribute.GetType()]; if (propertyAttribute == null) { if (!filterAttribute.IsDefaultAttribute()) { return true; } } else { if (!filterAttribute.Match(propertyAttribute)) { return true; } } } return false; } PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties() { return ((ICustomTypeDescriptor)this).GetProperties(null); } object ICustomTypeDescriptor.GetPropertyOwner(PropertyDescriptor pd) { InteropProperty intProp = pd as InteropProperty; if (intProp != null) { return intProp.Owner; } else { return this; } } internal void OnClose(NativeActivityContext context, Exception exception) { if (this.persistOnClose.Get(context)) { if (exception == null) { context.ScheduleActivity(this.persistActivity); } else { // The V1 workflow faulted and there is an uncaught exception. We cannot throw // the exception right away because we must Persist in order to process the WorkBatch. // So we are saving the uncaught exception and scheduling the Persist activity with a completion callback. // We will throw the exception from OnPersistComplete. this.outstandingException.Set(context, exception); if (this.onPersistComplete == null) { this.onPersistComplete = new CompletionCallback(this.OnPersistComplete); } context.ScheduleActivity(this.persistActivity, this.onPersistComplete); } } this.interopEnlistment.Set(context, null); } internal void Persist(NativeActivityContext context) { if (this.onPersistComplete == null) { this.onPersistComplete = new CompletionCallback(this.OnPersistComplete); } // If Persist fails for any reason, the workflow aborts context.ScheduleActivity(this.persistActivity, this.onPersistComplete); } internal void OnPersistComplete(NativeActivityContext context, ActivityInstance completedInstance) { this.persistOnClose.Set(context, false); Exception exception = this.outstandingException.Get(context); if (exception != null) { this.outstandingException.Set(context, null); throw exception; } this.Resume(context, null); } internal void CreateTransaction(NativeActivityContext context, TransactionOptions txOptions) { RuntimeTransactionHandle transactionHandle = this.runtimeTransactionHandle.Get(context); Debug.Assert(transactionHandle != null, "RuntimeTransactionHandle is null"); transactionHandle.RequestTransactionContext(context, OnTransactionContextAcquired, txOptions); } void OnTransactionContextAcquired(NativeActivityTransactionContext context, object state) { Debug.Assert(context != null, "ActivityTransactionContext was null"); TransactionOptions txOptions = (TransactionOptions)state; CommittableTransaction transaction = new CommittableTransaction(txOptions); context.SetRuntimeTransaction(transaction); this.Resume(context, transaction); } internal void CommitTransaction(NativeActivityContext context) { if (this.onTransactionComplete == null) { this.onTransactionComplete = new BookmarkCallback(this.OnTransactionComplete); } RuntimeTransactionHandle transactionHandle = this.runtimeTransactionHandle.Get(context); transactionHandle.CompleteTransaction(context, this.onTransactionComplete); } void OnTransactionComplete(NativeActivityContext context, Bookmark bookmark, object state) { this.Resume(context, null); } void Resume(NativeActivityContext context, Transaction transaction) { InteropExecutor interopExecutor = this.interopActivityExecutor.Get(context); if (!interopExecutor.HasCheckedForTrackingParticipant) { interopExecutor.TrackingEnabled = (context.GetExtension<TrackingParticipant>() != null); interopExecutor.HasCheckedForTrackingParticipant = true; } interopExecutor.EnsureReload(this); try { using (InteropEnvironment interopEnvironment = new InteropEnvironment( interopExecutor, context, this.onResumeBookmark, this, transaction)) { interopEnvironment.Resume(); } } catch (Exception exception) { if (WorkflowExecutor.IsIrrecoverableException(exception) || !this.persistOnClose.Get(context)) { throw; } // We are not ----ing the exception. The exception is saved in this.outstandingException. // We will throw the exception from OnPersistComplete. } } internal void AddResourceManager(NativeActivityContext context, VolatileResourceManager resourceManager) { if (Transaction.Current != null && Transaction.Current.TransactionInformation.Status == TransactionStatus.Active) { InteropEnlistment enlistment = this.interopEnlistment.Get(context); if (enlistment == null || !enlistment.IsValid) { enlistment = new InteropEnlistment(Transaction.Current, resourceManager); Transaction.Current.EnlistVolatile(enlistment, EnlistmentOptions.EnlistDuringPrepareRequired); this.interopEnlistment.Set(context, enlistment); } } else { InteropPersistenceParticipant persistenceParticipant = context.GetExtension<InteropPersistenceParticipant>(); persistenceParticipant.Add(this.Id, resourceManager); this.persistOnClose.Set(context, true); } } Constraint ProcessAdvancedConstraints() { DelegateInArgument<Interop> element = new DelegateInArgument<Interop>() { Name = "element" }; DelegateInArgument<ValidationContext> validationContext = new DelegateInArgument<ValidationContext>() { Name = "validationContext" }; DelegateInArgument<Activity> parent = new DelegateInArgument<Activity>() { Name = "parent" }; //This will accumulate all potential violations at the root level. See the use case DIRECT of the Interop spec Variable<HashSet<InteropValidationEnum>> rootValidationDataVar = new Variable<HashSet<InteropValidationEnum>>(context => new HashSet<InteropValidationEnum>()); //This will accumulate all violations at the nested level. See the use case NESTED of the Interop spec Variable<HashSet<InteropValidationEnum>> nestedChildrenValidationDataVar = new Variable<HashSet<InteropValidationEnum>>(context => new HashSet<InteropValidationEnum>()); return new Constraint<Interop> { Body = new ActivityAction<Interop, ValidationContext> { Argument1 = element, Argument2 = validationContext, Handler = new If { Condition = new InArgument<bool>(env => element.Get(env).hasValidBody), Then = new Sequence { Variables = { rootValidationDataVar, nestedChildrenValidationDataVar }, Activities = { //First traverse the interop body and collect all available data for validation. This is done at all levels, DIRECT and NESTED new WalkInteropBodyAndGatherData() { RootLevelValidationData = new InArgument<HashSet<InteropValidationEnum>>(rootValidationDataVar), NestedChildrenValidationData = new InArgument<HashSet<InteropValidationEnum>>(nestedChildrenValidationDataVar), InteropActivity = element }, //This is based off the table in the Interop spec. new ValidateAtRootAndNestedLevels() { RootLevelValidationData = rootValidationDataVar, NestedChildrenValidationData = nestedChildrenValidationDataVar, Interop = element, }, //Traverse the parent chain of the Interop activity to look for specifc violations regarding composition of 3.0 activities within 4.0 activities. //Specifically, // - 3.0 TransactionScope within a 4.0 TransactionScope // - 3.0 PersistOnClose within a 4.0 TransactionScope // new ForEach<Activity> { Values = new GetParentChain { ValidationContext = validationContext, }, Body = new ActivityAction<Activity> { Argument = parent, Handler = new Sequence { Activities = { new If() { Condition = new Or<bool, bool, bool> { Left = new Equal<Type, Type, bool> { Left = new ObtainType { Input = parent, }, Right = new InArgument<Type>(context => typeof(System.Activities.Statements.TransactionScope)) }, Right = new Equal<string, string, bool> { Left = new InArgument<string>(env => parent.Get(env).GetType().FullName), Right = "System.ServiceModel.Activities.TransactedReceiveScope" } }, Then = new Sequence { Activities = { new AssertValidation { //Here we only pass the NestedChildrenValidationData since root level use //of TransactionScope would have already been flagged as an error Assertion = new CheckForTransactionScope() { ValidationResults = nestedChildrenValidationDataVar }, Message = new InArgument<string>(ExecutionStringManager.InteropBodyNestedTransactionScope) }, new AssertValidation { Assertion = new CheckForPersistOnClose() { NestedChildrenValidationData = nestedChildrenValidationDataVar, RootLevelValidationData = rootValidationDataVar }, Message = new InArgument<string>(ExecutionStringManager.InteropBodyNestedPersistOnCloseWithinTransactionScope) }, } }, }, } } } }, new ActivityTreeValidation() { Interop = element } } } } } }; } class ActivityTreeValidation : NativeActivity { public ActivityTreeValidation() { } public InArgument<Interop> Interop { get; set; } protected override void Execute(NativeActivityContext context) { Interop interop = this.Interop.Get(context); if (interop == null) { return; } if (!typeof(System.Workflow.ComponentModel.Activity).IsAssignableFrom(interop.ActivityType)) { return; } System.ComponentModel.Design.ServiceContainer container = new System.ComponentModel.Design.ServiceContainer(); container.AddService(typeof(ITypeProvider), CreateTypeProvider(interop.ActivityType)); ValidationManager manager = new ValidationManager(container); System.Workflow.ComponentModel.Activity interopBody = interop.ComponentModelActivity; using (WorkflowCompilationContext.CreateScope(manager)) { foreach (Validator validator in manager.GetValidators(interop.ActivityType)) { ValidationErrorCollection errors = validator.Validate(manager, interopBody); foreach (System.Workflow.ComponentModel.Compiler.ValidationError error in errors) { Constraint.AddValidationError(context, new ValidationError(error.ErrorText, error.IsWarning, error.PropertyName)); } } } } static TypeProvider CreateTypeProvider(Type rootType) { TypeProvider typeProvider = new TypeProvider(null); typeProvider.SetLocalAssembly(rootType.Assembly); typeProvider.AddAssembly(rootType.Assembly); foreach (AssemblyName assemblyName in rootType.Assembly.GetReferencedAssemblies()) { Assembly referencedAssembly = null; try { referencedAssembly = Assembly.Load(assemblyName); if (referencedAssembly != null) typeProvider.AddAssembly(referencedAssembly); } catch { } if (referencedAssembly == null && assemblyName.CodeBase != null) typeProvider.AddAssemblyReference(assemblyName.CodeBase); } return typeProvider; } } class CheckForTransactionScope : CodeActivity<bool> { public InArgument<HashSet<InteropValidationEnum>> ValidationResults { get; set; } protected override bool Execute(CodeActivityContext context) { HashSet<InteropValidationEnum> validationResults = this.ValidationResults.Get(context); if (validationResults.Contains(InteropValidationEnum.TransactionScope)) { return false; } return true; } } class CheckForPersistOnClose : CodeActivity<bool> { public InArgument<HashSet<InteropValidationEnum>> NestedChildrenValidationData { get; set; } public InArgument<HashSet<InteropValidationEnum>> RootLevelValidationData { get; set; } protected override bool Execute(CodeActivityContext context) { HashSet<InteropValidationEnum> nestedValidationData = this.NestedChildrenValidationData.Get(context); HashSet<InteropValidationEnum> rootValidationData = this.RootLevelValidationData.Get(context); if (nestedValidationData.Contains(InteropValidationEnum.PersistOnClose) || rootValidationData.Contains(InteropValidationEnum.PersistOnClose)) { return false; } return true; } } class ValidateAtRootAndNestedLevels : NativeActivity { public ValidateAtRootAndNestedLevels() { } public InArgument<Interop> Interop { get; set; } public InArgument<HashSet<InteropValidationEnum>> RootLevelValidationData { get; set; } public InArgument<HashSet<InteropValidationEnum>> NestedChildrenValidationData { get; set; } protected override void Execute(NativeActivityContext context) { Interop activity = this.Interop.Get(context); foreach (InteropValidationEnum validationEnum in this.RootLevelValidationData.Get(context)) { //We care to mark PersistOnClose during the walking algorithm because we need to check if it happens under a 4.0 TransactionScopActivity and flag that //That is done later, so skip here. if (validationEnum != InteropValidationEnum.PersistOnClose) { string message = string.Format(CultureInfo.CurrentCulture, ExecutionStringManager.InteropBodyRootLevelViolation, activity.DisplayName, validationEnum.ToString() + "Activity"); Constraint.AddValidationError(context, new ValidationError(message)); } } foreach (InteropValidationEnum validationEnum in this.NestedChildrenValidationData.Get(context)) { //We care to mark PersistOnClose or TransactionScope during the walking algorithm because we need to check if it happens under a 4.0 TransactionScopActivity and flag that //That is done later, so skip here. if ((validationEnum != InteropValidationEnum.PersistOnClose) && (validationEnum != InteropValidationEnum.TransactionScope)) { string message = string.Format(CultureInfo.CurrentCulture, ExecutionStringManager.InteropBodyNestedViolation, activity.DisplayName, validationEnum.ToString() + "Activity"); Constraint.AddValidationError(context, new ValidationError(message)); } } } } class WalkInteropBodyAndGatherData : System.Activities.CodeActivity { public InArgument<Interop> InteropActivity { get; set; } public InArgument<HashSet<InteropValidationEnum>> RootLevelValidationData { get; set; } public InArgument<HashSet<InteropValidationEnum>> NestedChildrenValidationData { get; set; } protected override void Execute(CodeActivityContext context) { Interop interop = this.InteropActivity.Get(context); Debug.Assert(interop != null, "Interop activity is null"); Debug.Assert(interop.hasValidBody, "Interop activity has an invalid body"); System.Workflow.ComponentModel.Activity interopBody = interop.ComponentModelActivity; Debug.Assert(interopBody != null, "Interop Body was null"); HashSet<InteropValidationEnum> validationResults; validationResults = this.RootLevelValidationData.Get(context); Debug.Assert(validationResults != null, "The RootLevelValidationData hash set was null"); //Gather data at root level first ProcessAtRootLevel(interopBody, validationResults); validationResults = null; validationResults = this.NestedChildrenValidationData.Get(context); Debug.Assert(validationResults != null, "The NestedChildrenValidationData hash set was null"); //Next, process nested children of the Body if (interopBody is System.Workflow.ComponentModel.CompositeActivity) { ProcessNestedChildren(interopBody, validationResults); } return; } void ProcessAtRootLevel(System.Workflow.ComponentModel.Activity interopBody, HashSet<InteropValidationEnum> validationResults) { Debug.Assert(interopBody != null, "Interop Body is null"); Debug.Assert(validationResults != null, "The HashSet of validation results is null"); if (interopBody.PersistOnClose) { validationResults.Add(InteropValidationEnum.PersistOnClose); } Type interopBodyType = interopBody.GetType(); if (interopBodyType == typeof(System.Workflow.ComponentModel.TransactionScopeActivity)) { validationResults.Add(InteropValidationEnum.TransactionScope); } else if (interopBodyType == typeof(System.Workflow.Activities.CodeActivity)) { validationResults.Add(InteropValidationEnum.Code); } else if (interopBodyType == typeof(System.Workflow.Activities.DelayActivity)) { validationResults.Add(InteropValidationEnum.Delay); } else if (interopBodyType == typeof(System.Workflow.Activities.InvokeWebServiceActivity)) { validationResults.Add(InteropValidationEnum.InvokeWebService); } else if (interopBodyType == typeof(System.Workflow.Activities.InvokeWorkflowActivity)) { validationResults.Add(InteropValidationEnum.InvokeWorkflow); } else if (interopBodyType == typeof(System.Workflow.Activities.PolicyActivity)) { validationResults.Add(InteropValidationEnum.Policy); } else if (interopBodyType.FullName == "System.Workflow.Activities.SendActivity") { validationResults.Add(InteropValidationEnum.Send); } else if (interopBodyType == typeof(System.Workflow.Activities.SetStateActivity)) { validationResults.Add(InteropValidationEnum.SetState); } else if (interopBodyType == typeof(System.Workflow.Activities.WebServiceFaultActivity)) { validationResults.Add(InteropValidationEnum.WebServiceFault); } else if (interopBodyType == typeof(System.Workflow.Activities.WebServiceInputActivity)) { validationResults.Add(InteropValidationEnum.WebServiceInput); } else if (interopBodyType == typeof(System.Workflow.Activities.WebServiceOutputActivity)) { validationResults.Add(InteropValidationEnum.WebServiceOutput); } else if (interopBodyType == typeof(System.Workflow.ComponentModel.CompensateActivity)) { validationResults.Add(InteropValidationEnum.Compensate); } else if (interopBodyType == typeof(System.Workflow.ComponentModel.SuspendActivity)) { validationResults.Add(InteropValidationEnum.Suspend); } else if (interopBodyType == typeof(System.Workflow.ComponentModel.TerminateActivity)) { validationResults.Add(InteropValidationEnum.Terminate); } else if (interopBodyType == typeof(System.Workflow.ComponentModel.ThrowActivity)) { validationResults.Add(InteropValidationEnum.Throw); } else if (interopBodyType == typeof(System.Workflow.Activities.ConditionedActivityGroup)) { validationResults.Add(InteropValidationEnum.ConditionedActivityGroup); } else if (interopBodyType == typeof(System.Workflow.Activities.EventHandlersActivity)) { validationResults.Add(InteropValidationEnum.EventHandlers); } else if (interopBodyType == typeof(System.Workflow.Activities.EventHandlingScopeActivity)) { validationResults.Add(InteropValidationEnum.EventHandlingScope); } else if (interopBodyType == typeof(System.Workflow.Activities.IfElseActivity)) { validationResults.Add(InteropValidationEnum.IfElse); } else if (interopBodyType == typeof(System.Workflow.Activities.ListenActivity)) { validationResults.Add(InteropValidationEnum.Listen); } else if (interopBodyType == typeof(System.Workflow.Activities.ParallelActivity)) { validationResults.Add(InteropValidationEnum.Parallel); } else if (interopBodyType == typeof(System.Workflow.Activities.ReplicatorActivity)) { validationResults.Add(InteropValidationEnum.Replicator); } else if (interopBodyType == typeof(System.Workflow.Activities.SequenceActivity)) { validationResults.Add(InteropValidationEnum.Sequence); } else if (interopBodyType == typeof(System.Workflow.Activities.CompensatableSequenceActivity)) { validationResults.Add(InteropValidationEnum.CompensatableSequence); } else if (interopBodyType == typeof(System.Workflow.Activities.EventDrivenActivity)) { validationResults.Add(InteropValidationEnum.EventDriven); } else if (interopBodyType == typeof(System.Workflow.Activities.IfElseBranchActivity)) { validationResults.Add(InteropValidationEnum.IfElseBranch); } else if (interopBodyType.FullName == "System.Workflow.Activities.ReceiveActivity") { validationResults.Add(InteropValidationEnum.Receive); } else if (interopBodyType == typeof(System.Workflow.Activities.SequentialWorkflowActivity)) { validationResults.Add(InteropValidationEnum.SequentialWorkflow); } else if (interopBodyType == typeof(System.Workflow.Activities.StateFinalizationActivity)) { validationResults.Add(InteropValidationEnum.StateFinalization); } else if (interopBodyType == typeof(System.Workflow.Activities.StateInitializationActivity)) { validationResults.Add(InteropValidationEnum.StateInitialization); } else if (interopBodyType == typeof(System.Workflow.Activities.StateActivity)) { validationResults.Add(InteropValidationEnum.State); } else if (interopBodyType == typeof(System.Workflow.Activities.StateMachineWorkflowActivity)) { validationResults.Add(InteropValidationEnum.StateMachineWorkflow); } else if (interopBodyType == typeof(System.Workflow.Activities.WhileActivity)) { validationResults.Add(InteropValidationEnum.While); } else if (interopBodyType == typeof(System.Workflow.ComponentModel.CancellationHandlerActivity)) { validationResults.Add(InteropValidationEnum.CancellationHandler); } else if (interopBodyType == typeof(System.Workflow.ComponentModel.CompensatableTransactionScopeActivity)) { validationResults.Add(InteropValidationEnum.CompensatableTransactionScope); } else if (interopBodyType == typeof(System.Workflow.ComponentModel.CompensationHandlerActivity)) { validationResults.Add(InteropValidationEnum.CompensationHandler); } else if (interopBodyType == typeof(System.Workflow.ComponentModel.FaultHandlerActivity)) { validationResults.Add(InteropValidationEnum.FaultHandler); } else if (interopBodyType == typeof(System.Workflow.ComponentModel.FaultHandlersActivity)) { validationResults.Add(InteropValidationEnum.FaultHandlers); } else if (interopBodyType == typeof(System.Workflow.ComponentModel.SynchronizationScopeActivity)) { validationResults.Add(InteropValidationEnum.SynchronizationScope); } else if (interopBodyType == typeof(System.Workflow.ComponentModel.ICompensatableActivity)) { validationResults.Add(InteropValidationEnum.ICompensatable); } } void ProcessNestedChildren(System.Workflow.ComponentModel.Activity interopBody, HashSet<InteropValidationEnum> validationResults) { Debug.Assert(interopBody != null, "Interop Body is null"); Debug.Assert(validationResults != null, "The HashSet of validation results is null"); bool persistOnClose = false; foreach (System.Workflow.ComponentModel.Activity activity in interopBody.CollectNestedActivities()) { if (activity.PersistOnClose) { persistOnClose = true; } if (activity is System.Workflow.ComponentModel.TransactionScopeActivity) { validationResults.Add(InteropValidationEnum.TransactionScope); } else if (activity is System.Workflow.Activities.InvokeWorkflowActivity) { validationResults.Add(InteropValidationEnum.InvokeWorkflow); } // SendActivity is sealed else if (activity.GetType().FullName == "System.Workflow.Activities.SendActivity") { validationResults.Add(InteropValidationEnum.Send); } else if (activity is System.Workflow.Activities.WebServiceFaultActivity) { validationResults.Add(InteropValidationEnum.WebServiceFault); } else if (activity is System.Workflow.Activities.WebServiceInputActivity) { validationResults.Add(InteropValidationEnum.WebServiceInput); } else if (activity is System.Workflow.Activities.WebServiceOutputActivity) { validationResults.Add(InteropValidationEnum.WebServiceOutput); } else if (activity is System.Workflow.ComponentModel.CompensateActivity) { validationResults.Add(InteropValidationEnum.Compensate); } else if (activity is System.Workflow.ComponentModel.SuspendActivity) { validationResults.Add(InteropValidationEnum.Suspend); } else if (activity is System.Workflow.Activities.CompensatableSequenceActivity) { validationResults.Add(InteropValidationEnum.CompensatableSequence); } // ReceiveActivity is sealed else if (activity.GetType().FullName == "System.Workflow.Activities.ReceiveActivity") { validationResults.Add(InteropValidationEnum.Receive); } else if (activity is System.Workflow.ComponentModel.CompensatableTransactionScopeActivity) { validationResults.Add(InteropValidationEnum.CompensatableTransactionScope); } else if (activity is System.Workflow.ComponentModel.CompensationHandlerActivity) { validationResults.Add(InteropValidationEnum.CompensationHandler); } else if (activity is System.Workflow.ComponentModel.ICompensatableActivity) { validationResults.Add(InteropValidationEnum.ICompensatable); } } if (persistOnClose) { validationResults.Add(InteropValidationEnum.PersistOnClose); } } } //This needs to be in sync with the table in the spec //We use this internally to keep a hashset of validation data enum InteropValidationEnum { Code, Delay, InvokeWebService, InvokeWorkflow, Policy, Send, SetState, WebServiceFault, WebServiceInput, WebServiceOutput, Compensate, Suspend, ConditionedActivityGroup, EventHandlers, EventHandlingScope, IfElse, Listen, Parallel, Replicator, Sequence, CompensatableSequence, EventDriven, IfElseBranch, Receive, SequentialWorkflow, StateFinalization, StateInitialization, State, StateMachineWorkflow, While, CancellationHandler, CompensatableTransactionScope, CompensationHandler, FaultHandler, FaultHandlers, SynchronizationScope, TransactionScope, ICompensatable, PersistOnClose, Terminate, Throw } class ObtainType : CodeActivity<Type> { public ObtainType() { } public InArgument<Activity> Input { get; set; } protected override Type Execute(CodeActivityContext context) { return this.Input.Get(context).GetType(); } } abstract class InteropProperty : PropertyDescriptor { Interop owner; bool isValid; public InteropProperty(Interop owner, string name, Attribute[] propertyInfoAttributes) : base(name, propertyInfoAttributes) { this.owner = owner; this.isValid = true; } public override Type ComponentType { get { ThrowIfInvalid(); return this.owner.GetType(); } } protected internal Interop Owner { get { return this.owner; } } public override bool CanResetValue(object component) { ThrowIfInvalid(); return false; } public override void ResetValue(object component) { ThrowIfInvalid(); } public override bool ShouldSerializeValue(object component) { ThrowIfInvalid(); return false; } protected void ThrowIfInvalid() { if (!this.isValid) { throw new InvalidOperationException(ExecutionStringManager.InteropInvalidPropertyDescriptor); } } internal void Invalidate() { this.isValid = false; } } class ArgumentProperty : InteropProperty { string argumentName; Argument argument; public ArgumentProperty(Interop owner, string argumentName, Argument argument, Attribute[] attributes) : base(owner, argumentName, attributes) { this.argumentName = argumentName; this.argument = argument; } public override bool IsReadOnly { get { ThrowIfInvalid(); return false; } } public override Type PropertyType { get { ThrowIfInvalid(); return GetArgument().GetType(); } } public override object GetValue(object component) { ThrowIfInvalid(); return GetArgument(); } public override void SetValue(object component, object value) { ThrowIfInvalid(); if (value != null) { this.Owner.ActivityProperties[this.argumentName] = (Argument)value; } else { this.Owner.ActivityProperties.Remove(this.argumentName); } } Argument GetArgument() { Argument argument; if (!this.Owner.ActivityProperties.TryGetValue(this.argumentName, out argument)) { argument = this.argument; } return argument; } } class LiteralProperty : InteropProperty { string literalName; Type literalType; public LiteralProperty(Interop owner, string literalName, Type literalType, Attribute[] attributes) : base(owner, literalName, attributes) { this.literalName = literalName; this.literalType = literalType; } public override bool IsReadOnly { get { ThrowIfInvalid(); return false; } } public override Type PropertyType { get { ThrowIfInvalid(); return this.literalType; } } public override object GetValue(object component) { ThrowIfInvalid(); return GetLiteral(); } public override void SetValue(object component, object value) { ThrowIfInvalid(); this.Owner.ActivityMetaProperties[this.literalName] = value; } object GetLiteral() { object literal; if (this.Owner.ActivityMetaProperties.TryGetValue(this.literalName, out literal)) { return literal; } else { return null; } } } class InteropPersistenceParticipant : PersistenceIOParticipant { public InteropPersistenceParticipant() : base(true, false) { this.ResourceManagers = new Dictionary<string, VolatileResourceManager>(); this.CommittedResourceManagers = new Dictionary<Transaction, Dictionary<string, VolatileResourceManager>>(); } Dictionary<string, VolatileResourceManager> ResourceManagers { get; set; } Dictionary<Transaction, Dictionary<string, VolatileResourceManager>> CommittedResourceManagers { get; set; } protected override IAsyncResult BeginOnSave(IDictionary<XName, object> readWriteValues, IDictionary<System.Xml.Linq.XName, object> writeOnlyValues, TimeSpan timeout, AsyncCallback callback, object state) { try { foreach (VolatileResourceManager rm in this.ResourceManagers.Values) { rm.Commit(); } } finally { this.CommittedResourceManagers.Add(Transaction.Current, this.ResourceManagers); this.ResourceManagers = new Dictionary<string, VolatileResourceManager>(); Transaction.Current.TransactionCompleted += new TransactionCompletedEventHandler(Current_TransactionCompleted); } return new CompletedAsyncResult(callback, state); } protected override void EndOnSave(IAsyncResult result) { CompletedAsyncResult.End(result); } void Current_TransactionCompleted(object sender, TransactionEventArgs e) { if (e.Transaction.TransactionInformation.Status == TransactionStatus.Committed) { foreach (VolatileResourceManager rm in this.CommittedResourceManagers[e.Transaction].Values) { rm.Complete(); } } else { foreach (VolatileResourceManager rm in this.CommittedResourceManagers[e.Transaction].Values) { rm.ClearAllBatchedWork(); } } this.CommittedResourceManagers.Remove(e.Transaction); } protected override void Abort() { foreach (VolatileResourceManager rm in this.ResourceManagers.Values) { rm.ClearAllBatchedWork(); } this.ResourceManagers = new Dictionary<string, VolatileResourceManager>(); } internal void Add(string activityId, VolatileResourceManager rm) { // Add and OnSave shouldn't be called at the same time. A lock isn't needed here. this.ResourceManagers.Add(activityId, rm); } } [DataContract] class InteropEnlistment : IEnlistmentNotification { VolatileResourceManager resourceManager; Transaction transaction; public InteropEnlistment() { } public InteropEnlistment(Transaction transaction, VolatileResourceManager resourceManager) { this.resourceManager = resourceManager; this.transaction = transaction; this.IsValid = true; } public bool IsValid { get; set; } public void Commit(Enlistment enlistment) { this.resourceManager.Complete(); enlistment.Done(); } public void InDoubt(Enlistment enlistment) { // Following the WF3 runtime behavior - Aborting during InDoubt this.Rollback(enlistment); } public void Prepare(PreparingEnlistment preparingEnlistment) { using (System.Transactions.TransactionScope ts = new System.Transactions.TransactionScope(this.transaction)) { this.resourceManager.Commit(); ts.Complete(); } preparingEnlistment.Prepared(); } public void Rollback(Enlistment enlistment) { this.resourceManager.ClearAllBatchedWork(); enlistment.Done(); } } class CompletedAsyncResult : IAsyncResult { AsyncCallback callback; bool endCalled; ManualResetEvent manualResetEvent; object state; object thisLock; public CompletedAsyncResult(AsyncCallback callback, object state) { this.callback = callback; this.state = state; this.thisLock = new object(); if (callback != null) { try { callback(this); } catch (Exception e) // transfer to another thread, this is a fatal situation { throw new InvalidProgramException(ExecutionStringManager.AsyncCallbackThrewException, e); } } } public static void End(IAsyncResult result) { if (result == null) { throw new ArgumentNullException("result"); } CompletedAsyncResult asyncResult = result as CompletedAsyncResult; if (asyncResult == null) { throw new ArgumentException(ExecutionStringManager.InvalidAsyncResult, "result"); } if (asyncResult.endCalled) { throw new InvalidOperationException(ExecutionStringManager.EndCalledTwice); } asyncResult.endCalled = true; if (asyncResult.manualResetEvent != null) { asyncResult.manualResetEvent.Close(); } } public object AsyncState { get { return state; } } public WaitHandle AsyncWaitHandle { get { if (this.manualResetEvent != null) { return this.manualResetEvent; } lock (ThisLock) { if (this.manualResetEvent == null) { this.manualResetEvent = new ManualResetEvent(true); } } return this.manualResetEvent; } } public bool CompletedSynchronously { get { return true; } } public bool IsCompleted { get { return true; } } object ThisLock { get { return this.thisLock; } } } } }
namespace ChatCommon { public class ChatMessageResponse { public ChatUser User { get; } public string Message { get; } public ChatMessageResponse(ChatUser user, string message) { User = user; Message = message; } } }
namespace MultiControlDocking { partial class ContentInput { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.kryptonPanel = new Krypton.Toolkit.KryptonPanel(); this.kryptonButton1 = new Krypton.Toolkit.KryptonButton(); this.kryptonNumericUpDown1 = new Krypton.Toolkit.KryptonNumericUpDown(); this.kryptonLabel3 = new Krypton.Toolkit.KryptonLabel(); this.kryptonTextBox2 = new Krypton.Toolkit.KryptonTextBox(); this.kryptonLabel2 = new Krypton.Toolkit.KryptonLabel(); this.kryptonTextBox1 = new Krypton.Toolkit.KryptonTextBox(); this.kryptonLabel1 = new Krypton.Toolkit.KryptonLabel(); ((System.ComponentModel.ISupportInitialize)(this.kryptonPanel)).BeginInit(); this.kryptonPanel.SuspendLayout(); this.SuspendLayout(); // // kryptonPanel // this.kryptonPanel.Controls.Add(this.kryptonButton1); this.kryptonPanel.Controls.Add(this.kryptonNumericUpDown1); this.kryptonPanel.Controls.Add(this.kryptonLabel3); this.kryptonPanel.Controls.Add(this.kryptonTextBox2); this.kryptonPanel.Controls.Add(this.kryptonLabel2); this.kryptonPanel.Controls.Add(this.kryptonTextBox1); this.kryptonPanel.Controls.Add(this.kryptonLabel1); this.kryptonPanel.Dock = System.Windows.Forms.DockStyle.Fill; this.kryptonPanel.Location = new System.Drawing.Point(0, 0); this.kryptonPanel.Name = "kryptonPanel"; this.kryptonPanel.PanelBackStyle = Krypton.Toolkit.PaletteBackStyle.ControlClient; this.kryptonPanel.Size = new System.Drawing.Size(191, 154); this.kryptonPanel.TabIndex = 0; this.kryptonPanel.MouseDown += new System.Windows.Forms.MouseEventHandler(this.kryptonPanel_MouseDown); // // kryptonButton1 // this.kryptonButton1.Location = new System.Drawing.Point(85, 104); this.kryptonButton1.Name = "kryptonButton1"; this.kryptonButton1.Size = new System.Drawing.Size(81, 25); this.kryptonButton1.TabIndex = 6; this.kryptonButton1.Values.Text = "Update"; // // kryptonNumericUpDown1 // this.kryptonNumericUpDown1.Location = new System.Drawing.Point(85, 66); this.kryptonNumericUpDown1.Name = "kryptonNumericUpDown1"; this.kryptonNumericUpDown1.Size = new System.Drawing.Size(81, 22); this.kryptonNumericUpDown1.TabIndex = 5; this.kryptonNumericUpDown1.Value = new decimal(new int[] { 31, 0, 0, 0}); // // kryptonLabel3 // this.kryptonLabel3.Location = new System.Drawing.Point(45, 66); this.kryptonLabel3.Name = "kryptonLabel3"; this.kryptonLabel3.Size = new System.Drawing.Size(32, 20); this.kryptonLabel3.TabIndex = 4; this.kryptonLabel3.Values.Text = "Age"; // // kryptonTextBox2 // this.kryptonTextBox2.Location = new System.Drawing.Point(85, 40); this.kryptonTextBox2.Name = "kryptonTextBox2"; this.kryptonTextBox2.Size = new System.Drawing.Size(81, 20); this.kryptonTextBox2.TabIndex = 3; this.kryptonTextBox2.Text = "Doe"; // // kryptonLabel2 // this.kryptonLabel2.Location = new System.Drawing.Point(11, 40); this.kryptonLabel2.Name = "kryptonLabel2"; this.kryptonLabel2.Size = new System.Drawing.Size(68, 20); this.kryptonLabel2.TabIndex = 2; this.kryptonLabel2.Values.Text = "Last Name"; // // kryptonTextBox1 // this.kryptonTextBox1.Location = new System.Drawing.Point(85, 14); this.kryptonTextBox1.Name = "kryptonTextBox1"; this.kryptonTextBox1.Size = new System.Drawing.Size(81, 20); this.kryptonTextBox1.TabIndex = 1; this.kryptonTextBox1.Text = "John"; // // kryptonLabel1 // this.kryptonLabel1.Location = new System.Drawing.Point(10, 14); this.kryptonLabel1.Name = "kryptonLabel1"; this.kryptonLabel1.Size = new System.Drawing.Size(69, 20); this.kryptonLabel1.TabIndex = 0; this.kryptonLabel1.Values.Text = "First Name"; // // ContentInput // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add(this.kryptonPanel); this.Name = "ContentInput"; this.Size = new System.Drawing.Size(191, 154); ((System.ComponentModel.ISupportInitialize)(this.kryptonPanel)).EndInit(); this.kryptonPanel.ResumeLayout(false); this.kryptonPanel.PerformLayout(); this.ResumeLayout(false); } #endregion private Krypton.Toolkit.KryptonPanel kryptonPanel; private Krypton.Toolkit.KryptonButton kryptonButton1; private Krypton.Toolkit.KryptonNumericUpDown kryptonNumericUpDown1; private Krypton.Toolkit.KryptonLabel kryptonLabel3; private Krypton.Toolkit.KryptonTextBox kryptonTextBox2; private Krypton.Toolkit.KryptonLabel kryptonLabel2; private Krypton.Toolkit.KryptonTextBox kryptonTextBox1; private Krypton.Toolkit.KryptonLabel kryptonLabel1; } }
#region License // Copyright (c) 2011, ClearCanvas Inc. // All rights reserved. // http://www.clearcanvas.ca // // This software is licensed under the Open Software License v3.0. // For the complete license, see http://www.clearcanvas.ca/OSLv3.0 #endregion using System; using System.Collections.Generic; using ClearCanvas.Common; using ClearCanvas.Desktop; using ClearCanvas.ImageViewer.BaseTools; using ClearCanvas.ImageViewer.Imaging; using ClearCanvas.ImageViewer.RoiGraphics; namespace ClearCanvas.ImageViewer.Tools.ImageProcessing.RoiAnalysis { /// <summary> /// Extension point for views onto <see cref="RoiHistogramComponent"/> /// </summary> [ExtensionPoint] public class RoiHistogramComponentViewExtensionPoint : ExtensionPoint<IApplicationComponentView> {} /// <summary> /// RoiHistogramComponent class /// </summary> [AssociateView(typeof (RoiHistogramComponentViewExtensionPoint))] public class RoiHistogramComponent : RoiAnalysisComponent { private int _minBin = -200; private int _maxBin = 1000; private int _numBins = 100; private int[] _binLabels; private int[] _bins; private bool _autoscale; /// <summary> /// Constructor /// </summary> public RoiHistogramComponent(IImageViewerToolContext imageViewerToolContext) : base(imageViewerToolContext) {} public int MinBin { get { return _minBin; } set { _minBin = value; this.NotifyPropertyChanged("MinBin"); OnAllPropertiesChanged(); } } public int MaxBin { get { return _maxBin; } set { _maxBin = value; this.NotifyPropertyChanged("MaxBin"); OnAllPropertiesChanged(); } } public int NumBins { get { return _numBins; } set { _numBins = value; this.NotifyPropertyChanged("NumBins"); OnAllPropertiesChanged(); } } public bool AutoScale { get { return _autoscale; } set { _autoscale = value; this.NotifyPropertyChanged("AutoScale"); OnAllPropertiesChanged(); } } public int[] BinLabels { get { return _binLabels; } } public int[] Bins { get { return _bins; } } public bool ComputeHistogram() { Roi roi = GetRoi(); if (roi != null) { return ComputeHistogram(roi); } this.Enabled = false; return false; } private bool ComputeHistogram(Roi roi) { // For now, only allow ROIs of grayscale images GrayscalePixelData pixelData = roi.PixelData as GrayscalePixelData; if (pixelData == null) { this.Enabled = false; return false; } int left = (int) Math.Round(roi.BoundingBox.Left); int right = (int) Math.Round(roi.BoundingBox.Right); int top = (int) Math.Round(roi.BoundingBox.Top); int bottom = (int) Math.Round(roi.BoundingBox.Bottom); // If any part of the ROI is outside the bounds of the image, // don't allow a histogram to be displayed since it's invalid. if (left < 0 || left > pixelData.Columns - 1 || right < 0 || right > pixelData.Columns - 1 || top < 0 || top > pixelData.Rows - 1 || bottom < 0 || bottom > pixelData.Rows - 1) { this.Enabled = false; return false; } int[] roiPixelData = new List<int>(roi.GetPixelValues()).ToArray(); Histogram histogram = new Histogram( _minBin, _maxBin, _numBins, roiPixelData); _bins = histogram.Bins; _binLabels = histogram.BinLabels; NotifyPropertyChanged("MinBin"); NotifyPropertyChanged("MaxBin"); NotifyPropertyChanged("NumBins"); this.Enabled = true; return true; } private Roi GetRoi() { RoiGraphic graphic = GetSelectedRoi(); if (graphic == null) return null; return graphic.Roi; } protected override bool CanAnalyzeSelectedRoi() { return GetRoi() != null; } } }
namespace Orc.Controls { using System; using System.Collections.Generic; using System.Text; using System.Windows.Input; public interface ICallout { Guid Id { get; } string Name { get; } string Title { get; } object Tag { get; } bool IsOpen { get; } bool IsClosable { get; } bool HasShown { get; } string Version { get; } TimeSpan ShowTime { get; set; } ICommand Command { get; } event EventHandler<CalloutEventArgs> Showing; event EventHandler<CalloutEventArgs> Hiding; void Show(); void Hide(); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class SoundManager : Singleton<SoundManager> { const float musicChangeTime = 1.0f; public float MasterVolume { get { return _masterVolume; } set { _masterVolume = value; musicSource.volume = _musicVolume * MasterVolume; soundSource.volume = _soundVolume * MasterVolume; } } public float MusicVolume { get { return _musicVolume; } set { _musicVolume = value; musicSource.volume = _musicVolume * MasterVolume; } } public float SoundVolume { get { return _soundVolume; } set { _soundVolume = value; soundSource.volume = _soundVolume * MasterVolume; } } public float _masterVolume; public float _musicVolume; public float _soundVolume; AudioSource musicSource; AudioSource soundSource; Coroutine changeMusicCoroutine; protected SoundManager() { } void Awake() { //TODO: save/load this values _masterVolume = _musicVolume = _soundVolume = 1.0f; soundSource = CreateAS("soundSource"); soundSource.volume = SoundVolume * MasterVolume; musicSource = CreateAS("musicSource"); musicSource.volume = MusicVolume * MasterVolume; AudioSource CreateAS(string name) { GameObject soundgo = new GameObject(); soundgo.transform.parent = transform; soundgo.name = name; return soundgo.AddComponent<AudioSource>(); } } public void PlaySound(AudioClip clip) { soundSource.PlayOneShot(clip); } public void PlayMusic(AudioClip music) { changeMusicCoroutine = StartCoroutine(ChangeMusic()); IEnumerator ChangeMusic() { float timer = musicChangeTime; float startMusicVolume = musicSource.volume; while ((timer -= Time.deltaTime) > 0) { musicSource.volume = startMusicVolume * timer / musicChangeTime; yield return null; } yield return null; musicSource.Stop(); yield return null; musicSource.volume = MusicVolume * MasterVolume; musicSource.clip = music; musicSource.Play(); } } }
using System; using System.Reflection; using System.Runtime.CompilerServices; [assembly: AssemblyVersion ("1.0.0.0")] [assembly: AssemblyCulture ("en-US")] public class Lang { }
using WatiN.Core; namespace Coypu.Drivers.Watin { internal class WatiNElement : Element { internal WatiNElement(WatiN.Core.Element watinElement) { Native = watinElement; } private T GetNativeWatiNElement<T>() where T : WatiN.Core.Element { return Native as T; } private WatiN.Core.Element NativeWatiNElement { get { return GetNativeWatiNElement<WatiN.Core.Element>(); } } public override string Id { get { return NativeWatiNElement.Id; } } public override string Text { get { var text = NativeWatiNElement.Text ?? NativeWatiNElement.OuterText; return text != null ? text.Trim() : null; } } public override string Value { get { var textField = GetNativeWatiNElement<TextField>(); return textField != null ? textField.Value : this["value"]; } } public override string Name { get { return NativeWatiNElement.Name; } } public override string SelectedOption { get { var selectList = GetNativeWatiNElement<SelectList>(); return selectList != null ? selectList.SelectedOption.Text : string.Empty; } } public override bool Selected { get { var checkbox = GetNativeWatiNElement<CheckBox>(); if (checkbox != null) return checkbox.Checked; var radioButton = GetNativeWatiNElement<RadioButton>(); if (radioButton != null) return radioButton.Checked; return false; } } public override string this[string attributeName] { get { return NativeWatiNElement.GetAttributeValue(attributeName); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information namespace Dnn.Modules.ResourceManager.Components { using System.Drawing; using Dnn.Modules.ResourceManager.Components.Models; using DotNetNuke.Services.FileSystem; /// <summary> /// Manager for Thumbnails on Resource Manager. /// </summary> public interface IThumbnailsManager { /// <summary> /// Checks if a file has an available thumbnail. /// </summary> /// <param name="fileName">Name of the file.</param> /// <returns>A value indicating wheter the file is available to get a thumbnail.</returns> bool ThumbnailAvailable(string fileName); /// <summary> /// Gets the url of the thumbnail of a file. /// </summary> /// <param name="moduleId">Id of the module.</param> /// <param name="fileId">Id of the file.</param> /// <param name="width">Width of the thumbnail to generate.</param> /// <param name="height">Height of the thumbnail to generate.</param> /// <returns>A string containing the url of the requested thumbnail.</returns> string ThumbnailUrl(int moduleId, int fileId, int width, int height); /// <summary> /// Gets the url of the thumbnail of a file. /// </summary> /// <param name="moduleId">Id of the module.</param> /// <param name="fileId">Id of the file.</param> /// <param name="width">Width of the thumbnail to generate.</param> /// <param name="height">Height of the thumbnail to generate.</param> /// <param name="timestamp">A timestamp string to append to the url for cachebusting.</param> /// <returns>A string containing the url of the requested thumbnail.</returns> string ThumbnailUrl(int moduleId, int fileId, int width, int height, string timestamp); /// <summary> /// Gets the url of the thumbnail of a file. /// </summary> /// <param name="moduleId">Id of the module.</param> /// <param name="fileId">Id of the file.</param> /// <param name="width">Width of the thumbnail to generate.</param> /// <param name="height">Height of the thumbnail to generate.</param> /// <param name="version">The version number of the file.</param> /// <returns>A string containing the url of the requested thumbnail.</returns> string ThumbnailUrl(int moduleId, int fileId, int width, int height, int version); /// <summary> /// Get the thumbnail from an image. /// </summary> /// <param name="imageUrl">Url of the image.</param> /// <param name="width">Width of the thumbnail to generate.</param> /// <param name="height">Height of the thumbnail to generate.</param> /// <returns>The thumbnail of the image, <see cref="ThumbnailContent"/>.</returns> ThumbnailContent GetThumbnailContentFromImageUrl(string imageUrl, int width, int height); /// <summary> /// Get the thumbnail from an image. /// </summary> /// <param name="image">The original image from which to get a thumbnail.</param> /// <param name="width">Width of the thumbnail to generate.</param> /// <param name="height">Height of the thumbnail to generate.</param> /// <param name="crop">If true, will crop the thumbnail image.</param> /// <returns>The thumbnail of the image, <see cref="ThumbnailContent"/>.</returns> ThumbnailContent GetThumbnailContentFromImage(Image image, int width, int height, bool crop = false); /// <summary> /// Get the thumbnail from a file. /// </summary> /// <param name="item">The file from which to get a thumbnail.</param> /// <param name="width">Width of the thumbnail to generate.</param> /// <param name="height">Height of the thumbnail to generate.</param> /// <param name="crop">If true, will crop the thumbnail image.</param> /// <returns>The thumbnail of the file, <see cref="ThumbnailContent"/>.</returns> ThumbnailContent GetThumbnailContent(IFileInfo item, int width, int height, bool crop = false); } }
using System.Collections.Generic; using System.Threading.Tasks; using DeployMe.Api.Models; using DeployMe.Http.WebApiExtensions; using DeployMe.Http.WebApiExtensions.Extensions; using DeployMe.Http.WebApiExtensions.Utility; using Microsoft.AspNetCore.Mvc; using StackExchange.Redis.Extensions.Core.Abstractions; namespace DeployMe.Api.Controllers { [Route("[controller]")] [ApiController] public class AgentsController : Controller, ILogDelegate { public AgentsController(LogDelegate logDelegate, IRedisDatabase redisDatabase) { LogDelegate = logDelegate; RedisDatabase = redisDatabase; } private IRedisDatabase RedisDatabase { get; } public LogDelegate LogDelegate { get; } [HttpGet] public async Task<HttpActionResult<Dictionary<string, AgentInfo>>> List() => await this.WithResponseContainer( async () => await RedisDatabase.HashGetAllAsync<AgentInfo>(CacheKeys.AgentInfo)); } }
using THUnity2D.Interfaces; using THUnity2D.Utility; //所有游戏人物,道具,子弹的基类 namespace THUnity2D.ObjClasses { public enum ObjType { Empty = 0, Wall = 1, Prop = 2, Bullet = 3, BirthPoint = 4, OutOfBoundBlock = 5 } public abstract class Obj : GameObject, IObj //道具,墙 { public override GameObjType GetGameObjType() { return GameObjType.Obj; } protected ObjType objType; public ObjType ObjType => objType; private ICharacter? parent = null; //道具的主人 public ICharacter? Parent { get => parent; set { //Operations.Add lock (gameObjLock) { string debugStr = (value == null ? " has been throwed by " + (parent == null ? "null." : parent.ToString()) : "has been picked by " + (value == null ? "null." : value.ToString())); parent = value; Debugger.Output(this, debugStr); } } } public Obj(XYPosition initPos, int radius, ObjType objType, ShapeType shape) : base(initPos, radius, shape) { this.objType = objType; Debugger.Output(this, " constructed!"); } public override string ToString() { return objType + "->" + ID + ": " + Position.ToString() + " "; } } }
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Text; namespace Master40.DB.DataModel { /* * Previous called MachineGroup, now describes a Skill to do something * owns a list of Resources */ public class M_ResourceSkill : BaseEntity { public string Name { get; set; } /* * Resources, who can provide the required ResourceSkill */ [JsonIgnore] public virtual ICollection<M_ResourceSetup> ResourceSetups { get; set; } } }
namespace BasicMultiplayerGamesCP.Data; public class BasicMultiplayerGamesPlayerItem : SimplePlayer { //anything needed is here }
using MAVN.Service.EligibilityEngine.Client.Enums; namespace MAVN.Service.EligibilityEngine.Client.Models { /// <summary> /// Represents a response model containing error information. /// </summary> public class EligibilityEngineErrorResponseModel { /// <summary> /// The error code. /// </summary> public EligibilityEngineErrors ErrorCode { get; set; } /// <summary> /// The Error Message. /// </summary> public string ErrorMessage { get; set; } } }
namespace TopGearApi.Data.Migrations { using System; using System.Data.Entity.Migrations; public partial class RemoverCarroAgencia : DbMigration { public override void Up() { DropForeignKey("dbo.Carroes", "AgenciaId", "dbo.Agencias"); DropIndex("dbo.Carroes", new[] { "AgenciaId" }); } public override void Down() { CreateIndex("dbo.Carroes", "AgenciaId"); AddForeignKey("dbo.Carroes", "AgenciaId", "dbo.Agencias", "Id", cascadeDelete: true); } } }
using GameRules; using Movement.States; using StateMachine; using UnityEngine; namespace Movement { public class MovementColliderConsumer : MonoBehaviour, ISMOutputConsumer { public int GetPriority() { return 0; } //Make adjustments to the colliders as necessary public void ReceiveOutput(SMOutput output) { float height; float radius; Vector3 center; switch (output.input.state) { case CrouchRun _: case Crouch _: height = 1f; radius = 0.45f; center = Vector3.down; break; default: height = 2f; radius = 0.5f; center = Vector3.zero; break; } PlayerStatus.Instance.CollisionHandler.height = height; PlayerStatus.Instance.CollisionHandler.radius = radius; PlayerStatus.Instance.CollisionHandler.center = center; } } }
using Unity.Entities; using System; using UnityEngine; namespace E7.ECS.LineRenderer { /// <summary> /// This is some properties of the line that could be shared between different lines. /// When line corners and line caps are supported, this component could also be used with them. /// </summary> [Serializable] public struct LineStyle : ISharedComponentData, IEquatable<LineStyle> { public Material material; // /// <summary> // /// WIP : Override billboard camera target. // /// </summary> // public Camera alignWithCamera; // /// <summary> // /// WIP // /// </summary> // public int endCapVertices; // /// <summary> // /// WIP // /// </summary> // public int cornerVertices; public bool Equals(LineStyle other) => ReferenceEquals(material, other.material); public override int GetHashCode() => ReferenceEquals(material, null) ? material.GetHashCode() : 0; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Drawing; namespace pEditorGrafico { class Retangulo : Figura { private Ponto[] vertices; public Ponto[] Vertices { get { return vertices; } //set { vertices = value; } } public Linha[] GetLados() { var lados = new Linha[4]; for (int counter = 0; counter < 4; counter++) lados[counter] = new Linha(this.Vertices[counter], this.Vertices[(counter + 1) % 4]); return lados; } public new Point Posicao // Sobreescreve a propriedade herdada de figura { get { return posicao; } set { var alt = Altura; var larg = Largura; var p = new Ponto(value.X, value.Y); vertices[0] = p; vertices[1] = p + new Ponto(larg, 0); vertices[2] = p + new Ponto(larg, alt); vertices[3] = p + new Ponto(0, alt); } } public int Largura { get { return Convert.ToInt32(vertices[0].GetDistancia(vertices[1])); } set { vertices[1] = vertices[0] + new Ponto(value, 0); vertices[2].X = vertices[1].X; vertices[2].Y = vertices[3].Y; } } public int Altura { get { return Convert.ToInt32(vertices[1].GetDistancia(vertices[2])); } set { vertices[3] = vertices[0] + new Ponto(0, value); vertices[2].Y = vertices[3].Y; vertices[2].X = vertices[3].X; } } public Retangulo(Ponto pos, int largura, int altura) { posicao.X = pos.Posicao.X; posicao.Y = pos.Posicao.Y; vertices = new Ponto[4]; vertices[0] = pos; vertices[1] = pos + new Ponto(largura, 0); vertices[2] = pos + new Ponto(largura, altura); vertices[3] = pos + new Ponto(0, altura); base.corContorno = Color.Black; } public override void desenhar(Graphics g) { var verticePoint = new Point[4]; for (int counter = 0; counter < vertices.Length; counter++) verticePoint[counter] = vertices[counter].ToPoint(); Pen pen = new Pen(CorContorno, espessura); SolidBrush brush = new SolidBrush(CorPreenchimento); //g.DrawPolygon(pen, verticePoint); if (preencher) g.FillPolygon(brush, verticePoint); if(contornar) g.DrawPolygon(pen, verticePoint); } public void Girar(double graus) { Girar(graus, this.GetCentro()); } public void Girar(double graus, Ponto centroDeRotacao) { throw new NotImplementedException(); } public Ponto GetCentro() { throw new NotImplementedException(); } public override bool Contem(Ponto p) //Verifica se o ponto passado por parâmetro está contido na figura { var lados = GetLados(); for (int counter = 0; counter < 4; counter++) if (lados[counter].GetSemiplano(p) == -1) return false; return true; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using DotVVM.Framework.ViewModel; using DotVVM.Framework.Controls; using System.ComponentModel.DataAnnotations; using PhotoGallery.Data.Services; using PhotoGallery.Data.DTO; using DotVVM.Framework.Storage; namespace PhotoGallery.App.ViewModels { public class CreateGalleryViewModel : MasterPageViewModel { private readonly GalleryService galleryService; private readonly IUploadedFileStorage uploadedFileStorage; [Required] public string Title { get; set; } public UploadedFilesCollection Files { get; set; } = new UploadedFilesCollection(); public CreateGalleryViewModel(GalleryService galleryService, IUploadedFileStorage uploadedFileStorage) { this.galleryService = galleryService; this.uploadedFileStorage = uploadedFileStorage; } public async Task CreateGallery() { var gallery = new GalleryNewDTO() { Title = Title, Photos = Files.Files .Select(f => new PhotoNewDTO() { FileName = f.FileName, Stream = uploadedFileStorage.GetFile(f.FileId) }) .ToList() }; try { await galleryService.CreateGallery(gallery); Context.RedirectToRoute("Default"); } finally { foreach (var photo in gallery.Photos) { photo.Stream?.Dispose(); } } } } }
namespace RadeonResetBugFixService.Contracts { using System; interface ILogger : IDisposable { void Log(string message); void LogError(string message); } }
namespace AillieoUtils { public enum ScheduleMode { Dynamic = 0, Static, LongTerm, } }
using System; using System.Collections.Generic; using System.Text; namespace locgen { /// <summary> /// /// </summary> public interface ILocGeneratorSettings { /// <summary> /// Gets or sets the path for the generated file (including file name and extension). /// </summary> string TargetDir { get; set; } /// <summary> /// Gets or sets ident size (in spaces) for the generated file. /// </summary> int IdentSize { get; set; } } }
using Swashbuckle.AspNetCore.SwaggerGen; using System; using Swashbuckle.AspNetCore.Swagger; namespace TinkoffBank.TQM.WebConfiguration.Swagger { class RequiredSchemaFilter : ISchemaFilter { public void Apply(Schema model, SchemaFilterContext context) { if (context.SystemType.IsValueType && !context.SystemType.IsEnum && !context.SystemType.Equals(typeof(bool)) && Nullable.GetUnderlyingType(context.SystemType) == null) model.Extensions.Add("x-nullable", false); } } }
using System; using System.Reactive.Disposables; using Prism.AppModel; using Prism.Navigation; using ReactiveUI; namespace Sample { public abstract class ViewModel : ReactiveObject, IPageLifecycleAware, INavigatingAware { CompositeDisposable disposer; protected CompositeDisposable DisposeWith { get { if (this.disposer == null) this.disposer = new CompositeDisposable(); return this.disposer; } } public virtual void OnAppearing() { } public virtual void OnDisappearing() { this.disposer?.Dispose(); this.disposer = null; } public virtual void OnNavigatingFrom(INavigationParameters parameters) { } public virtual void OnNavigatingTo(INavigationParameters parameters) { } } }
using Com.LuisPedroFonseca.ProCamera2D; using TMPro; using UnityEngine; public class PlayerAttributesController : MonoBehaviour { // Variables #region Variables // Public Variables // -------------------------------- [Header("Player Attributes")] public int playerHealth; // Current player health public int playerHealthMax; // Max player health public float invulnerabilityTimer; // How long the player is invulnerable after hit public float staggerTimer; // How long the player is staggered public float playerRespawnTimer; // How long before the player can respawn after death public AudioClip playerTakingDamage; public AudioClip playerDeathSound; [Header("UI Attributes")] public SimpleHealthBar P1_Health_Bar; public GameObject P1_healthTextHolder; public TextMeshProUGUI P1_curHPText; public TextMeshProUGUI P1_MaxHPText; public TextMeshProUGUI P1_Respawn_Text; public TextMeshProUGUI p1_strText; public SimpleHealthBar P2_Health_Bar; public GameObject P2_healthTextHolder; public TextMeshProUGUI P2_curHPText; public TextMeshProUGUI P2_maxHPText; public TextMeshProUGUI P2_Respawn_Text; public TextMeshProUGUI p2_strText; [Header("Player Combat Values")] public int AttackStrength; // Player attack strength [Header("Player Partner Attributes")] public PlayerAttributesController partner; [HideInInspector] public AudioSource audioSource; [HideInInspector] public ProCamera2D cam; [Header("Pickups")] public LayerMask pickupsCollisionMask; // Private Variables // --------------------------------- // Component references private BoxCollider2D box2d; // Defies player number private int player_number; // invul timer private float invulTimer = 0; // Timer to decrement invul private bool isInvul = false; private float staggeredTimer = 0; private bool isStaggered = false; private float respawnTimer = 0; private bool isPlayerDead = false; #endregion // Private Methods // ------------------------------------ #region private Methods private void Start() { // get rb2d box2d = GetComponent<BoxCollider2D>(); audioSource = GetComponent<AudioSource>(); // Get the camera cam = GameObject.FindGameObjectWithTag("MainCamera").GetComponent<ProCamera2D>(); // Ensures health bars are properly updated updateHealthBars(); // Set respawn text if (player_number == 0) { P1_Respawn_Text.gameObject.SetActive(false); } else { P2_Respawn_Text.gameObject.SetActive(false); } } /// <summary> /// Unity update method /// /// Runs once every frame /// </summary> private void Update() { // Resets invl timer if (invulTimer >= 0 && isInvul) resetInvul(); if (staggeredTimer >= 0 && isStaggered) resetStagger(); if (respawnTimer >= 0 && isPlayerDead) resetRespawn(); // Check for item pickups pickupItem(); } // Item PIckup Methods // ----------------------------------------- private void pickupItem() { // Get current vector2 location of where the attack will start Vector2 rayOrigin = (Vector2)transform.position + new Vector2(box2d.size.x / 2, box2d.size.y / 2); // Create raycast box for checking if enemy has been hit RaycastHit2D hit = Physics2D.BoxCast(rayOrigin, box2d.size, 0, Vector2.zero, 0, pickupsCollisionMask); if (hit) { // Get pickup itemDrop pickup = hit.transform.GetComponent<itemDrop>(); // add on new stats playerHealth += pickup.restoreHealthAmount; playerHealthMax += pickup.permanentHealthIncreaseAmount; AttackStrength += pickup.permanentAttackStrengthIncreaseAmount; // Updates health bars updateHealthBars(); // Destroy object Destroy(pickup.gameObject); } } // stagger invul states // ------------------------------------------ /// <summary> /// Set invul state /// </summary> private void setInvul() { isInvul = true; invulTimer = invulnerabilityTimer; } /// <summary> /// Sets stagger state /// </summary> private void setStagger() { staggeredTimer = staggerTimer; isStaggered = true; } /// <summary> /// Sets player to dead, starts respawn timer /// </summary> private void setRespawn() { respawnTimer = playerRespawnTimer; isPlayerDead = true; // Set respawn text if (player_number == 0) { P1_Respawn_Text.gameObject.SetActive(true); } else { P2_Respawn_Text.gameObject.SetActive(true); } } /// <summary> /// Timer decrements to reset the invulnerability timer /// </summary> private void resetInvul() { // decrement timer invulTimer -= Time.deltaTime; // Set invul to false when timer runs if (invulTimer <= 0) { isInvul = false; } } /// <summary> /// Timer decrements to reset the stagger /// </summary> private void resetStagger() { // decrement timer staggeredTimer -= Time.deltaTime; // set stagger to false is timer runs out if (staggeredTimer <= 0) { isStaggered = false; } } /// <summary> /// Timer decrements to allow for respawning /// </summary> private void resetRespawn() { respawnTimer -= Time.deltaTime; int textTimer = (int)respawnTimer; // Set respawn text if (player_number == 0) { P1_Respawn_Text.text = "Respawning in " + textTimer.ToString() + "..."; } else { P2_Respawn_Text.text = "Respawning in " + textTimer.ToString() + "..."; } if (respawnTimer <= 0) { respawn(); } Debug.Log("Respawning in " + (int)respawnTimer); } #endregion // public Methods // ------------------------------------ #region public Methods /// <summary> /// Player takes damage /// </summary> /// <param name="damageToTake"></param> public void takeDamage(int damageToTake) { if (!isInvul && !isPlayerDead) { // player invulnerable setInvul(); // player staggered setStagger(); // Take damage playerHealth -= damageToTake; // Update UI updateHealthBars(); // Disable player if dead if (playerHealth <= 0) { death(); setRespawn(); } else { audioSource.PlayOneShot(playerTakingDamage); } } } /// <summary> /// Restores health based on an item the player picks up /// </summary> /// <param name="healthToRestore"></param> public void restoreHealth(int healthToRestore) { // if player picks up health restore item and is low enough health to restore it if (playerHealth < playerHealthMax) { // destroy pickup, restore health // Player can overheal a little bit playerHealth += healthToRestore; } } /// <summary> /// Sets called if player dies /// </summary> public void death() { isPlayerDead = true; // Kill player Debug.Log("player died, respawning player"); // play death sound audioSource.PlayOneShot(playerDeathSound); // Remove player from camera cam.RemoveCameraTarget(this.transform); if (player_number == 0) { P1_healthTextHolder.SetActive(false); } else { P2_healthTextHolder.SetActive(false); } } /// <summary> /// respawns player when they've died /// </summary> public void respawn() { Debug.Log("Respawning Player now"); // Return player object from dead //gameObject.SetActive(true); isPlayerDead = false; // restore health playerHealth = playerHealthMax; if (player_number == 0) { P1_healthTextHolder.SetActive(true); } else { P2_healthTextHolder.SetActive(true); } updateHealthBars(); // Set respawn text if (player_number == 0) { P1_Respawn_Text.gameObject.SetActive(false); } else { P2_Respawn_Text.gameObject.SetActive(false); } // set invulnerable setInvul(); // move player next to partner transform.position = partner.transform.position + Vector3.up; // add player to camera cam.AddCameraTarget(this.transform); } /// <summary> /// Updates the player's health bars when called /// </summary> public void updateHealthBars() { // Updates health bars if (player_number == 0) { P1_Health_Bar.UpdateBar(playerHealth, playerHealthMax); P1_curHPText.text = playerHealth.ToString(); P1_MaxHPText.text = playerHealthMax.ToString(); p1_strText.text = AttackStrength.ToString(); } else { P2_Health_Bar.UpdateBar(playerHealth, playerHealthMax); P2_curHPText.text = playerHealth.ToString(); P2_maxHPText.text = playerHealthMax.ToString(); p2_strText.text = AttackStrength.ToString(); } } #endregion #region getters/setters /// <summary> /// Returns if player is invulnerable /// </summary> public bool playerInvulnerable { get { return isInvul; } } /// <summary> /// Returns if player is staggered /// </summary> public bool playerStaggered { get { return isStaggered; } } /// <summary> /// Returns if is dead /// </summary> public bool PlayerDied { get { return isPlayerDead; } } public int currentPlayerNumber { set { player_number = value; } } #endregion }
using System.Diagnostics.CodeAnalysis; using SCUMSLang.SyntaxTree.Definitions; using SCUMSLang.SyntaxTree.References; namespace SCUMSLang.SyntaxTree { internal class ParentBlockFeature : IHasParentBlock { [AllowNull] public BlockContainer ParentBlockContainer { get => parentBlockContainer ??= new BlockContainer(); set => parentBlockContainer = value; } [AllowNull] public BlockDefinition ParentBlock { get => AsParentBlock(ParentBlockContainer.Block); set => ParentBlockContainer.Block = value; } [AllowNull] BlockDefinition IHasParentBlock.ParentBlock { get => ParentBlock; set => ParentBlock = value; } [MemberNotNullWhen(true, nameof(ParentBlock))] public virtual bool HasParentBlock => ParentBlockContainer.HasBlock; private BlockContainer? parentBlockContainer; private readonly Reference owner; public ParentBlockFeature(Reference owner) => this.owner = owner; public BlockDefinition AsParentBlock(BlockDefinition? block) => block ?? throw SyntaxTreeThrowHelper.InvalidOperation(owner); } }
using System; using System.Collections.Generic; using System.Linq; using System.Management; namespace Device { public class DeviceWMI { public string Name { get; set; } public string ClassGUID { get; set; } public List<string> HardwareID { get; set; } public string DeviceID { get; set; } public string PnpDeviceID { get; set; } public DeviceWMI() { } public DeviceWMI(string name, string classGuid, List<string> hardwareID, string deviceID, string pnpDeviceID) { Name = name; ClassGUID = classGuid; HardwareID = hardwareID; DeviceID = deviceID; PnpDeviceID = pnpDeviceID; } public override string ToString() { return $"Name: {Name}{Environment.NewLine}GUID: {ClassGUID}{Environment.NewLine}Device ID: {DeviceID}"; } public static List<DeviceWMI> GetPNPDevicesWithNames(string[] names) { ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_PnPEntity"); List<DeviceWMI> devices = new List<DeviceWMI>(); foreach (ManagementObject queryObj in searcher.Get()) { string name = queryObj["Name"]?.ToString(); if (!string.IsNullOrEmpty(name) && names.Any(p => name.ToLower().Contains(p.ToLower()))) { string guid = queryObj["ClassGuid"].ToString(); var hardwareID = (string[])queryObj["HardwareID"]; string deviceID = queryObj["DeviceID"].ToString(); string pnpDeviceID = queryObj["PNPDeviceID"].ToString(); devices.Add(new DeviceWMI(name, guid, hardwareID.ToList(), deviceID, pnpDeviceID)); } } return devices; } } }